instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ProcessStateChangesPlanB(WebRtcSetDescriptionObserver::States states) { DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kPlanB); std::vector<RTCRtpReceiver*> removed_receivers; for (auto it = handler_->rtp_receivers_.begin(); it != handler_->rtp_receivers_.end(); ++it) { if (ReceiverWasRemoved(*(*it), states.transceiver_states)) removed_receivers.push_back(it->get()); } for (auto& transceiver_state : states.transceiver_states) { if (ReceiverWasAdded(transceiver_state)) { handler_->OnAddReceiverPlanB(transceiver_state.MoveReceiverState()); } } for (auto* removed_receiver : removed_receivers) { handler_->OnRemoveReceiverPlanB(RTCRtpReceiver::getId( removed_receiver->state().webrtc_receiver().get())); } } Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl Bug: 912074 Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8 Reviewed-on: https://chromium-review.googlesource.com/c/1411916 Commit-Queue: Guido Urdaneta <guidou@chromium.org> Reviewed-by: Henrik Boström <hbos@chromium.org> Cr-Commit-Position: refs/heads/master@{#622945} CWE ID: CWE-416
void ProcessStateChangesPlanB(WebRtcSetDescriptionObserver::States states) { DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kPlanB); if (!handler_) return; std::vector<RTCRtpReceiver*> removed_receivers; for (auto it = handler_->rtp_receivers_.begin(); it != handler_->rtp_receivers_.end(); ++it) { if (ReceiverWasRemoved(*(*it), states.transceiver_states)) removed_receivers.push_back(it->get()); } for (auto& transceiver_state : states.transceiver_states) { if (handler_ && ReceiverWasAdded(transceiver_state)) { // |handler_| can become null after this call. handler_->OnAddReceiverPlanB(transceiver_state.MoveReceiverState()); } } for (auto* removed_receiver : removed_receivers) { if (handler_) { // |handler_| can become null after this call. handler_->OnRemoveReceiverPlanB(RTCRtpReceiver::getId( removed_receiver->state().webrtc_receiver().get())); } } }
173,074
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool ParamTraits<FilePath>::Read(const Message* m, PickleIterator* iter, param_type* r) { FilePath::StringType value; if (!ParamTraits<FilePath::StringType>::Read(m, iter, &value)) return false; *r = FilePath(value); return true; } Commit Message: Validate that paths don't contain embedded NULLs at deserialization. BUG=166867 Review URL: https://chromiumcodereview.appspot.com/11743009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@174935 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool ParamTraits<FilePath>::Read(const Message* m, PickleIterator* iter, param_type* r) { FilePath::StringType value; if (!ParamTraits<FilePath::StringType>::Read(m, iter, &value)) return false; // Reject embedded NULs as they can cause security checks to go awry. if (value.find(FILE_PATH_LITERAL('\0')) != FilePath::StringType::npos) return false; *r = FilePath(value); return true; }
171,501
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: string16 ExtensionInstallUI::Prompt::GetDialogTitle( const Extension* extension) const { if (type_ == INSTALL_PROMPT) { return l10n_util::GetStringUTF16(extension->is_app() ? IDS_EXTENSION_INSTALL_APP_PROMPT_TITLE : IDS_EXTENSION_INSTALL_EXTENSION_PROMPT_TITLE); } else if (type_ == INLINE_INSTALL_PROMPT) { return l10n_util::GetStringFUTF16( kTitleIds[type_], l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)); } else { return l10n_util::GetStringUTF16(kTitleIds[type_]); } } Commit Message: [i18n-fixlet] Make strings branding specific in extension code. IDS_EXTENSIONS_UNINSTALL IDS_EXTENSIONS_INCOGNITO_WARNING IDS_EXTENSION_INSTALLED_HEADING IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug. IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/9107061 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
string16 ExtensionInstallUI::Prompt::GetDialogTitle( const Extension* extension) const { if (type_ == INSTALL_PROMPT) { return l10n_util::GetStringUTF16(extension->is_app() ? IDS_EXTENSION_INSTALL_APP_PROMPT_TITLE : IDS_EXTENSION_INSTALL_EXTENSION_PROMPT_TITLE); } else { return l10n_util::GetStringUTF16(kTitleIds[type_]); } }
170,981
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(locale_lookup) { char* fallback_loc = NULL; int fallback_loc_len = 0; const char* loc_range = NULL; int loc_range_len = 0; zval* arr = NULL; HashTable* hash_arr = NULL; zend_bool boolCanonical = 0; char* result =NULL; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "as|bs", &arr, &loc_range, &loc_range_len, &boolCanonical, &fallback_loc, &fallback_loc_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_lookup: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_range_len == 0) { loc_range = intl_locale_get_default(TSRMLS_C); } hash_arr = HASH_OF(arr); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) { RETURN_EMPTY_STRING(); } result = lookup_loc_range(loc_range, hash_arr, boolCanonical TSRMLS_CC); if(result == NULL || result[0] == '\0') { if( fallback_loc ) { result = estrndup(fallback_loc, fallback_loc_len); } else { RETURN_EMPTY_STRING(); } } RETVAL_STRINGL(result, strlen(result), 0); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_lookup) { char* fallback_loc = NULL; int fallback_loc_len = 0; const char* loc_range = NULL; int loc_range_len = 0; zval* arr = NULL; HashTable* hash_arr = NULL; zend_bool boolCanonical = 0; char* result =NULL; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "as|bs", &arr, &loc_range, &loc_range_len, &boolCanonical, &fallback_loc, &fallback_loc_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_lookup: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_range_len == 0) { loc_range = intl_locale_get_default(TSRMLS_C); } hash_arr = HASH_OF(arr); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) { RETURN_EMPTY_STRING(); } result = lookup_loc_range(loc_range, hash_arr, boolCanonical TSRMLS_CC); if(result == NULL || result[0] == '\0') { if( fallback_loc ) { result = estrndup(fallback_loc, fallback_loc_len); } else { RETURN_EMPTY_STRING(); } } RETVAL_STRINGL(result, strlen(result), 0); }
167,194
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PresentationConnectionProxy::DidChangeState( content::PresentationConnectionState state) { if (state == content::PRESENTATION_CONNECTION_STATE_CONNECTED) { source_connection_->didChangeState( blink::WebPresentationConnectionState::Connected); } else if (state == content::PRESENTATION_CONNECTION_STATE_CLOSED) { source_connection_->didChangeState( blink::WebPresentationConnectionState::Closed); } else { NOTREACHED(); } } Commit Message: [Presentation API] Add layout test for connection.close() and fix test failures Add layout test. 1-UA connection.close() hits NOTREACHED() in PresentationConnection::didChangeState(). Use PresentationConnection::didClose() instead. BUG=697719 Review-Url: https://codereview.chromium.org/2730123003 Cr-Commit-Position: refs/heads/master@{#455225} CWE ID:
void PresentationConnectionProxy::DidChangeState( content::PresentationConnectionState state) { if (state == content::PRESENTATION_CONNECTION_STATE_CONNECTED) { source_connection_->didChangeState( blink::WebPresentationConnectionState::Connected); } else if (state == content::PRESENTATION_CONNECTION_STATE_CLOSED) { source_connection_->didClose(); } else { NOTREACHED(); } }
172,044
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WT_NoiseGenerator (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pOutputBuffer; EAS_I32 phaseInc; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 nInterpolatedSample; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; pOutputBuffer = pWTIntFrame->pAudioBuffer; phaseInc = pWTIntFrame->frame.phaseIncrement; /* get last two samples generated */ /*lint -e{704} <avoid divide for performance>*/ tmp0 = (EAS_I32) (pWTVoice->phaseAccum) >> 18; /*lint -e{704} <avoid divide for performance>*/ tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18; /* generate a buffer of noise */ while (numSamples--) { nInterpolatedSample = MULT_AUDIO_COEF( tmp0, (PHASE_ONE - pWTVoice->phaseFrac)); nInterpolatedSample += MULT_AUDIO_COEF( tmp1, pWTVoice->phaseFrac); *pOutputBuffer++ = (EAS_PCM) nInterpolatedSample; /* update PRNG */ pWTVoice->phaseFrac += (EAS_U32) phaseInc; if (GET_PHASE_INT_PART(pWTVoice->phaseFrac)) { tmp0 = tmp1; pWTVoice->phaseAccum = pWTVoice->loopEnd; pWTVoice->loopEnd = (5 * pWTVoice->loopEnd + 1); tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18; pWTVoice->phaseFrac = GET_PHASE_FRAC_PART(pWTVoice->phaseFrac); } } } Commit Message: Sonivox: sanity check numSamples. Bug: 26366256 Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc CWE ID: CWE-119
void WT_NoiseGenerator (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pOutputBuffer; EAS_I32 phaseInc; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 nInterpolatedSample; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); return; } pOutputBuffer = pWTIntFrame->pAudioBuffer; phaseInc = pWTIntFrame->frame.phaseIncrement; /* get last two samples generated */ /*lint -e{704} <avoid divide for performance>*/ tmp0 = (EAS_I32) (pWTVoice->phaseAccum) >> 18; /*lint -e{704} <avoid divide for performance>*/ tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18; /* generate a buffer of noise */ while (numSamples--) { nInterpolatedSample = MULT_AUDIO_COEF( tmp0, (PHASE_ONE - pWTVoice->phaseFrac)); nInterpolatedSample += MULT_AUDIO_COEF( tmp1, pWTVoice->phaseFrac); *pOutputBuffer++ = (EAS_PCM) nInterpolatedSample; /* update PRNG */ pWTVoice->phaseFrac += (EAS_U32) phaseInc; if (GET_PHASE_INT_PART(pWTVoice->phaseFrac)) { tmp0 = tmp1; pWTVoice->phaseAccum = pWTVoice->loopEnd; pWTVoice->loopEnd = (5 * pWTVoice->loopEnd + 1); tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18; pWTVoice->phaseFrac = GET_PHASE_FRAC_PART(pWTVoice->phaseFrac); } } }
173,920
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static InputMethodStatusConnection* GetConnection( void* language_library, LanguageCurrentInputMethodMonitorFunction current_input_method_changed, LanguageRegisterImePropertiesFunction register_ime_properties, LanguageUpdateImePropertyFunction update_ime_property, LanguageConnectionChangeMonitorFunction connection_change_handler) { DCHECK(language_library); DCHECK(current_input_method_changed), DCHECK(register_ime_properties); DCHECK(update_ime_property); InputMethodStatusConnection* object = GetInstance(); if (!object->language_library_) { object->language_library_ = language_library; object->current_input_method_changed_ = current_input_method_changed; object->register_ime_properties_= register_ime_properties; object->update_ime_property_ = update_ime_property; object->connection_change_handler_ = connection_change_handler; object->MaybeRestoreConnections(); } else if (object->language_library_ != language_library) { LOG(ERROR) << "Unknown language_library is passed"; } return object; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static InputMethodStatusConnection* GetConnection( // TODO(satorux,yusukes): Remove use of singleton here. static IBusControllerImpl* GetInstance() { return Singleton<IBusControllerImpl, LeakySingletonTraits<IBusControllerImpl> >::get(); }
170,534
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MaintainContentLengthPrefsForDateChange( base::ListValue* original_update, base::ListValue* received_update, int days_since_last_update) { if (days_since_last_update == -1) { days_since_last_update = 0; } else if (days_since_last_update < -1) { original_update->Clear(); received_update->Clear(); days_since_last_update = kNumDaysInHistory; //// DailyContentLengthUpdate maintains a data saving pref. The pref is a list //// of |kNumDaysInHistory| elements of daily total content lengths for the past //// |kNumDaysInHistory| days. } DCHECK_GE(days_since_last_update, 0); for (int i = 0; i < days_since_last_update && i < static_cast<int>(kNumDaysInHistory); ++i) { original_update->AppendString(base::Int64ToString(0)); received_update->AppendString(base::Int64ToString(0)); } MaintainContentLengthPrefsWindow(original_update, kNumDaysInHistory); MaintainContentLengthPrefsWindow(received_update, kNumDaysInHistory); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void MaintainContentLengthPrefsForDateChange( //// DailyContentLengthUpdate maintains a data saving pref. The pref is a list //// of |kNumDaysInHistory| elements of daily total content lengths for the past //// |kNumDaysInHistory| days. class DailyContentLengthUpdate { public: DailyContentLengthUpdate( const char* pref, PrefService* pref_service) : update_(pref_service, pref) { } void UpdateForDataChange(int days_since_last_update) { // New empty lists may have been created. Maintain the invariant that // there should be exactly |kNumDaysInHistory| days in the histories. MaintainContentLengthPrefsWindow(update_.Get(), kNumDaysInHistory); if (days_since_last_update) { MaintainContentLengthPrefForDateChange(days_since_last_update); } }
171,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: v8::Local<v8::Value> V8Debugger::collectionEntries(v8::Local<v8::Context> context, v8::Local<v8::Object> object) { if (!enabled()) { NOTREACHED(); return v8::Undefined(m_isolate); } v8::Local<v8::Value> argv[] = { object }; v8::Local<v8::Value> entriesValue = callDebuggerMethod("getCollectionEntries", 1, argv).ToLocalChecked(); if (!entriesValue->IsArray()) return v8::Undefined(m_isolate); v8::Local<v8::Array> entries = entriesValue.As<v8::Array>(); if (!markArrayEntriesAsInternal(context, entries, V8InternalValueType::kEntry)) return v8::Undefined(m_isolate); if (!entries->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false)) return v8::Undefined(m_isolate); return entries; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::Local<v8::Value> V8Debugger::collectionEntries(v8::Local<v8::Context> context, v8::Local<v8::Object> object) { if (!enabled()) { NOTREACHED(); return v8::Undefined(m_isolate); } v8::Local<v8::Value> argv[] = { object }; v8::Local<v8::Value> entriesValue = callDebuggerMethod("getCollectionEntries", 1, argv).ToLocalChecked(); v8::Local<v8::Value> copied; if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, entriesValue).ToLocal(&copied) || !copied->IsArray()) return v8::Undefined(m_isolate); if (!markArrayEntriesAsInternal(context, v8::Local<v8::Array>::Cast(copied), V8InternalValueType::kEntry)) return v8::Undefined(m_isolate); return copied; }
172,064
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void StartSync(const StartSyncArgs& args, OneClickSigninSyncStarter::StartSyncMode start_mode) { if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) { LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO); return; } OneClickSigninSyncStarter::ConfirmationRequired confirmation = args.confirmation_required; if (start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST && confirmation == OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN) { confirmation = OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN; } new OneClickSigninSyncStarter(args.profile, args.browser, args.session_index, args.email, args.password, start_mode, args.force_same_tab_navigation, confirmation); int action = one_click_signin::HISTOGRAM_MAX; switch (args.auto_accept) { case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT: break; case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED: action = start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ? one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS : one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED; break; action = one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS; break; case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE: DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST); action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED; break; default: NOTREACHED() << "Invalid auto_accept: " << args.auto_accept; break; } if (action != one_click_signin::HISTOGRAM_MAX) LogOneClickHistogramValue(action); } Commit Message: Display confirmation dialog for untrusted signins BUG=252062 Review URL: https://chromiumcodereview.appspot.com/17482002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void StartSync(const StartSyncArgs& args, OneClickSigninSyncStarter::StartSyncMode start_mode) { if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) { LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO); return; } new OneClickSigninSyncStarter(args.profile, args.browser, args.session_index, args.email, args.password, start_mode, args.force_same_tab_navigation, args.confirmation_required, args.source); int action = one_click_signin::HISTOGRAM_MAX; switch (args.auto_accept) { case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT: break; case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED: action = start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ? one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS : one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED; break; action = one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS; break; case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE: DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST); action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED; break; default: NOTREACHED() << "Invalid auto_accept: " << args.auto_accept; break; } if (action != one_click_signin::HISTOGRAM_MAX) LogOneClickHistogramValue(action); }
171,244
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */ { spl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC); if (fsobj->u.dir.entry.d_name[0] == '\0' && fsobj->orig_path == NULL) { method = "_bad_state_ex"; method_len = sizeof("_bad_state_ex") - 1; key = NULL; } return zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC); } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */ { spl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC); if (fsobj->u.dir.entry.d_name[0] == '\0' && fsobj->orig_path == NULL) { method = "_bad_state_ex"; method_len = sizeof("_bad_state_ex") - 1; key = NULL; } return zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC); } /* }}} */
167,085
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: dtls1_process_buffered_records(SSL *s) { pitem *item; item = pqueue_peek(s->d1->unprocessed_rcds.q); if (item) { /* Check if epoch is current. */ if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch) return(1); /* Nothing to do. */ /* Process all the records. */ while (pqueue_peek(s->d1->unprocessed_rcds.q)) { dtls1_get_unprocessed_record(s); if ( ! dtls1_process_record(s)) return(0); dtls1_buffer_record(s, &(s->d1->processed_rcds), s->s3->rrec.seq_num); } } /* sync epoch numbers once all the unprocessed records * have been processed */ s->d1->processed_rcds.epoch = s->d1->r_epoch; s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1; return(1); } Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a malloc failure, whilst the latter will fail if attempting to add a duplicate record to the queue. This should never happen because duplicate records should be detected and dropped before any attempt to add them to the queue. Unfortunately records that arrive that are for the next epoch are not being recorded correctly, and therefore replays are not being detected. Additionally, these "should not happen" failures that can occur in dtls1_buffer_record are not being treated as fatal and therefore an attacker could exploit this by sending repeated replay records for the next epoch, eventually causing a DoS through memory exhaustion. Thanks to Chris Mueller for reporting this issue and providing initial analysis and a patch. Further analysis and the final patch was performed by Matt Caswell from the OpenSSL development team. CVE-2015-0206 Reviewed-by: Dr Stephen Henson <steve@openssl.org> CWE ID: CWE-119
dtls1_process_buffered_records(SSL *s) { pitem *item; item = pqueue_peek(s->d1->unprocessed_rcds.q); if (item) { /* Check if epoch is current. */ if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch) return(1); /* Nothing to do. */ /* Process all the records. */ while (pqueue_peek(s->d1->unprocessed_rcds.q)) { dtls1_get_unprocessed_record(s); if ( ! dtls1_process_record(s)) return(0); if(dtls1_buffer_record(s, &(s->d1->processed_rcds), s->s3->rrec.seq_num)<0) return -1; } } /* sync epoch numbers once all the unprocessed records * have been processed */ s->d1->processed_rcds.epoch = s->d1->r_epoch; s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1; return(1); }
166,747
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GpuProcessHost::EstablishChannelError( const EstablishChannelCallback& callback, const IPC::ChannelHandle& channel_handle, base::ProcessHandle renderer_process_for_gpu, const content::GPUInfo& gpu_info) { callback.Run(channel_handle, renderer_process_for_gpu, gpu_info); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuProcessHost::EstablishChannelError( const EstablishChannelCallback& callback, const IPC::ChannelHandle& channel_handle, base::ProcessHandle renderer_process_for_gpu, const content::GPUInfo& gpu_info) { callback.Run(channel_handle, gpu_info); }
170,920
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 32) ; psf->header [psf->headindex++] = (x >> 40) ; psf->header [psf->headindex++] = (x >> 48) ; psf->header [psf->headindex++] = (x >> 56) ; } ; } /* header_put_le_8byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x) { psf->header.ptr [psf->header.indx++] = x ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 32) ; psf->header.ptr [psf->header.indx++] = (x >> 40) ; psf->header.ptr [psf->header.indx++] = (x >> 48) ; psf->header.ptr [psf->header.indx++] = (x >> 56) ; } /* header_put_le_8byte */
170,056
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: _warc_read(struct archive_read *a, const void **buf, size_t *bsz, int64_t *off) { struct warc_s *w = a->format->data; const char *rab; ssize_t nrd; if (w->cntoff >= w->cntlen) { eof: /* it's our lucky day, no work, we can leave early */ *buf = NULL; *bsz = 0U; *off = w->cntoff + 4U/*for \r\n\r\n separator*/; w->unconsumed = 0U; return (ARCHIVE_EOF); } rab = __archive_read_ahead(a, 1U, &nrd); if (nrd < 0) { *bsz = 0U; /* big catastrophe */ return (int)nrd; } else if (nrd == 0) { goto eof; } else if ((size_t)nrd > w->cntlen - w->cntoff) { /* clamp to content-length */ nrd = w->cntlen - w->cntoff; } *off = w->cntoff; *bsz = nrd; *buf = rab; w->cntoff += nrd; w->unconsumed = (size_t)nrd; return (ARCHIVE_OK); } Commit Message: warc: consume data once read The warc decoder only used read ahead, it wouldn't actually consume data that had previously been printed. This means that if you specify an invalid content length, it will just reprint the same data over and over and over again until it hits the desired length. This means that a WARC resource with e.g. Content-Length: 666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666665 but only a few hundred bytes of data, causes a quasi-infinite loop. Consume data in subsequent calls to _warc_read. Found with an AFL + afl-rb + qsym setup. CWE ID: CWE-415
_warc_read(struct archive_read *a, const void **buf, size_t *bsz, int64_t *off) { struct warc_s *w = a->format->data; const char *rab; ssize_t nrd; if (w->cntoff >= w->cntlen) { eof: /* it's our lucky day, no work, we can leave early */ *buf = NULL; *bsz = 0U; *off = w->cntoff + 4U/*for \r\n\r\n separator*/; w->unconsumed = 0U; return (ARCHIVE_EOF); } if (w->unconsumed) { __archive_read_consume(a, w->unconsumed); w->unconsumed = 0U; } rab = __archive_read_ahead(a, 1U, &nrd); if (nrd < 0) { *bsz = 0U; /* big catastrophe */ return (int)nrd; } else if (nrd == 0) { goto eof; } else if ((size_t)nrd > w->cntlen - w->cntoff) { /* clamp to content-length */ nrd = w->cntlen - w->cntoff; } *off = w->cntoff; *bsz = nrd; *buf = rab; w->cntoff += nrd; w->unconsumed = (size_t)nrd; return (ARCHIVE_OK); }
168,928
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void OPENSSL_fork_child(void) { rand_fork(); } Commit Message: CWE ID: CWE-330
void OPENSSL_fork_child(void) { }
165,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ApplyBlockElementCommand::formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection) { Position start = startOfSelection.deepEquivalent().downstream(); if (isAtUnsplittableElement(start)) { RefPtr<Element> blockquote = createBlockElement(); insertNodeAt(blockquote, start); RefPtr<Element> placeholder = createBreakElement(document()); appendNode(placeholder, blockquote); setEndingSelection(VisibleSelection(positionBeforeNode(placeholder.get()), DOWNSTREAM, endingSelection().isDirectional())); return; } RefPtr<Element> blockquoteForNextIndent; VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection); VisiblePosition endAfterSelection = endOfParagraph(endOfParagraph(endOfSelection).next()); m_endOfLastParagraph = endOfParagraph(endOfSelection).deepEquivalent(); bool atEnd = false; Position end; while (endOfCurrentParagraph != endAfterSelection && !atEnd) { if (endOfCurrentParagraph.deepEquivalent() == m_endOfLastParagraph) atEnd = true; rangeForParagraphSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end); endOfCurrentParagraph = end; Position afterEnd = end.next(); Node* enclosingCell = enclosingNodeOfType(start, &isTableCell); VisiblePosition endOfNextParagraph = endOfNextParagrahSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end); formatRange(start, end, m_endOfLastParagraph, blockquoteForNextIndent); if (enclosingCell && enclosingCell != enclosingNodeOfType(endOfNextParagraph.deepEquivalent(), &isTableCell)) blockquoteForNextIndent = 0; if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument()) break; if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument()) { ASSERT_NOT_REACHED(); return; } endOfCurrentParagraph = endOfNextParagraph; } } Commit Message: Remove false assertion in ApplyBlockElementCommand::formatSelection() Note: This patch is preparation of fixing issue 294456. This patch removes false assertion in ApplyBlockElementCommand::formatSelection(), when contents of being indent is modified, e.g. mutation event, |endOfNextParagraph| can hold removed contents. BUG=294456 TEST=n/a R=tkent@chromium.org Review URL: https://codereview.chromium.org/25657004 git-svn-id: svn://svn.chromium.org/blink/trunk@158701 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void ApplyBlockElementCommand::formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection) { Position start = startOfSelection.deepEquivalent().downstream(); if (isAtUnsplittableElement(start)) { RefPtr<Element> blockquote = createBlockElement(); insertNodeAt(blockquote, start); RefPtr<Element> placeholder = createBreakElement(document()); appendNode(placeholder, blockquote); setEndingSelection(VisibleSelection(positionBeforeNode(placeholder.get()), DOWNSTREAM, endingSelection().isDirectional())); return; } RefPtr<Element> blockquoteForNextIndent; VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection); VisiblePosition endAfterSelection = endOfParagraph(endOfParagraph(endOfSelection).next()); m_endOfLastParagraph = endOfParagraph(endOfSelection).deepEquivalent(); bool atEnd = false; Position end; while (endOfCurrentParagraph != endAfterSelection && !atEnd) { if (endOfCurrentParagraph.deepEquivalent() == m_endOfLastParagraph) atEnd = true; rangeForParagraphSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end); endOfCurrentParagraph = end; Position afterEnd = end.next(); Node* enclosingCell = enclosingNodeOfType(start, &isTableCell); VisiblePosition endOfNextParagraph = endOfNextParagrahSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end); formatRange(start, end, m_endOfLastParagraph, blockquoteForNextIndent); if (enclosingCell && enclosingCell != enclosingNodeOfType(endOfNextParagraph.deepEquivalent(), &isTableCell)) blockquoteForNextIndent = 0; if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument()) break; // If somehow, e.g. mutation event handler, we did, return to prevent crashes. if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument()) return; endOfCurrentParagraph = endOfNextParagraph; } }
171,170
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void SyncTest::AddOptionalTypesToCommandLine(CommandLine* cl) { if (!cl->HasSwitch(switches::kEnableSyncTabs)) cl->AppendSwitch(switches::kEnableSyncTabs); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void SyncTest::AddOptionalTypesToCommandLine(CommandLine* cl) {
170,789
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: my_object_emit_signals (MyObject *obj, GError **error) { GValue val = {0, }; g_signal_emit (obj, signals[SIG0], 0, "foo", 22, "moo"); g_value_init (&val, G_TYPE_STRING); g_value_set_string (&val, "bar"); g_signal_emit (obj, signals[SIG1], 0, "baz", &val); g_value_unset (&val); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_emit_signals (MyObject *obj, GError **error)
165,096
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MaybeChangeCurrentKeyboardLayout(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value)) { ChangeCurrentInputMethodFromId(value.string_list_value[0]); } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MaybeChangeCurrentKeyboardLayout(const std::string& section, void MaybeChangeCurrentKeyboardLayout( const std::string& section, const std::string& config_name, const input_method::ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value)) { ChangeCurrentInputMethodFromId(value.string_list_value[0]); } }
170,498
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize) { UINT32 len; UINT32 left; BYTE value; left = originalSize; while (left > 4) { value = *in++; if (left == 5) { *out++ = value; left--; } else if (value == *in) { in++; if (*in < 0xFF) { len = (UINT32) * in++; len += 2; } else { in++; len = *((UINT32*) in); in += 4; } FillMemory(out, len, value); out += len; left -= len; } else { *out++ = value; left--; } } *((UINT32*)out) = *((UINT32*)in); } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787
static void nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize) static BOOL nsc_rle_decode(BYTE* in, BYTE* out, UINT32 outSize, UINT32 originalSize) { UINT32 len; UINT32 left; BYTE value; left = originalSize; while (left > 4) { value = *in++; if (left == 5) { if (outSize < 1) return FALSE; outSize--; *out++ = value; left--; } else if (value == *in) { in++; if (*in < 0xFF) { len = (UINT32) * in++; len += 2; } else { in++; len = *((UINT32*) in); in += 4; } if (outSize < len) return FALSE; outSize -= len; FillMemory(out, len, value); out += len; left -= len; } else { if (outSize < 1) return FALSE; outSize--; *out++ = value; left--; } } if ((outSize < 4) || (left < 4)) return FALSE; memcpy(out, in, 4); return TRUE; }
169,284
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex) : mGraphicBuffer(graphicBuffer), mIsBackup(false), mPortIndex(portIndex) { } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex) : mGraphicBuffer(graphicBuffer), mCopyFromOmx(false), mCopyToOmx(false), mPortIndex(portIndex), mBackup(NULL) { }
174,126
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { int i; png_uint_16 freq[256]; /* libpng takes the count from the PLTE count; we don't check it here but we * do set the array to 0 for unspecified entries. */ memset(freq, 0, sizeof freq); for (i=0; i<nparams; ++i) { char *endptr = NULL; unsigned long int l = strtoul(params[i], &endptr, 0/*base*/); if (params[i][0] && *endptr == 0 && l <= 65535) freq[i] = (png_uint_16)l; else { fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]); exit(1); } } png_set_hIST(png_ptr, info_ptr, freq); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params) { int i; png_uint_16 freq[256]; /* libpng takes the count from the PLTE count; we don't check it here but we * do set the array to 0 for unspecified entries. */ memset(freq, 0, sizeof freq); for (i=0; i<nparams; ++i) { char *endptr = NULL; unsigned long int l = strtoul(params[i], &endptr, 0/*base*/); if (params[i][0] && *endptr == 0 && l <= 65535) freq[i] = (png_uint_16)l; else { fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]); exit(1); } } png_set_hIST(png_ptr, info_ptr, freq); }
173,582
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ChromeMockRenderThread::OnCheckForCancel( const std::string& preview_ui_addr, int preview_request_id, bool* cancel) { *cancel = (print_preview_pages_remaining_ == print_preview_cancel_page_number_); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void ChromeMockRenderThread::OnCheckForCancel( void ChromeMockRenderThread::OnCheckForCancel(int32 preview_ui_id, int preview_request_id, bool* cancel) { *cancel = (print_preview_pages_remaining_ == print_preview_cancel_page_number_); }
170,847
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: TouchpadLibrary* CrosLibrary::GetTouchpadLibrary() { return touchpad_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
TouchpadLibrary* CrosLibrary::GetTouchpadLibrary() {
170,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool PrivateScriptRunner::runDOMAttributeSetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder, v8::Local<v8::Value> v8Value) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> descriptor; if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) { fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } v8::Local<v8::Value> setter; if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "set")).ToLocal(&setter) || !setter->IsFunction()) { fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::Local<v8::Value> argv[] = { v8Value }; v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(setter), scriptState->getExecutionContext(), holder, WTF_ARRAY_LENGTH(argv), argv, isolate).ToLocal(&result)) { rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::SetterContext, attributeName, className); block.ReThrow(); return false; } return true; } Commit Message: Blink-in-JS should not run micro tasks If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug (see 645211 for concrete steps). This CL makes Blink-in-JS use callInternalFunction (instead of callFunction) to avoid running micro tasks after Blink-in-JS' callbacks. BUG=645211 Review-Url: https://codereview.chromium.org/2330843002 Cr-Commit-Position: refs/heads/master@{#417874} CWE ID: CWE-79
bool PrivateScriptRunner::runDOMAttributeSetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder, v8::Local<v8::Value> v8Value) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> descriptor; if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) { fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } v8::Local<v8::Value> setter; if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "set")).ToLocal(&setter) || !setter->IsFunction()) { fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::Local<v8::Value> argv[] = { v8Value }; v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(setter), holder, WTF_ARRAY_LENGTH(argv), argv, isolate).ToLocal(&result)) { rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::SetterContext, attributeName, className); block.ReThrow(); return false; } return true; }
172,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info) { struct uvesafb_pal_entry *entries; int shift = 16 - dac_width; int i, err = 0; if (info->var.bits_per_pixel == 8) { if (cmap->start + cmap->len > info->cmap.start + info->cmap.len || cmap->start < info->cmap.start) return -EINVAL; entries = kmalloc(sizeof(*entries) * cmap->len, GFP_KERNEL); if (!entries) return -ENOMEM; for (i = 0; i < cmap->len; i++) { entries[i].red = cmap->red[i] >> shift; entries[i].green = cmap->green[i] >> shift; entries[i].blue = cmap->blue[i] >> shift; entries[i].pad = 0; } err = uvesafb_setpalette(entries, cmap->len, cmap->start, info); kfree(entries); } else { /* * For modes with bpp > 8, we only set the pseudo palette in * the fb_info struct. We rely on uvesafb_setcolreg to do all * sanity checking. */ for (i = 0; i < cmap->len; i++) { err |= uvesafb_setcolreg(cmap->start + i, cmap->red[i], cmap->green[i], cmap->blue[i], 0, info); } } return err; } Commit Message: video: uvesafb: Fix integer overflow in allocation cmap->len can get close to INT_MAX/2, allowing for an integer overflow in allocation. This uses kmalloc_array() instead to catch the condition. Reported-by: Dr Silvio Cesare of InfoSect <silvio.cesare@gmail.com> Fixes: 8bdb3a2d7df48 ("uvesafb: the driver core") Cc: stable@vger.kernel.org Signed-off-by: Kees Cook <keescook@chromium.org> CWE ID: CWE-190
static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info) { struct uvesafb_pal_entry *entries; int shift = 16 - dac_width; int i, err = 0; if (info->var.bits_per_pixel == 8) { if (cmap->start + cmap->len > info->cmap.start + info->cmap.len || cmap->start < info->cmap.start) return -EINVAL; entries = kmalloc_array(cmap->len, sizeof(*entries), GFP_KERNEL); if (!entries) return -ENOMEM; for (i = 0; i < cmap->len; i++) { entries[i].red = cmap->red[i] >> shift; entries[i].green = cmap->green[i] >> shift; entries[i].blue = cmap->blue[i] >> shift; entries[i].pad = 0; } err = uvesafb_setpalette(entries, cmap->len, cmap->start, info); kfree(entries); } else { /* * For modes with bpp > 8, we only set the pseudo palette in * the fb_info struct. We rely on uvesafb_setcolreg to do all * sanity checking. */ for (i = 0; i < cmap->len; i++) { err |= uvesafb_setcolreg(cmap->start + i, cmap->red[i], cmap->green[i], cmap->blue[i], 0, info); } } return err; }
169,152
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SYSCALL_DEFINE3(rt_sigqueueinfo, pid_t, pid, int, sig, siginfo_t __user *, uinfo) { siginfo_t info; if (copy_from_user(&info, uinfo, sizeof(siginfo_t))) return -EFAULT; /* Not even root can pretend to send signals from the kernel. Nor can they impersonate a kill(), which adds source info. */ if (info.si_code >= 0) return -EPERM; info.si_signo = sig; /* POSIX.1b doesn't mention process groups. */ return kill_proc_info(sig, &info, pid); } Commit Message: Prevent rt_sigqueueinfo and rt_tgsigqueueinfo from spoofing the signal code Userland should be able to trust the pid and uid of the sender of a signal if the si_code is SI_TKILL. Unfortunately, the kernel has historically allowed sigqueueinfo() to send any si_code at all (as long as it was negative - to distinguish it from kernel-generated signals like SIGILL etc), so it could spoof a SI_TKILL with incorrect siginfo values. Happily, it looks like glibc has always set si_code to the appropriate SI_QUEUE, so there are probably no actual user code that ever uses anything but the appropriate SI_QUEUE flag. So just tighten the check for si_code (we used to allow any negative value), and add a (one-time) warning in case there are binaries out there that might depend on using other si_code values. Signed-off-by: Julien Tinnes <jln@google.com> Acked-by: Oleg Nesterov <oleg@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID:
SYSCALL_DEFINE3(rt_sigqueueinfo, pid_t, pid, int, sig, siginfo_t __user *, uinfo) { siginfo_t info; if (copy_from_user(&info, uinfo, sizeof(siginfo_t))) return -EFAULT; /* Not even root can pretend to send signals from the kernel. * Nor can they impersonate a kill()/tgkill(), which adds source info. */ if (info.si_code != SI_QUEUE) { /* We used to allow any < 0 si_code */ WARN_ON_ONCE(info.si_code < 0); return -EPERM; } info.si_signo = sig; /* POSIX.1b doesn't mention process groups. */ return kill_proc_info(sig, &info, pid); }
166,231
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int asymmetric_key_match_preparse(struct key_match_data *match_data) { match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE; return 0; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <dhowells@redhat.com> Acked-by: Vivek Goyal <vgoyal@redhat.com> CWE ID: CWE-476
static int asymmetric_key_match_preparse(struct key_match_data *match_data) { match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE; match_data->cmp = asymmetric_key_cmp; return 0; }
168,437
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool DataReductionProxyConfig::IsFetchInFlight() const { DCHECK(thread_checker_.CalledOnValidThread()); return warmup_url_fetcher_->IsFetchInFlight(); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <tbansal@chromium.org> Reviewed-by: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
bool DataReductionProxyConfig::IsFetchInFlight() const { DCHECK(thread_checker_.CalledOnValidThread()); if (!warmup_url_fetcher_) return false; return warmup_url_fetcher_->IsFetchInFlight(); }
172,417
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() { SetContentViewCore(NULL); if (!shared_surface_.is_null()) { ImageTransportFactoryAndroid::GetInstance()->DestroySharedSurfaceHandle( shared_surface_); } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() { SetContentViewCore(NULL); if (!shared_surface_.is_null()) { ImageTransportFactoryAndroid::GetInstance()->DestroySharedSurfaceHandle( shared_surface_); } if (texture_id_in_layer_) { ImageTransportFactoryAndroid::GetInstance()->DeleteTexture( texture_id_in_layer_); } }
171,371
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int multipath_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct multipath *m = (struct multipath *) ti->private; struct block_device *bdev = NULL; fmode_t mode = 0; unsigned long flags; int r = 0; spin_lock_irqsave(&m->lock, flags); if (!m->current_pgpath) __choose_pgpath(m, 0); if (m->current_pgpath) { bdev = m->current_pgpath->path.dev->bdev; mode = m->current_pgpath->path.dev->mode; } if (m->queue_io) r = -EAGAIN; else if (!bdev) r = -EIO; spin_unlock_irqrestore(&m->lock, flags); return r ? : __blkdev_driver_ioctl(bdev, mode, cmd, arg); } Commit Message: dm: do not forward ioctls from logical volumes to the underlying device A logical volume can map to just part of underlying physical volume. In this case, it must be treated like a partition. Based on a patch from Alasdair G Kergon. Cc: Alasdair G Kergon <agk@redhat.com> Cc: dm-devel@redhat.com Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-264
static int multipath_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct multipath *m = (struct multipath *) ti->private; struct block_device *bdev = NULL; fmode_t mode = 0; unsigned long flags; int r = 0; spin_lock_irqsave(&m->lock, flags); if (!m->current_pgpath) __choose_pgpath(m, 0); if (m->current_pgpath) { bdev = m->current_pgpath->path.dev->bdev; mode = m->current_pgpath->path.dev->mode; } if (m->queue_io) r = -EAGAIN; else if (!bdev) r = -EIO; spin_unlock_irqrestore(&m->lock, flags); /* * Only pass ioctls through if the device sizes match exactly. */ if (!r && ti->len != i_size_read(bdev->bd_inode) >> SECTOR_SHIFT) r = scsi_verify_blk_ioctl(NULL, cmd); return r ? : __blkdev_driver_ioctl(bdev, mode, cmd, arg); }
165,724
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int ext4_dax_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { int result; handle_t *handle = NULL; struct super_block *sb = file_inode(vma->vm_file)->i_sb; bool write = vmf->flags & FAULT_FLAG_WRITE; if (write) { sb_start_pagefault(sb); file_update_time(vma->vm_file); handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE, EXT4_DATA_TRANS_BLOCKS(sb)); } if (IS_ERR(handle)) result = VM_FAULT_SIGBUS; else result = __dax_fault(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); if (write) { if (!IS_ERR(handle)) ext4_journal_stop(handle); sb_end_pagefault(sb); } return result; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-362
static int ext4_dax_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { int result; handle_t *handle = NULL; struct inode *inode = file_inode(vma->vm_file); struct super_block *sb = inode->i_sb; bool write = vmf->flags & FAULT_FLAG_WRITE; if (write) { sb_start_pagefault(sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE, EXT4_DATA_TRANS_BLOCKS(sb)); } else down_read(&EXT4_I(inode)->i_mmap_sem); if (IS_ERR(handle)) result = VM_FAULT_SIGBUS; else result = __dax_fault(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); if (write) { if (!IS_ERR(handle)) ext4_journal_stop(handle); up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(sb); } else up_read(&EXT4_I(inode)->i_mmap_sem); return result; }
167,486
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual bool Speak( const std::string& utterance, const std::string& language, const std::string& gender, double rate, double pitch, double volume) { error_ = kNotSupportedError; return false; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
virtual bool Speak( int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params) { error_ = kNotSupportedError; return false; }
170,400
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ReadUserLogState::SetState( const ReadUserLog::FileState &state ) { const ReadUserLogFileState::FileState *istate; if ( !convertState(state, istate) ) { return false; } if ( strcmp( istate->m_signature, FileStateSignature ) ) { m_init_error = true; return false; } if ( istate->m_version != FILESTATE_VERSION ) { m_init_error = true; return false; } m_base_path = istate->m_base_path; m_max_rotations = istate->m_max_rotations; Rotation( istate->m_rotation, false, true ); m_log_type = istate->m_log_type; m_uniq_id = istate->m_uniq_id; m_sequence = istate->m_sequence; m_stat_buf.st_ino = istate->m_inode; m_stat_buf.st_ctime = istate->m_ctime; m_stat_buf.st_size = istate->m_size.asint; m_stat_valid = true; m_offset = istate->m_offset.asint; m_event_num = istate->m_event_num.asint; m_log_position = istate->m_log_position.asint; m_log_record = istate->m_log_record.asint; m_update_time = istate->m_update_time; m_initialized = true; MyString str; GetStateString( str, "Restored reader state" ); dprintf( D_FULLDEBUG, str.Value() ); return true; } Commit Message: CWE ID: CWE-134
ReadUserLogState::SetState( const ReadUserLog::FileState &state ) { const ReadUserLogFileState::FileState *istate; if ( !convertState(state, istate) ) { return false; } if ( strcmp( istate->m_signature, FileStateSignature ) ) { m_init_error = true; return false; } if ( istate->m_version != FILESTATE_VERSION ) { m_init_error = true; return false; } m_base_path = istate->m_base_path; m_max_rotations = istate->m_max_rotations; Rotation( istate->m_rotation, false, true ); m_log_type = istate->m_log_type; m_uniq_id = istate->m_uniq_id; m_sequence = istate->m_sequence; m_stat_buf.st_ino = istate->m_inode; m_stat_buf.st_ctime = istate->m_ctime; m_stat_buf.st_size = istate->m_size.asint; m_stat_valid = true; m_offset = istate->m_offset.asint; m_event_num = istate->m_event_num.asint; m_log_position = istate->m_log_position.asint; m_log_record = istate->m_log_record.asint; m_update_time = istate->m_update_time; m_initialized = true; MyString str; GetStateString( str, "Restored reader state" ); dprintf( D_FULLDEBUG, "%s", str.Value() ); return true; }
165,387
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BluetoothDeviceChooserController::~BluetoothDeviceChooserController() { if (scanning_start_time_) { RecordScanningDuration(base::TimeTicks::Now() - scanning_start_time_.value()); } if (chooser_) { DCHECK(!error_callback_.is_null()); error_callback_.Run(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); } } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <chrishtr@chromium.org> Reviewed-by: Giovanni Ortuño Urquidi <ortuno@chromium.org> Reviewed-by: Kinuko Yasuda <kinuko@chromium.org> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
BluetoothDeviceChooserController::~BluetoothDeviceChooserController() { if (scanning_start_time_) { RecordScanningDuration(base::TimeTicks::Now() - scanning_start_time_.value()); } if (chooser_) { DCHECK(!error_callback_.is_null()); error_callback_.Run(WebBluetoothResult::CHOOSER_CANCELLED); } }
172,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: modifier_color_encoding_is_set(PNG_CONST png_modifier *pm) { return pm->current_gamma != 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
modifier_color_encoding_is_set(PNG_CONST png_modifier *pm) modifier_color_encoding_is_set(const png_modifier *pm) { return pm->current_gamma != 0; }
173,668
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx, struct iw_exif_state *e, iw_uint32 ifd) { unsigned int tag_count; unsigned int i; unsigned int tag_pos; unsigned int tag_id; unsigned int v; double v_dbl; if(ifd<8 || ifd>e->d_len-18) return; tag_count = iw_get_ui16_e(&e->d[ifd],e->endian); if(tag_count>1000) return; // Sanity check. for(i=0;i<tag_count;i++) { tag_pos = ifd+2+i*12; if(tag_pos+12 > e->d_len) return; // Avoid overruns. tag_id = iw_get_ui16_e(&e->d[tag_pos],e->endian); switch(tag_id) { case 274: // 274 = Orientation if(get_exif_tag_int_value(e,tag_pos,&v)) { rctx->exif_orientation = v; } break; case 296: // 296 = ResolutionUnit if(get_exif_tag_int_value(e,tag_pos,&v)) { rctx->exif_density_unit = v; } break; case 282: // 282 = XResolution if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) { rctx->exif_density_x = v_dbl; } break; case 283: // 283 = YResolution if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) { rctx->exif_density_y = v_dbl; } break; } } } Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data Fixes issues #22, #23, #24, #25 CWE ID: CWE-125
static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx, struct iw_exif_state *e, iw_uint32 ifd) { unsigned int tag_count; unsigned int i; unsigned int tag_pos; unsigned int tag_id; unsigned int v; double v_dbl; if(ifd<8 || e->d_len<18 || ifd>e->d_len-18) return; tag_count = get_exif_ui16(e, ifd); if(tag_count>1000) return; // Sanity check. for(i=0;i<tag_count;i++) { tag_pos = ifd+2+i*12; if(tag_pos+12 > e->d_len) return; // Avoid overruns. tag_id = get_exif_ui16(e, tag_pos); switch(tag_id) { case 274: // 274 = Orientation if(get_exif_tag_int_value(e,tag_pos,&v)) { rctx->exif_orientation = v; } break; case 296: // 296 = ResolutionUnit if(get_exif_tag_int_value(e,tag_pos,&v)) { rctx->exif_density_unit = v; } break; case 282: // 282 = XResolution if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) { rctx->exif_density_x = v_dbl; } break; case 283: // 283 = YResolution if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) { rctx->exif_density_y = v_dbl; } break; } } }
168,116
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: v8::Local<v8::Object> V8SchemaRegistry::GetSchema(const std::string& api) { if (schema_cache_ != NULL) { v8::Local<v8::Object> cached_schema = schema_cache_->Get(api); if (!cached_schema.IsEmpty()) { return cached_schema; } } v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::EscapableHandleScope handle_scope(isolate); v8::Local<v8::Context> context = GetOrCreateContext(isolate); v8::Context::Scope context_scope(context); const base::DictionaryValue* schema = ExtensionAPI::GetSharedInstance()->GetSchema(api); CHECK(schema) << api; std::unique_ptr<V8ValueConverter> v8_value_converter( V8ValueConverter::create()); v8::Local<v8::Value> value = v8_value_converter->ToV8Value(schema, context); CHECK(!value.IsEmpty()); v8::Local<v8::Object> v8_schema(v8::Local<v8::Object>::Cast(value)); v8_schema->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen); schema_cache_->Set(api, v8_schema); return handle_scope.Escape(v8_schema); } Commit Message: [Extensions] Finish freezing schema BUG=604901 BUG=603725 BUG=591164 Review URL: https://codereview.chromium.org/1906593002 Cr-Commit-Position: refs/heads/master@{#388945} CWE ID: CWE-200
v8::Local<v8::Object> V8SchemaRegistry::GetSchema(const std::string& api) { if (schema_cache_ != NULL) { v8::Local<v8::Object> cached_schema = schema_cache_->Get(api); if (!cached_schema.IsEmpty()) { return cached_schema; } } v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::EscapableHandleScope handle_scope(isolate); v8::Local<v8::Context> context = GetOrCreateContext(isolate); v8::Context::Scope context_scope(context); const base::DictionaryValue* schema = ExtensionAPI::GetSharedInstance()->GetSchema(api); CHECK(schema) << api; std::unique_ptr<V8ValueConverter> v8_value_converter( V8ValueConverter::create()); v8::Local<v8::Value> value = v8_value_converter->ToV8Value(schema, context); CHECK(!value.IsEmpty()); v8::Local<v8::Object> v8_schema(v8::Local<v8::Object>::Cast(value)); DeepFreeze(v8_schema, context); schema_cache_->Set(api, v8_schema); return handle_scope.Escape(v8_schema); }
172,259
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (!mTimeToSample.empty() || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); if ((uint64_t)mTimeToSampleCount > (uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) { ALOGE(" Error: Time-to-sample table size too large."); return ERROR_OUT_OF_RANGE; } if (!mDataSource->getVector(data_offset + 8, &mTimeToSample, mTimeToSampleCount * 2)) { ALOGE(" Error: Incomplete data read for time-to-sample table."); return ERROR_IO; } for (size_t i = 0; i < mTimeToSample.size(); ++i) { mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]); } return OK; } Commit Message: SampleTable.cpp: Fixed a regression caused by a fix for bug 28076789. Detail: Before the original fix (Id207f369ab7b27787d83f5d8fc48dc53ed9fcdc9) for 28076789, the code allowed a time-to-sample table size to be 0. The change made in that fix disallowed such situation, which in fact should be allowed. This current patch allows it again while maintaining the security of the previous fix. Bug: 28288202 Bug: 28076789 Change-Id: I1c9a60c7f0cfcbd3d908f24998dde15d5136a295 CWE ID: CWE-20
status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mHasTimeToSample || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); if ((uint64_t)mTimeToSampleCount > (uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) { ALOGE(" Error: Time-to-sample table size too large."); return ERROR_OUT_OF_RANGE; } if (!mDataSource->getVector(data_offset + 8, &mTimeToSample, mTimeToSampleCount * 2)) { ALOGE(" Error: Incomplete data read for time-to-sample table."); return ERROR_IO; } for (size_t i = 0; i < mTimeToSample.size(); ++i) { mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]); } mHasTimeToSample = true; return OK; }
173,773
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: atol10(const char *p, size_t char_cnt) { uint64_t l; int digit; l = 0; digit = *p - '0'; while (digit >= 0 && digit < 10 && char_cnt-- > 0) { l = (l * 10) + digit; digit = *++p - '0'; } return (l); } Commit Message: Do something sensible for empty strings to make fuzzers happy. CWE ID: CWE-125
atol10(const char *p, size_t char_cnt) { uint64_t l; int digit; if (char_cnt == 0) return (0); l = 0; digit = *p - '0'; while (digit >= 0 && digit < 10 && char_cnt-- > 0) { l = (l * 10) + digit; digit = *++p - '0'; } return (l); }
167,767
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void* sspi_SecureHandleGetUpperPointer(SecHandle* handle) { void* pointer; if (!handle) return NULL; pointer = (void*) ~((size_t) handle->dwUpper); return pointer; } Commit Message: nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished. CWE ID: CWE-476
void* sspi_SecureHandleGetUpperPointer(SecHandle* handle) { void* pointer; if (!handle || !SecIsValidHandle(handle)) return NULL; pointer = (void*) ~((size_t) handle->dwUpper); return pointer; }
167,605
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode) { if (file->f_flags & O_DSYNC) return 0; if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE)) return 1; if (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL || (inode->i_flock->fl_start == 0 && inode->i_flock->fl_end == OFFSET_MAX && inode->i_flock->fl_type != F_RDLCK))) return 1; return 0; } Commit Message: nfs: always make sure page is up-to-date before extending a write to cover the entire page We should always make sure the cached page is up-to-date when we're determining whether we can extend a write to cover the full page -- even if we've received a write delegation from the server. Commit c7559663 added logic to skip this check if we have a write delegation, which can lead to data corruption such as the following scenario if client B receives a write delegation from the NFS server: Client A: # echo 123456789 > /mnt/file Client B: # echo abcdefghi >> /mnt/file # cat /mnt/file 0�D0�abcdefghi Just because we hold a write delegation doesn't mean that we've read in the entire page contents. Cc: <stable@vger.kernel.org> # v3.11+ Signed-off-by: Scott Mayhew <smayhew@redhat.com> Signed-off-by: Trond Myklebust <trond.myklebust@primarydata.com> CWE ID: CWE-20
static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode) { if (file->f_flags & O_DSYNC) return 0; if (!nfs_write_pageuptodate(page, inode)) return 0; if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE)) return 1; if (inode->i_flock == NULL || (inode->i_flock->fl_start == 0 && inode->i_flock->fl_end == OFFSET_MAX && inode->i_flock->fl_type != F_RDLCK)) return 1; return 0; }
166,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ } Commit Message: CWE ID: CWE-476
Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } if ( coords ) { for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ } else { for ( i = 0; i < num_axes; i++ ) args[i] = 0; } }
165,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int http_open(URLContext *h, const char *uri, int flags, AVDictionary **options) { HTTPContext *s = h->priv_data; int ret; if( s->seekable == 1 ) h->is_streamed = 0; else h->is_streamed = 1; s->filesize = -1; s->location = av_strdup(uri); if (!s->location) return AVERROR(ENOMEM); if (options) av_dict_copy(&s->chained_options, *options, 0); if (s->headers) { int len = strlen(s->headers); if (len < 2 || strcmp("\r\n", s->headers + len - 2)) { av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n"); ret = av_reallocp(&s->headers, len + 3); if (ret < 0) return ret; s->headers[len] = '\r'; s->headers[len + 1] = '\n'; s->headers[len + 2] = '\0'; } } if (s->listen) { return http_listen(h, uri, flags, options); } ret = http_open_cnx(h, options); if (ret < 0) av_dict_free(&s->chained_options); return ret; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <paulcher@icloud.com>. CWE ID: CWE-119
static int http_open(URLContext *h, const char *uri, int flags, AVDictionary **options) { HTTPContext *s = h->priv_data; int ret; if( s->seekable == 1 ) h->is_streamed = 0; else h->is_streamed = 1; s->filesize = UINT64_MAX; s->location = av_strdup(uri); if (!s->location) return AVERROR(ENOMEM); if (options) av_dict_copy(&s->chained_options, *options, 0); if (s->headers) { int len = strlen(s->headers); if (len < 2 || strcmp("\r\n", s->headers + len - 2)) { av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n"); ret = av_reallocp(&s->headers, len + 3); if (ret < 0) return ret; s->headers[len] = '\r'; s->headers[len + 1] = '\n'; s->headers[len + 2] = '\0'; } } if (s->listen) { return http_listen(h, uri, flags, options); } ret = http_open_cnx(h, options); if (ret < 0) av_dict_free(&s->chained_options); return ret; }
168,498
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int WebGraphicsContext3DCommandBufferImpl::GetGPUProcessID() { return host_ ? host_->gpu_process_id() : 0; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
int WebGraphicsContext3DCommandBufferImpl::GetGPUProcessID() { return host_ ? host_->gpu_host_id() : 0; }
170,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static double abserr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* Absolute error permitted in linear values - affected by the bit depth of * the calculations. */ if (pm->assume_16_bit_calculations || (pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxabs16; else return pm->maxabs8; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double abserr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) static double abserr(const png_modifier *pm, int in_depth, int out_depth) { /* Absolute error permitted in linear values - affected by the bit depth of * the calculations. */ if (pm->assume_16_bit_calculations || (pm->calculations_use_input_precision ? in_depth : out_depth) == 16) return pm->maxabs16; else return pm->maxabs8; }
173,603
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: iakerb_gss_export_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 maj; iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; /* We don't currently support exporting partially established contexts. */ if (!ctx->established) return GSS_S_UNAVAILABLE; maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc, interprocess_token); if (ctx->gssc == GSS_C_NO_CONTEXT) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } return maj; } Commit Message: Fix IAKERB context export/import [CVE-2015-2698] The patches for CVE-2015-2696 contained a regression in the newly added IAKERB iakerb_gss_export_sec_context() function, which could cause it to corrupt memory. Fix the regression by properly dereferencing the context_handle pointer before casting it. Also, the patches did not implement an IAKERB gss_import_sec_context() function, under the erroneous belief that an exported IAKERB context would be tagged as a krb5 context. Implement it now to allow IAKERB contexts to be successfully exported and imported after establishment. CVE-2015-2698: In any MIT krb5 release with the patches for CVE-2015-2696 applied, an application which calls gss_export_sec_context() may experience memory corruption if the context was established using the IAKERB mechanism. Historically, some vulnerabilities of this nature can be translated into remote code execution, though the necessary exploits must be tailored to the individual application and are usually quite complicated. CVSSv2 Vector: AV:N/AC:H/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C ticket: 8273 (new) target_version: 1.14 tags: pullup CWE ID: CWE-119
iakerb_gss_export_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 maj; iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)*context_handle; /* We don't currently support exporting partially established contexts. */ if (!ctx->established) return GSS_S_UNAVAILABLE; maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc, interprocess_token); if (ctx->gssc == GSS_C_NO_CONTEXT) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } return maj; }
166,640
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long Chapters::Edition::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) // Atom ID { status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Chapters::Edition::Parse( Segment* const pSegment = pChapters->m_pSegment; if (pSegment == NULL) // weird return -1; const SegmentInfo* const pInfo = pSegment->GetInfo(); if (pInfo == NULL) return -1; const long long timecode_scale = pInfo->GetTimeCodeScale(); if (timecode_scale < 1) // weird return -1; if (timecode < 0) return -1; const long long result = timecode_scale * timecode; return result; } long Chapters::Atom::ParseDisplay(IMkvReader* pReader, long long pos, long long size) { if (!ExpandDisplaysArray()) return -1; Display& d = m_displays[m_displays_count++]; d.Init(); return d.Parse(pReader, pos, size); } bool Chapters::Atom::ExpandDisplaysArray() { if (m_displays_size > m_displays_count) return true; // nothing else to do const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size; Display* const displays = new (std::nothrow) Display[size]; if (displays == NULL) return false; for (int idx = 0; idx < m_displays_count; ++idx) { m_displays[idx].ShallowCopy(displays[idx]); } delete[] m_displays; m_displays = displays; m_displays_size = size; return true; } Chapters::Display::Display() {} Chapters::Display::~Display() {} const char* Chapters::Display::GetString() const { return m_string; } const char* Chapters::Display::GetLanguage() const { return m_language; } const char* Chapters::Display::GetCountry() const { return m_country; } void Chapters::Display::Init() { m_string = NULL; m_language = NULL; m_country = NULL; } void Chapters::Display::ShallowCopy(Display& rhs) const { rhs.m_string = m_string; rhs.m_language = m_language; rhs.m_country = m_country; } void Chapters::Display::Clear() { delete[] m_string; m_string = NULL; delete[] m_language; m_language = NULL; delete[] m_country; m_country = NULL; } long Chapters::Display::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x05) { // ChapterString ID status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) { // ChapterLanguage ID status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) { // ChapterCountry ID status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; }
174,401
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BaseRenderingContext2D::setFillStyle( const StringOrCanvasGradientOrCanvasPattern& style) { DCHECK(!style.IsNull()); ValidateStateStack(); String color_string; CanvasStyle* canvas_style = nullptr; if (style.IsString()) { color_string = style.GetAsString(); if (color_string == GetState().UnparsedFillColor()) return; Color parsed_color = 0; if (!ParseColorOrCurrentColor(parsed_color, color_string)) return; if (GetState().FillStyle()->IsEquivalentRGBA(parsed_color.Rgb())) { ModifiableState().SetUnparsedFillColor(color_string); return; } canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb()); } else if (style.IsCanvasGradient()) { canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient()); } else if (style.IsCanvasPattern()) { CanvasPattern* canvas_pattern = style.GetAsCanvasPattern(); if (OriginClean() && !canvas_pattern->OriginClean()) { SetOriginTainted(); ClearResolvedFilters(); } if (canvas_pattern->GetPattern()->IsTextureBacked()) DisableDeferral(kDisableDeferralReasonUsingTextureBackedPattern); canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern); } DCHECK(canvas_style); ModifiableState().SetFillStyle(canvas_style); ModifiableState().SetUnparsedFillColor(color_string); ModifiableState().ClearResolvedFilter(); } Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <fs@opera.com> Commit-Queue: Chris Harrelson <chrishtr@chromium.org> Cr-Commit-Position: refs/heads/master@{#522274} CWE ID: CWE-200
void BaseRenderingContext2D::setFillStyle( const StringOrCanvasGradientOrCanvasPattern& style) { DCHECK(!style.IsNull()); ValidateStateStack(); String color_string; CanvasStyle* canvas_style = nullptr; if (style.IsString()) { color_string = style.GetAsString(); if (color_string == GetState().UnparsedFillColor()) return; Color parsed_color = 0; if (!ParseColorOrCurrentColor(parsed_color, color_string)) return; if (GetState().FillStyle()->IsEquivalentRGBA(parsed_color.Rgb())) { ModifiableState().SetUnparsedFillColor(color_string); return; } canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb()); } else if (style.IsCanvasGradient()) { canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient()); } else if (style.IsCanvasPattern()) { CanvasPattern* canvas_pattern = style.GetAsCanvasPattern(); if (!origin_tainted_by_content_ && !canvas_pattern->OriginClean()) { SetOriginTaintedByContent(); } if (canvas_pattern->GetPattern()->IsTextureBacked()) DisableDeferral(kDisableDeferralReasonUsingTextureBackedPattern); canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern); } DCHECK(canvas_style); ModifiableState().SetFillStyle(canvas_style); ModifiableState().SetUnparsedFillColor(color_string); ModifiableState().ClearResolvedFilter(); }
172,908
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: jbig2_sd_release(Jbig2Ctx *ctx, Jbig2SymbolDict *dict) { int i; if (dict == NULL) return; for (i = 0; i < dict->n_symbols; i++) if (dict->glyphs[i]) jbig2_image_release(ctx, dict->glyphs[i]); jbig2_free(ctx->allocator, dict->glyphs); jbig2_free(ctx->allocator, dict); } Commit Message: CWE ID: CWE-119
jbig2_sd_release(Jbig2Ctx *ctx, Jbig2SymbolDict *dict) { uint32_t i; if (dict == NULL) return; for (i = 0; i < dict->n_symbols; i++) if (dict->glyphs[i]) jbig2_image_release(ctx, dict->glyphs[i]); jbig2_free(ctx->allocator, dict->glyphs); jbig2_free(ctx->allocator, dict); }
165,503
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func) { irda_queue_t* queue; unsigned long flags = 0; int i; IRDA_ASSERT(hashbin != NULL, return -1;); IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;); /* Synchronize */ if ( hashbin->hb_type & HB_LOCK ) { spin_lock_irqsave_nested(&hashbin->hb_spinlock, flags, hashbin_lock_depth++); } /* * Free the entries in the hashbin, TODO: use hashbin_clear when * it has been shown to work */ for (i = 0; i < HASHBIN_SIZE; i ++ ) { queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]); while (queue ) { if (free_func) (*free_func)(queue); queue = dequeue_first( (irda_queue_t**) &hashbin->hb_queue[i]); } } /* Cleanup local data */ hashbin->hb_current = NULL; hashbin->magic = ~HB_MAGIC; /* Release lock */ if ( hashbin->hb_type & HB_LOCK) { spin_unlock_irqrestore(&hashbin->hb_spinlock, flags); #ifdef CONFIG_LOCKDEP hashbin_lock_depth--; #endif } /* * Free the hashbin structure */ kfree(hashbin); return 0; } Commit Message: irda: Fix lockdep annotations in hashbin_delete(). A nested lock depth was added to the hasbin_delete() code but it doesn't actually work some well and results in tons of lockdep splats. Fix the code instead to properly drop the lock around the operation and just keep peeking the head of the hashbin queue. Reported-by: Dmitry Vyukov <dvyukov@google.com> Tested-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func) { irda_queue_t* queue; unsigned long flags = 0; int i; IRDA_ASSERT(hashbin != NULL, return -1;); IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;); /* Synchronize */ if (hashbin->hb_type & HB_LOCK) spin_lock_irqsave(&hashbin->hb_spinlock, flags); /* * Free the entries in the hashbin, TODO: use hashbin_clear when * it has been shown to work */ for (i = 0; i < HASHBIN_SIZE; i ++ ) { while (1) { queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]); if (!queue) break; if (free_func) { if (hashbin->hb_type & HB_LOCK) spin_unlock_irqrestore(&hashbin->hb_spinlock, flags); free_func(queue); if (hashbin->hb_type & HB_LOCK) spin_lock_irqsave(&hashbin->hb_spinlock, flags); } } } /* Cleanup local data */ hashbin->hb_current = NULL; hashbin->magic = ~HB_MAGIC; /* Release lock */ if (hashbin->hb_type & HB_LOCK) spin_unlock_irqrestore(&hashbin->hb_spinlock, flags); /* * Free the hashbin structure */ kfree(hashbin); return 0; }
168,344
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int sock_send_all(int sock_fd, const uint8_t* buf, int len) { int s = len; int ret; while(s) { do ret = send(sock_fd, buf, s, 0); while(ret < 0 && errno == EINTR); if(ret <= 0) { BTIF_TRACE_ERROR("sock fd:%d send errno:%d, ret:%d", sock_fd, errno, ret); return -1; } buf += ret; s -= ret; } return len; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
int sock_send_all(int sock_fd, const uint8_t* buf, int len) { int s = len; int ret; while(s) { do ret = TEMP_FAILURE_RETRY(send(sock_fd, buf, s, 0)); while(ret < 0 && errno == EINTR); if(ret <= 0) { BTIF_TRACE_ERROR("sock fd:%d send errno:%d, ret:%d", sock_fd, errno, ret); return -1; } buf += ret; s -= ret; } return len; }
173,469
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end, OnigCompileInfo* ci, OnigErrorInfo* einfo) { int r; UChar *cpat, *cpat_end; if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL; if (ci->pattern_enc != ci->target_enc) { r = conv_encoding(ci->pattern_enc, ci->target_enc, pattern, pattern_end, &cpat, &cpat_end); if (r != 0) return r; } else { cpat = (UChar* )pattern; cpat_end = (UChar* )pattern_end; } *reg = (regex_t* )xmalloc(sizeof(regex_t)); if (IS_NULL(*reg)) { r = ONIGERR_MEMORY; goto err2; } r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc, ci->syntax); if (r != 0) goto err; r = onig_compile(*reg, cpat, cpat_end, einfo); if (r != 0) { err: onig_free(*reg); *reg = NULL; } err2: if (cpat != pattern) xfree(cpat); return r; } Commit Message: Fix CVE-2019-13224: don't allow different encodings for onig_new_deluxe() CWE ID: CWE-416
onig_new_deluxe(regex_t** reg, const UChar* pattern, const UChar* pattern_end, OnigCompileInfo* ci, OnigErrorInfo* einfo) { int r; UChar *cpat, *cpat_end; if (IS_NOT_NULL(einfo)) einfo->par = (UChar* )NULL; if (ci->pattern_enc != ci->target_enc) { return ONIGERR_NOT_SUPPORTED_ENCODING_COMBINATION; } else { cpat = (UChar* )pattern; cpat_end = (UChar* )pattern_end; } *reg = (regex_t* )xmalloc(sizeof(regex_t)); if (IS_NULL(*reg)) { r = ONIGERR_MEMORY; goto err2; } r = onig_reg_init(*reg, ci->option, ci->case_fold_flag, ci->target_enc, ci->syntax); if (r != 0) goto err; r = onig_compile(*reg, cpat, cpat_end, einfo); if (r != 0) { err: onig_free(*reg); *reg = NULL; } err2: if (cpat != pattern) xfree(cpat); return r; }
169,613
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: vmxnet3_io_bar0_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { VMXNET3State *s = opaque; if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_TXPROD, VMXNET3_DEVICE_MAX_TX_QUEUES, VMXNET3_REG_ALIGN)) { int tx_queue_idx = return; } if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_IMR, VMXNET3_MAX_INTRS, VMXNET3_REG_ALIGN)) { int l = VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_IMR, VMXNET3_REG_ALIGN); VMW_CBPRN("Interrupt mask for line %d written: 0x%" PRIx64, l, val); vmxnet3_on_interrupt_mask_changed(s, l, val); return; } if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD, VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN) || VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD2, VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN)) { return; } VMW_WRPRN("BAR0 unknown write [%" PRIx64 "] = %" PRIx64 ", size %d", (uint64_t) addr, val, size); } Commit Message: CWE ID: CWE-416
vmxnet3_io_bar0_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { VMXNET3State *s = opaque; if (!s->device_active) { return; } if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_TXPROD, VMXNET3_DEVICE_MAX_TX_QUEUES, VMXNET3_REG_ALIGN)) { int tx_queue_idx = return; } if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_IMR, VMXNET3_MAX_INTRS, VMXNET3_REG_ALIGN)) { int l = VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_IMR, VMXNET3_REG_ALIGN); VMW_CBPRN("Interrupt mask for line %d written: 0x%" PRIx64, l, val); vmxnet3_on_interrupt_mask_changed(s, l, val); return; } if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD, VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN) || VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD2, VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN)) { return; } VMW_WRPRN("BAR0 unknown write [%" PRIx64 "] = %" PRIx64 ", size %d", (uint64_t) addr, val, size); }
164,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: explicit ConsoleCallbackFilter( base::Callback<void(const base::string16&)> callback) : callback_(callback) {} Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <lowell@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
explicit ConsoleCallbackFilter(
172,489
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: psf_asciiheader_printf (SF_PRIVATE *psf, const char *format, ...) { va_list argptr ; int maxlen ; char *start ; maxlen = strlen ((char*) psf->header) ; start = ((char*) psf->header) + maxlen ; maxlen = sizeof (psf->header) - maxlen ; va_start (argptr, format) ; vsnprintf (start, maxlen, format, argptr) ; va_end (argptr) ; /* Make sure the string is properly terminated. */ start [maxlen - 1] = 0 ; psf->headindex = strlen ((char*) psf->header) ; return ; } /* psf_asciiheader_printf */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
psf_asciiheader_printf (SF_PRIVATE *psf, const char *format, ...) { va_list argptr ; int maxlen ; char *start ; maxlen = strlen ((char*) psf->header.ptr) ; start = ((char*) psf->header.ptr) + maxlen ; maxlen = psf->header.len - maxlen ; va_start (argptr, format) ; vsnprintf (start, maxlen, format, argptr) ; va_end (argptr) ; /* Make sure the string is properly terminated. */ start [maxlen - 1] = 0 ; psf->header.indx = strlen ((char*) psf->header.ptr) ; return ; } /* psf_asciiheader_printf */
170,063
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RunAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); uint32_t max_error = 0; int64_t total_error = 0; const int count_test_block = 10000; for (int i = 0; i < count_test_block; ++i) { DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs); for (int j = 0; j < kNumCoeffs; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; } REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block, test_temp_block, pitch_)); REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { const uint32_t diff = dst[j] - src[j]; const uint32_t error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(1u, max_error) << "Error: 16x16 FHT/IHT has an individual round trip error > 1"; EXPECT_GE(count_test_block , total_error) << "Error: 16x16 FHT/IHT has average round trip error > 1 per block"; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); uint32_t max_error = 0; int64_t total_error = 0; const int count_test_block = 10000; for (int i = 0; i < count_test_block; ++i) { DECLARE_ALIGNED(16, int16_t, test_input_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, test_temp_block[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]); #if CONFIG_VP9_HIGHBITDEPTH DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]); DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]); #endif // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < kNumCoeffs; ++j) { if (bit_depth_ == VPX_BITS_8) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; #if CONFIG_VP9_HIGHBITDEPTH } else { src16[j] = rnd.Rand16() & mask_; dst16[j] = rnd.Rand16() & mask_; test_input_block[j] = src16[j] - dst16[j]; #endif } } ASM_REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block, test_temp_block, pitch_)); if (bit_depth_ == VPX_BITS_8) { ASM_REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, dst, pitch_)); #if CONFIG_VP9_HIGHBITDEPTH } else { ASM_REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_)); #endif } for (int j = 0; j < kNumCoeffs; ++j) { #if CONFIG_VP9_HIGHBITDEPTH const uint32_t diff = bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; #else const uint32_t diff = dst[j] - src[j]; #endif const uint32_t error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(1u << 2 * (bit_depth_ - 8), max_error) << "Error: 16x16 FHT/IHT has an individual round trip error > 1"; EXPECT_GE(count_test_block << 2 * (bit_depth_ - 8), total_error) << "Error: 16x16 FHT/IHT has average round trip error > 1 per block"; }
174,519
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: init_device (u2fh_devs * devs, struct u2fdevice *dev) { unsigned char resp[1024]; unsigned char nonce[8]; if (obtain_nonce(nonce) != 0) { return U2FH_TRANSPORT_ERROR; } size_t resplen = sizeof (resp); dev->cid = CID_BROADCAST; if (u2fh_sendrecv (devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp, &resplen) == U2FH_OK) { U2FHID_INIT_RESP initresp; if (resplen > sizeof (initresp)) { return U2FH_MEMORY_ERROR; } memcpy (&initresp, resp, resplen); dev->cid = initresp.cid; dev->versionInterface = initresp.versionInterface; dev->versionMajor = initresp.versionMajor; dev->versionMinor = initresp.versionMinor; dev->capFlags = initresp.capFlags; } else { return U2FH_TRANSPORT_ERROR; } return U2FH_OK; } Commit Message: fix filling out of initresp CWE ID: CWE-119
init_device (u2fh_devs * devs, struct u2fdevice *dev) { unsigned char resp[1024]; unsigned char nonce[8]; if (obtain_nonce(nonce) != 0) { return U2FH_TRANSPORT_ERROR; } size_t resplen = sizeof (resp); dev->cid = CID_BROADCAST; if (u2fh_sendrecv (devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp, &resplen) == U2FH_OK) { int offs = sizeof (nonce); /* the response has to be atleast 17 bytes, if it's more we discard that */ if (resplen < 17) { return U2FH_SIZE_ERROR; } /* incoming and outgoing nonce has to match */ if (memcmp (nonce, resp, sizeof (nonce)) != 0) { return U2FH_TRANSPORT_ERROR; } dev->cid = resp[offs] << 24 | resp[offs + 1] << 16 | resp[offs + 2] << 8 | resp[offs + 3]; offs += 4; dev->versionInterface = resp[offs++]; dev->versionMajor = resp[offs++]; dev->versionMinor = resp[offs++]; dev->versionBuild = resp[offs++]; dev->capFlags = resp[offs++]; } else { return U2FH_TRANSPORT_ERROR; } return U2FH_OK; }
169,721
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DevToolsDomainHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) {} Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void DevToolsDomainHandler::SetRenderer(RenderProcessHost* process_host, void DevToolsDomainHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) {}
172,744
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool AddPolicyForGPU(CommandLine* cmd_line, sandbox::TargetPolicy* policy) { #if !defined(NACL_WIN64) // We don't need this code on win nacl64. if (base::win::GetVersion() > base::win::VERSION_SERVER_2003) { if (cmd_line->GetSwitchValueASCII(switches::kUseGL) == gfx::kGLImplementationDesktopName) { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_LIMITED); policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); } else { if (cmd_line->GetSwitchValueASCII(switches::kUseGL) == gfx::kGLImplementationSwiftShaderName || cmd_line->HasSwitch(switches::kReduceGpuSandbox)) { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_LIMITED); policy->SetJobLevel(sandbox::JOB_LIMITED_USER, JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS); } else { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_RESTRICTED); policy->SetJobLevel(sandbox::JOB_LOCKDOWN, JOB_OBJECT_UILIMIT_HANDLES); } policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); } } else { policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0); policy->SetTokenLevel(sandbox::USER_UNPROTECTED, sandbox::USER_LIMITED); } sandbox::ResultCode result = policy->AddRule( sandbox::TargetPolicy::SUBSYS_NAMED_PIPES, sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY, L"\\\\.\\pipe\\chrome.gpu.*"); if (result != sandbox::SBOX_ALL_OK) return false; AddGenericDllEvictionPolicy(policy); #endif return true; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool AddPolicyForGPU(CommandLine* cmd_line, sandbox::TargetPolicy* policy) { #if !defined(NACL_WIN64) // We don't need this code on win nacl64. if (base::win::GetVersion() > base::win::VERSION_SERVER_2003) { if (cmd_line->GetSwitchValueASCII(switches::kUseGL) == gfx::kGLImplementationDesktopName) { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_LIMITED); policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); } else { if (cmd_line->GetSwitchValueASCII(switches::kUseGL) == gfx::kGLImplementationSwiftShaderName || cmd_line->HasSwitch(switches::kReduceGpuSandbox)) { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_LIMITED); policy->SetJobLevel(sandbox::JOB_LIMITED_USER, JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS); } else { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_RESTRICTED); policy->SetJobLevel(sandbox::JOB_LOCKDOWN, JOB_OBJECT_UILIMIT_HANDLES); } policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); } } else { policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0); policy->SetTokenLevel(sandbox::USER_UNPROTECTED, sandbox::USER_LIMITED); } sandbox::ResultCode result = policy->AddRule( sandbox::TargetPolicy::SUBSYS_NAMED_PIPES, sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY, L"\\\\.\\pipe\\chrome.gpu.*"); if (result != sandbox::SBOX_ALL_OK) return false; // GPU needs to copy sections to renderers. result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; AddGenericDllEvictionPolicy(policy); #endif return true; }
170,944
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: gplotMakeOutput(GPLOT *gplot) { char buf[L_BUF_SIZE]; char *cmdname; l_int32 ignore; PROCNAME("gplotMakeOutput"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); gplotGenCommandFile(gplot); gplotGenDataFiles(gplot); cmdname = genPathname(gplot->cmdname, NULL); #ifndef _WIN32 snprintf(buf, L_BUF_SIZE, "gnuplot %s", cmdname); #else snprintf(buf, L_BUF_SIZE, "wgnuplot %s", cmdname); #endif /* _WIN32 */ #ifndef OS_IOS /* iOS 11 does not support system() */ ignore = system(buf); /* gnuplot || wgnuplot */ #endif /* !OS_IOS */ LEPT_FREE(cmdname); return 0; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
gplotMakeOutput(GPLOT *gplot) { char buf[L_BUFSIZE]; char *cmdname; l_int32 ignore; PROCNAME("gplotMakeOutput"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); gplotGenCommandFile(gplot); gplotGenDataFiles(gplot); cmdname = genPathname(gplot->cmdname, NULL); #ifndef _WIN32 snprintf(buf, L_BUFSIZE, "gnuplot %s", cmdname); #else snprintf(buf, L_BUFSIZE, "wgnuplot %s", cmdname); #endif /* _WIN32 */ #ifndef OS_IOS /* iOS 11 does not support system() */ ignore = system(buf); /* gnuplot || wgnuplot */ #endif /* !OS_IOS */ LEPT_FREE(cmdname); return 0; }
169,326
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view) : content::RenderViewObserver(render_view), content::RenderViewObserverTracker<PrintWebViewHelper>(render_view), print_web_view_(NULL), is_preview_enabled_(IsPrintPreviewEnabled()), is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()), is_print_ready_metafile_sent_(false), ignore_css_margins_(false), user_cancelled_scripted_print_count_(0), is_scripted_printing_blocked_(false), notify_browser_of_print_failure_(true), print_for_preview_(false) { } Commit Message: Guard against the same PrintWebViewHelper being re-entered. BUG=159165 Review URL: https://chromiumcodereview.appspot.com/11367076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view) : content::RenderViewObserver(render_view), content::RenderViewObserverTracker<PrintWebViewHelper>(render_view), print_web_view_(NULL), is_preview_enabled_(IsPrintPreviewEnabled()), is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()), is_print_ready_metafile_sent_(false), ignore_css_margins_(false), user_cancelled_scripted_print_count_(0), is_scripted_printing_blocked_(false), notify_browser_of_print_failure_(true), print_for_preview_(false), print_node_in_progress_(false) { }
170,698
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BrowserMainParts::PostDestroyThreads() { if (BrowserProcessMain::GetInstance()->GetProcessModel() == PROCESS_MODEL_SINGLE_PROCESS) { BrowserContext::AssertNoContextsExist(); } device_client_.reset(); display::Screen::SetScreenInstance(nullptr); gpu::oxide_shim::SetGLShareGroup(nullptr); gl_share_context_ = nullptr; #if defined(OS_LINUX) gpu::SetGpuInfoCollectorOxideLinux(nullptr); #endif } Commit Message: CWE ID: CWE-20
void BrowserMainParts::PostDestroyThreads() { device_client_.reset(); display::Screen::SetScreenInstance(nullptr); gpu::oxide_shim::SetGLShareGroup(nullptr); gl_share_context_ = nullptr; #if defined(OS_LINUX) gpu::SetGpuInfoCollectorOxideLinux(nullptr); #endif }
165,422
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int32 CommandBufferProxyImpl::RegisterTransferBuffer( base::SharedMemory* shared_memory, size_t size, int32 id_request) { if (last_state_.error != gpu::error::kNoError) return -1; int32 id; if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer( route_id_, shared_memory->handle(), // Returns FileDescriptor with auto_close off. size, id_request, &id))) { return -1; } return id; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
int32 CommandBufferProxyImpl::RegisterTransferBuffer( base::SharedMemory* shared_memory, size_t size, int32 id_request) { if (last_state_.error != gpu::error::kNoError) return -1; // Returns FileDescriptor with auto_close off. base::SharedMemoryHandle handle = shared_memory->handle(); #if defined(OS_WIN) // Windows needs to explicitly duplicate the handle out to another process. if (!sandbox::BrokerDuplicateHandle(handle, channel_->gpu_pid(), &handle, FILE_MAP_WRITE, 0)) { return -1; } #endif int32 id; if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer( route_id_, handle, size, id_request, &id))) { return -1; } return id; }
170,927
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t OMXNodeInstance::updateNativeHandleInMeta( OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) { return BAD_VALUE; } BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate); sp<ABuffer> data = bufferMeta->getBuffer( header, portIndex == kPortIndexInput /* backup */, false /* limit */); bufferMeta->setNativeHandle(nativeHandle); if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource && data->capacity() >= sizeof(VideoNativeHandleMetadata)) { VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data()); metadata.eType = mMetadataType[portIndex]; metadata.pHandle = nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle()); } else { CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)", portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity()); return BAD_VALUE; } CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p", portString(portIndex), portIndex, buffer, nativeHandle == NULL ? NULL : nativeHandle->handle()); return OK; } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::updateNativeHandleInMeta( OMX_U32 portIndex, const sp<NativeHandle>& nativeHandle, OMX::buffer_id buffer) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex); if (header == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) { return BAD_VALUE; } BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate); sp<ABuffer> data = bufferMeta->getBuffer( header, false /* backup */, false /* limit */); bufferMeta->setNativeHandle(nativeHandle); if (mMetadataType[portIndex] == kMetadataBufferTypeNativeHandleSource && data->capacity() >= sizeof(VideoNativeHandleMetadata)) { VideoNativeHandleMetadata &metadata = *(VideoNativeHandleMetadata *)(data->data()); metadata.eType = mMetadataType[portIndex]; metadata.pHandle = nativeHandle == NULL ? NULL : const_cast<native_handle*>(nativeHandle->handle()); } else { CLOG_ERROR(updateNativeHandleInMeta, BAD_VALUE, "%s:%u, %#x bad type (%d) or size (%zu)", portString(portIndex), portIndex, buffer, mMetadataType[portIndex], data->capacity()); return BAD_VALUE; } CLOG_BUFFER(updateNativeHandleInMeta, "%s:%u, %#x := %p", portString(portIndex), portIndex, buffer, nativeHandle == NULL ? NULL : nativeHandle->handle()); return OK; }
174,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool V8DOMWindow::namedSecurityCheckCustom(v8::Local<v8::Object> host, v8::Local<v8::Value> key, v8::AccessType type, v8::Local<v8::Value>) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Handle<v8::Object> window = host->FindInstanceInPrototypeChain(V8DOMWindow::GetTemplate(isolate, worldTypeInMainThread(isolate))); if (window.IsEmpty()) return false; // the frame is gone. DOMWindow* targetWindow = V8DOMWindow::toNative(window); ASSERT(targetWindow); Frame* target = targetWindow->frame(); if (!target) return false; if (target->loader()->stateMachine()->isDisplayingInitialEmptyDocument()) target->loader()->didAccessInitialDocument(); if (key->IsString()) { DEFINE_STATIC_LOCAL(AtomicString, nameOfProtoProperty, ("__proto__", AtomicString::ConstructFromLiteral)); String name = toWebCoreString(key); Frame* childFrame = target->tree()->scopedChild(name); if (type == v8::ACCESS_HAS && childFrame) return true; if (type == v8::ACCESS_GET && childFrame && !host->HasRealNamedProperty(key->ToString()) && name != nameOfProtoProperty) return true; } return BindingSecurity::shouldAllowAccessToFrame(target, DoNotReportSecurityError); } Commit Message: Named access checks on DOMWindow miss navigator The design of the named access check is very fragile. Instead of doing the access check at the same time as the access, we need to check access in a separate operation using different parameters. Worse, we need to implement a part of the access check as a blacklist of dangerous properties. This CL expands the blacklist slightly by adding in the real named properties from the DOMWindow instance to the current list (which included the real named properties of the shadow object). In the longer term, we should investigate whether we can change the V8 API to let us do the access check in the same callback as the property access itself. BUG=237022 Review URL: https://chromiumcodereview.appspot.com/15346002 git-svn-id: svn://svn.chromium.org/blink/trunk@150616 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
bool V8DOMWindow::namedSecurityCheckCustom(v8::Local<v8::Object> host, v8::Local<v8::Value> key, v8::AccessType type, v8::Local<v8::Value>) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Handle<v8::Object> window = host->FindInstanceInPrototypeChain(V8DOMWindow::GetTemplate(isolate, worldTypeInMainThread(isolate))); if (window.IsEmpty()) return false; // the frame is gone. DOMWindow* targetWindow = V8DOMWindow::toNative(window); ASSERT(targetWindow); Frame* target = targetWindow->frame(); if (!target) return false; if (target->loader()->stateMachine()->isDisplayingInitialEmptyDocument()) target->loader()->didAccessInitialDocument(); if (key->IsString()) { DEFINE_STATIC_LOCAL(AtomicString, nameOfProtoProperty, ("__proto__", AtomicString::ConstructFromLiteral)); String name = toWebCoreString(key); Frame* childFrame = target->tree()->scopedChild(name); if (type == v8::ACCESS_HAS && childFrame) return true; v8::Handle<v8::String> keyString = key->ToString(); if (type == v8::ACCESS_GET && childFrame && !host->HasRealNamedProperty(keyString) && !window->HasRealNamedProperty(keyString) && name != nameOfProtoProperty) return true; } return BindingSecurity::shouldAllowAccessToFrame(target, DoNotReportSecurityError); }
171,335
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: status_t SampleTable::setSyncSampleParams(off64_t data_offset, size_t data_size) { if (mSyncSampleOffset >= 0 || data_size < 8) { return ERROR_MALFORMED; } mSyncSampleOffset = data_offset; uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mNumSyncSamples = U32_AT(&header[4]); if (mNumSyncSamples < 2) { ALOGV("Table of sync samples is empty or has only a single entry!"); } uint64_t allocSize = mNumSyncSamples * sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mSyncSamples = new uint32_t[mNumSyncSamples]; size_t size = mNumSyncSamples * sizeof(uint32_t); if (mDataSource->readAt(mSyncSampleOffset + 8, mSyncSamples, size) != (ssize_t)size) { return ERROR_IO; } for (size_t i = 0; i < mNumSyncSamples; ++i) { mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1; } return OK; } Commit Message: Fix several ineffective integer overflow checks Commit edd4a76 (which addressed bugs 15328708, 15342615, 15342751) added several integer overflow checks. Unfortunately, those checks fail to take into account integer promotion rules and are thus themselves subject to an integer overflow. Cast the sizeof() operator to a uint64_t to force promotion while multiplying. Bug: 20139950 (cherry picked from commit e2e812e58e8d2716b00d7d82db99b08d3afb4b32) Change-Id: I080eb3fa147601f18cedab86e0360406c3963d7b CWE ID: CWE-189
status_t SampleTable::setSyncSampleParams(off64_t data_offset, size_t data_size) { if (mSyncSampleOffset >= 0 || data_size < 8) { return ERROR_MALFORMED; } mSyncSampleOffset = data_offset; uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mNumSyncSamples = U32_AT(&header[4]); if (mNumSyncSamples < 2) { ALOGV("Table of sync samples is empty or has only a single entry!"); } uint64_t allocSize = mNumSyncSamples * (uint64_t)sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mSyncSamples = new uint32_t[mNumSyncSamples]; size_t size = mNumSyncSamples * sizeof(uint32_t); if (mDataSource->readAt(mSyncSampleOffset + 8, mSyncSamples, size) != (ssize_t)size) { return ERROR_IO; } for (size_t i = 0; i < mNumSyncSamples; ++i) { mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1; } return OK; }
173,338
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int csum_len_for_type(int cst) { switch (cst) { case CSUM_NONE: return 1; case CSUM_ARCHAIC: return 2; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: return MD4_DIGEST_LEN; case CSUM_MD5: return MD5_DIGEST_LEN; } return 0; } Commit Message: CWE ID: CWE-354
int csum_len_for_type(int cst) { switch (cst) { case CSUM_NONE: return 1; case CSUM_MD4_ARCHAIC: return 2; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: return MD4_DIGEST_LEN; case CSUM_MD5: return MD5_DIGEST_LEN; } return 0; }
164,642
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: mark_trusted_task_thread_func (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) { MarkTrustedJob *job = task_data; CommonJob *common; common = (CommonJob *) job; nautilus_progress_info_start (job->common.progress); mark_desktop_file_trusted (common, cancellable, job->file, job->interactive); } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20
mark_trusted_task_thread_func (GTask *task, mark_desktop_file_executable_task_thread_func (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable) { MarkTrustedJob *job = task_data; CommonJob *common; common = (CommonJob *) job; nautilus_progress_info_start (job->common.progress); mark_desktop_file_executable (common, cancellable, job->file, job->interactive); }
167,750
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void serial_update_parameters(SerialState *s) { int speed, parity, data_bits, stop_bits, frame_size; QEMUSerialSetParams ssp; if (s->divider == 0) return; /* Start bit. */ frame_size = 1; /* Parity bit. */ frame_size++; if (s->lcr & 0x10) parity = 'E'; else parity = 'O'; } else { parity = 'N'; } Commit Message: CWE ID: CWE-369
static void serial_update_parameters(SerialState *s) { int speed, parity, data_bits, stop_bits, frame_size; QEMUSerialSetParams ssp; if (s->divider == 0 || s->divider > s->baudbase) { return; } /* Start bit. */ frame_size = 1; /* Parity bit. */ frame_size++; if (s->lcr & 0x10) parity = 'E'; else parity = 'O'; } else { parity = 'N'; }
164,910
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CastCastView::ButtonPressed(views::Button* sender, const ui::Event& event) { DCHECK(sender == stop_button_); StopCast(); } Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods. BUG=489445 Review URL: https://codereview.chromium.org/1145833003 Cr-Commit-Position: refs/heads/master@{#330663} CWE ID: CWE-79
void CastCastView::ButtonPressed(views::Button* sender, const ui::Event& event) { DCHECK(sender == stop_button_); cast_config_delegate_->StopCasting(); }
171,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PS_SERIALIZER_DECODE_FUNC(php_serialize) /* {{{ */ { const char *endptr = val + vallen; zval *session_vars; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); ALLOC_INIT_ZVAL(session_vars); if (php_var_unserialize(&session_vars, &val, endptr, &var_hash TSRMLS_CC)) { var_push_dtor(&var_hash, &session_vars); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PS(http_session_vars)) { zval_ptr_dtor(&PS(http_session_vars)); } if (Z_TYPE_P(session_vars) == IS_NULL) { array_init(session_vars); } PS(http_session_vars) = session_vars; ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), Z_REFCOUNT_P(PS(http_session_vars)) + 1, 1); return SUCCESS; } /* }}} */ Commit Message: CWE ID: CWE-416
PS_SERIALIZER_DECODE_FUNC(php_serialize) /* {{{ */ { const char *endptr = val + vallen; zval *session_vars; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); ALLOC_INIT_ZVAL(session_vars); if (php_var_unserialize(&session_vars, &val, endptr, &var_hash TSRMLS_CC)) { var_push_dtor(&var_hash, &session_vars); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PS(http_session_vars)) { zval_ptr_dtor(&PS(http_session_vars)); } if (Z_TYPE_P(session_vars) == IS_NULL) { array_init(session_vars); } PS(http_session_vars) = session_vars; ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), Z_REFCOUNT_P(PS(http_session_vars)) + 1, 1); return SUCCESS; } /* }}} */
164,980
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: l2tp_ppp_discon_cc_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%04x, ", EXTRACT_16BITS(ptr))); ptr++; /* Disconnect Code */ ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(ptr))); ptr++; /* Control Protocol Number */ ND_PRINT((ndo, "%s", tok2str(l2tp_cc_direction2str, "Direction-#%u", *((const u_char *)ptr++)))); if (length > 5) { ND_PRINT((ndo, " ")); print_string(ndo, (const u_char *)ptr, length-5); } } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_ppp_discon_cc_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; if (length < 5) { ND_PRINT((ndo, "AVP too short")); return; } /* Disconnect Code */ ND_PRINT((ndo, "%04x, ", EXTRACT_16BITS(dat))); dat += 2; length -= 2; /* Control Protocol Number */ ND_PRINT((ndo, "%04x ", EXTRACT_16BITS(dat))); dat += 2; length -= 2; /* Direction */ ND_PRINT((ndo, "%s", tok2str(l2tp_cc_direction2str, "Direction-#%u", EXTRACT_8BITS(ptr)))); ptr++; length--; if (length != 0) { ND_PRINT((ndo, " ")); print_string(ndo, (const u_char *)ptr, length); } }
167,897
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) { inv_txfm_(out, dst, stride); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) { void RunInvTxfm(const tran_low_t *out, uint8_t *dst, int stride) { inv_txfm_(out, dst, stride); }
174,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool dstBufferSizeHasOverflow(ParsedOptions options) { CheckedNumeric<size_t> totalBytes = options.cropRect.width(); totalBytes *= options.cropRect.height(); totalBytes *= options.bytesPerPixel; if (!totalBytes.IsValid()) return true; if (!options.shouldScaleInput) return false; totalBytes = options.resizeWidth; totalBytes *= options.resizeHeight; totalBytes *= options.bytesPerPixel; if (!totalBytes.IsValid()) return true; return false; } Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull Currently when ImageBitmap's constructor is invoked, we check whether dstSize will overflow size_t or not. The problem comes when we call ArrayBuffer::createOrNull some times in the code. Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap when we call this method, the first parameter is usually width * height. This could overflow unsigned even if it has been checked safe with size_t, the reason is that unsigned is a 32-bit value on 64-bit systems, while size_t is a 64-bit value. This CL makes a change such that we check whether the dstSize will overflow unsigned or not. In this case, we can guarantee that createOrNull will not have any crash. BUG=664139 Review-Url: https://codereview.chromium.org/2500493002 Cr-Commit-Position: refs/heads/master@{#431936} CWE ID: CWE-787
bool dstBufferSizeHasOverflow(ParsedOptions options) { CheckedNumeric<unsigned> totalBytes = options.cropRect.width(); totalBytes *= options.cropRect.height(); totalBytes *= options.bytesPerPixel; if (!totalBytes.IsValid()) return true; if (!options.shouldScaleInput) return false; totalBytes = options.resizeWidth; totalBytes *= options.resizeHeight; totalBytes *= options.bytesPerPixel; if (!totalBytes.IsValid()) return true; return false; }
172,501
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool Browser::CanCloseContentsAt(int index) { if (!CanCloseTab()) return false; if (tab_handler_->GetTabStripModel()->count() > 1) return true; return CanCloseWithInProgressDownloads(); } Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab. BUG=chromium-os:12088 TEST=verify bug per bug report. Review URL: http://codereview.chromium.org/6882058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool Browser::CanCloseContentsAt(int index) { bool Browser::CanCloseContents(std::vector<int>* indices) { DCHECK(!indices->empty()); TabCloseableStateWatcher* watcher = g_browser_process->tab_closeable_state_watcher(); bool can_close_all = !watcher || watcher->CanCloseTabs(this, indices); if (indices->empty()) // Cannot close any tab. return false; // Now, handle cases where at least one tab can be closed. // If we are closing all the tabs for this browser, make sure to check for if (tab_handler_->GetTabStripModel()->count() == static_cast<int>(indices->size()) && !CanCloseWithInProgressDownloads()) { indices->clear(); can_close_all = false; } return can_close_all; }
170,303
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void virgl_resource_attach_backing(VirtIOGPU *g, struct virtio_gpu_ctrl_command *cmd) { struct virtio_gpu_resource_attach_backing att_rb; struct iovec *res_iovs; int ret; VIRTIO_GPU_FILL_CMD(att_rb); trace_virtio_gpu_cmd_res_back_attach(att_rb.resource_id); ret = virtio_gpu_create_mapping_iov(&att_rb, cmd, NULL, &res_iovs); if (ret != 0) { cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC; return; } virgl_renderer_resource_attach_iov(att_rb.resource_id, res_iovs, att_rb.nr_entries); } Commit Message: CWE ID: CWE-772
static void virgl_resource_attach_backing(VirtIOGPU *g, struct virtio_gpu_ctrl_command *cmd) { struct virtio_gpu_resource_attach_backing att_rb; struct iovec *res_iovs; int ret; VIRTIO_GPU_FILL_CMD(att_rb); trace_virtio_gpu_cmd_res_back_attach(att_rb.resource_id); ret = virtio_gpu_create_mapping_iov(&att_rb, cmd, NULL, &res_iovs); if (ret != 0) { cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC; return; } ret = virgl_renderer_resource_attach_iov(att_rb.resource_id, res_iovs, att_rb.nr_entries); if (ret != 0) virtio_gpu_cleanup_mapping_iov(res_iovs, att_rb.nr_entries); }
164,988
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool BluetoothDeviceChromeOS::ExpectingPinCode() const { return !pincode_callback_.is_null(); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool BluetoothDeviceChromeOS::ExpectingPinCode() const { return pairing_context_.get() && pairing_context_->ExpectingPinCode(); }
171,226
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int Chapters::Atom::GetDisplayCount() const { return m_displays_count; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
int Chapters::Atom::GetDisplayCount() const
174,305
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void CancelHandwritingStrokes(int stroke_count) { if (!initialized_successfully_) return; chromeos::CancelHandwriting(input_method_status_connection_, stroke_count); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual void CancelHandwritingStrokes(int stroke_count) { if (!initialized_successfully_) return; ibus_controller_->CancelHandwriting(stroke_count); }
170,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) { int totlen; uint32_t t; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } Commit Message: CVE-2017-13039/IKEv1: Do more bounds checking. Have ikev1_attrmap_print() and ikev1_attr_print() do full bounds checking, and return null on a bounds overflow. Have their callers check for a null return. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125
ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) { int totlen; uint32_t t; ND_TCHECK(p[0]); if (p[0] & 0x80) totlen = 4; else { ND_TCHECK_16BITS(&p[2]); totlen = 4 + EXTRACT_16BITS(&p[2]); } if (ep2 < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep2 + 1; } ND_TCHECK_16BITS(&p[0]); ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ND_PRINT((ndo,")")); goto trunc; } } else { ND_PRINT((ndo,"len=%d value=", totlen - 4)); if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); return p + totlen; trunc: return NULL; }
167,839
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void _modinit(module_t *m) { service_named_bind_command("chanserv", &cs_flags); } Commit Message: chanserv/flags: make Anope FLAGS compatibility an option Previously, ChanServ FLAGS behavior could be modified by registering or dropping the keyword nicks "LIST", "CLEAR", and "MODIFY". Now, a configuration option is available that when turned on (default), disables registration of these keyword nicks and enables this compatibility feature. When turned off, registration of these keyword nicks is possible, and compatibility to Anope's FLAGS command is disabled. Fixes atheme/atheme#397 CWE ID: CWE-284
void _modinit(module_t *m) { service_named_bind_command("chanserv", &cs_flags); add_bool_conf_item("ANOPE_FLAGS_COMPAT", &chansvs.me->conf_table, 0, &anope_flags_compat, true); hook_add_event("nick_can_register"); hook_add_nick_can_register(check_registration_keywords); hook_add_event("user_can_register"); hook_add_user_can_register(check_registration_keywords); }
167,586
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CameraSource::releaseQueuedFrames() { List<sp<IMemory> >::iterator it; while (!mFramesReceived.empty()) { it = mFramesReceived.begin(); releaseRecordingFrame(*it); mFramesReceived.erase(it); ++mNumFramesDropped; } } Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak Subtract address of a random static object from pointers being routed through app process. Bug: 28466701 Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04 CWE ID: CWE-200
void CameraSource::releaseQueuedFrames() { List<sp<IMemory> >::iterator it; while (!mFramesReceived.empty()) { it = mFramesReceived.begin(); // b/28466701 adjustOutgoingANWBuffer(it->get()); releaseRecordingFrame(*it); mFramesReceived.erase(it); ++mNumFramesDropped; } }
173,509
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: WebString WebPageSerializer::generateBaseTagDeclaration(const WebString& baseTarget) { if (baseTarget.isEmpty()) return String("<base href=\".\">"); String baseString = "<base href=\".\" target=\"" + static_cast<const String&>(baseTarget) + "\">"; return baseString; } Commit Message: Escape "--" in the page URL at page serialization This patch makes page serializer to escape the page URL embed into a HTML comment of result HTML[1] to avoid inserting text as HTML from URL by introducing a static member function |PageSerialzier::markOfTheWebDeclaration()| for sharing it between |PageSerialzier| and |WebPageSerialzier| classes. [1] We use following format for serialized HTML: saved from url=(${lengthOfURL})${URL} BUG=503217 TEST=webkit_unit_tests --gtest_filter=PageSerializerTest.markOfTheWebDeclaration TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.fromUrlWithMinusMinu Review URL: https://codereview.chromium.org/1371323003 Cr-Commit-Position: refs/heads/master@{#351736} CWE ID: CWE-20
WebString WebPageSerializer::generateBaseTagDeclaration(const WebString& baseTarget) { // TODO(yosin) We should call |PageSerializer::baseTagDeclarationOf()|. if (baseTarget.isEmpty()) return String("<base href=\".\">"); String baseString = "<base href=\".\" target=\"" + static_cast<const String&>(baseTarget) + "\">"; return baseString; }
171,786
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) { uint8_t desc[20]; uint32_t i; *flags |= FLAGS_DID_BUILD_ID; if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" : "sha1") == -1) return 1; (void)memcpy(desc, &nbuf[doff], descsz); for (i = 0; i < descsz; i++) if (file_printf(ms, "%02x", desc[i]) == -1) return 1; return 1; } return 0; } Commit Message: Extend build-id reporting to 8-byte IDs that lld can generate (Ed Maste) CWE ID: CWE-119
do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_BUILD_ID && (descsz >= 4 || descsz <= 20)) { uint8_t desc[20]; const char *btype; uint32_t i; *flags |= FLAGS_DID_BUILD_ID; switch (descsz) { case 8: btype = "xxHash"; break; case 16: btype = "md5/uuid"; break; case 20: btype = "sha1"; break; default: btype = "unknown"; break; } if (file_printf(ms, ", BuildID[%s]=", btype) == -1) return 1; (void)memcpy(desc, &nbuf[doff], descsz); for (i = 0; i < descsz; i++) if (file_printf(ms, "%02x", desc[i]) == -1) return 1; return 1; } return 0; }
170,010
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BOOL transport_connect_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->layer == TRANSPORT_LAYER_TSG) return TRUE; if (!transport_connect_tls(transport)) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { if (!connectErrorCode) connectErrorCode = AUTHENTICATIONERROR; fprintf(stderr, "Authentication failure, check credentials.\n" "If credentials are valid, the NTLMSSP implementation may be to blame.\n"); credssp_free(transport->credssp); return FALSE; } credssp_free(transport->credssp); return TRUE; } Commit Message: nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished. CWE ID: CWE-476
BOOL transport_connect_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->layer == TRANSPORT_LAYER_TSG) return TRUE; if (!transport_connect_tls(transport)) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { if (!connectErrorCode) connectErrorCode = AUTHENTICATIONERROR; fprintf(stderr, "Authentication failure, check credentials.\n" "If credentials are valid, the NTLMSSP implementation may be to blame.\n"); credssp_free(transport->credssp); transport->credssp = NULL; return FALSE; } credssp_free(transport->credssp); return TRUE; }
167,602
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool FrameFetchContext::UpdateTimingInfoForIFrameNavigation( ResourceTimingInfo* info) { if (IsDetached()) return false; if (!GetFrame()->Owner()) return false; if (!GetFrame()->should_send_resource_timing_info_to_parent()) return false; if (MasterDocumentLoader()->LoadType() == WebFrameLoadType::kBackForward) return false; return true; } Commit Message: Do not forward resource timing to parent frame after back-forward navigation LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to send timing info to parent except for the first navigation. This flag is cleared when the first timing is sent to parent, however this does not happen if iframe's first navigation was by back-forward navigation. For such iframes, we shouldn't send timings to parent at all. Bug: 876822 Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5 Reviewed-on: https://chromium-review.googlesource.com/1186215 Reviewed-by: Kinuko Yasuda <kinuko@chromium.org> Commit-Queue: Kunihiko Sakamoto <ksakamoto@chromium.org> Cr-Commit-Position: refs/heads/master@{#585736} CWE ID: CWE-200
bool FrameFetchContext::UpdateTimingInfoForIFrameNavigation( ResourceTimingInfo* info) { if (IsDetached()) return false; if (!GetFrame()->Owner()) return false; if (!GetFrame()->should_send_resource_timing_info_to_parent()) return false; // location may have been changed after initial navigation, if (MasterDocumentLoader()->LoadType() == WebFrameLoadType::kBackForward) { // ...and do not report subsequent navigations in the iframe too. GetFrame()->SetShouldSendResourceTimingInfoToParent(false); return false; } return true; }
172,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void FrameFetchContext::AddResourceTiming(const ResourceTimingInfo& info) { if (!document_) return; LocalFrame* frame = document_->GetFrame(); if (!frame) return; if (info.IsMainResource()) { DCHECK(frame->Owner()); frame->Owner()->AddResourceTiming(info); frame->DidSendResourceTimingInfoToParent(); return; } DOMWindowPerformance::performance(*document_->domWindow()) ->GenerateAndAddResourceTiming(info); } Commit Message: Do not forward resource timing to parent frame after back-forward navigation LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to send timing info to parent except for the first navigation. This flag is cleared when the first timing is sent to parent, however this does not happen if iframe's first navigation was by back-forward navigation. For such iframes, we shouldn't send timings to parent at all. Bug: 876822 Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5 Reviewed-on: https://chromium-review.googlesource.com/1186215 Reviewed-by: Kinuko Yasuda <kinuko@chromium.org> Commit-Queue: Kunihiko Sakamoto <ksakamoto@chromium.org> Cr-Commit-Position: refs/heads/master@{#585736} CWE ID: CWE-200
void FrameFetchContext::AddResourceTiming(const ResourceTimingInfo& info) { if (!document_) return; LocalFrame* frame = document_->GetFrame(); if (!frame) return; if (info.IsMainResource()) { DCHECK(frame->Owner()); frame->Owner()->AddResourceTiming(info); frame->SetShouldSendResourceTimingInfoToParent(false); return; } DOMWindowPerformance::performance(*document_->domWindow()) ->GenerateAndAddResourceTiming(info); }
172,656
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: my_object_many_return (MyObject *obj, guint32 *arg0, char **arg1, gint32 *arg2, guint32 *arg3, guint32 *arg4, const char **arg5, GError **error) { *arg0 = 42; *arg1 = g_strdup ("42"); *arg2 = -67; *arg3 = 2; *arg4 = 26; *arg5 = "hello world"; /* Annotation specifies as const */ return TRUE; } Commit Message: CWE ID: CWE-264
my_object_many_return (MyObject *obj, guint32 *arg0, char **arg1, gint32 *arg2, guint32 *arg3, guint32 *arg4, const char **arg5, GError **error)
165,111
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH))); return NULL; }
167,791
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BufferPresented(params.route_id, false, 0)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; delayed_send.Cancel(); static const base::TimeDelta swap_delay = GetSwapDelay(); if (swap_delay.ToInternalValue()) base::PlatformThread::Sleep(swap_delay); view->AcceleratedSurfaceBuffersSwapped(params, host_id_); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped( const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) { TRACE_EVENT0("renderer", "GpuProcessHostUIShim::OnAcceleratedSurfaceBuffersSwapped"); ScopedSendOnIOThread delayed_send( host_id_, new AcceleratedSurfaceMsg_BufferPresented(params.route_id, params.surface_handle, 0)); RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID( params.surface_id); if (!view) return; delayed_send.Cancel(); static const base::TimeDelta swap_delay = GetSwapDelay(); if (swap_delay.ToInternalValue()) base::PlatformThread::Sleep(swap_delay); view->AcceleratedSurfaceBuffersSwapped(params, host_id_); }
171,357
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ExtensionServiceBackend::OnExtensionInstalled( const scoped_refptr<const Extension>& extension) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (frontend_.get()) frontend_->OnExtensionInstalled(extension); } Commit Message: Unrevert: Show the install dialog for the initial load of an unpacked extension with plugins. First landing broke some browser tests. BUG=83273 TEST=in the extensions managmenet page, with developer mode enabled, Load an unpacked extension on an extension with NPAPI plugins. You should get an install dialog. TBR=mihaip git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87738 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionServiceBackend::OnExtensionInstalled( void ExtensionServiceBackend::OnLoadSingleExtension( const scoped_refptr<const Extension>& extension) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (frontend_.get()) frontend_->OnLoadSingleExtension(extension); }
170,408
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: MockRenderProcess::MockRenderProcess() : transport_dib_next_sequence_number_(0) { } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
MockRenderProcess::MockRenderProcess() : transport_dib_next_sequence_number_(0), enabled_bindings_(0) { }
171,020
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void MediaStreamDevicesController::Accept(bool update_content_setting) { if (content_settings_) content_settings_->OnMediaStreamAllowed(); NotifyUIRequestAccepted(); content::MediaStreamDevices devices; if (microphone_requested_ || webcam_requested_) { switch (request_.request_type) { case content::MEDIA_OPEN_DEVICE: MediaCaptureDevicesDispatcher::GetInstance()->GetRequestedDevice( request_.requested_device_id, request_.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE, request_.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE, &devices); break; case content::MEDIA_DEVICE_ACCESS: case content::MEDIA_GENERATE_STREAM: case content::MEDIA_ENUMERATE_DEVICES: MediaCaptureDevicesDispatcher::GetInstance()-> GetDefaultDevicesForProfile(profile_, microphone_requested_, webcam_requested_, &devices); break; } if (update_content_setting && IsSchemeSecure() && !devices.empty()) SetPermission(true); } scoped_ptr<content::MediaStreamUI> ui; if (!devices.empty()) { ui = MediaCaptureDevicesDispatcher::GetInstance()-> GetMediaStreamCaptureIndicator()->RegisterMediaStream( web_contents_, devices); } content::MediaResponseCallback cb = callback_; callback_.Reset(); cb.Run(devices, ui.Pass()); } Commit Message: Make the content setting for webcam/mic sticky for Pepper requests. This makes the content setting sticky for webcam/mic requests from Pepper from non-https origins. BUG=249335 R=xians@chromium.org, yzshen@chromium.org Review URL: https://codereview.chromium.org/17060006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@206479 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void MediaStreamDevicesController::Accept(bool update_content_setting) { if (content_settings_) content_settings_->OnMediaStreamAllowed(); NotifyUIRequestAccepted(); content::MediaStreamDevices devices; if (microphone_requested_ || webcam_requested_) { switch (request_.request_type) { case content::MEDIA_OPEN_DEVICE: MediaCaptureDevicesDispatcher::GetInstance()->GetRequestedDevice( request_.requested_device_id, request_.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE, request_.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE, &devices); break; case content::MEDIA_DEVICE_ACCESS: case content::MEDIA_GENERATE_STREAM: case content::MEDIA_ENUMERATE_DEVICES: MediaCaptureDevicesDispatcher::GetInstance()-> GetDefaultDevicesForProfile(profile_, microphone_requested_, webcam_requested_, &devices); break; } // TODO(raymes): We currently set the content permission for non-https // websites for Pepper requests as well. This is temporary and should be // removed. if (update_content_setting) { if ((IsSchemeSecure() && !devices.empty()) || request_.request_type == content::MEDIA_OPEN_DEVICE) { SetPermission(true); } } } scoped_ptr<content::MediaStreamUI> ui; if (!devices.empty()) { ui = MediaCaptureDevicesDispatcher::GetInstance()-> GetMediaStreamCaptureIndicator()->RegisterMediaStream( web_contents_, devices); } content::MediaResponseCallback cb = callback_; callback_.Reset(); cb.Run(devices, ui.Pass()); }
171,312
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void OMX::binderDied(const wp<IBinder> &the_late_who) { OMXNodeInstance *instance; { Mutex::Autolock autoLock(mLock); ssize_t index = mLiveNodes.indexOfKey(the_late_who); CHECK(index >= 0); instance = mLiveNodes.editValueAt(index); mLiveNodes.removeItemsAt(index); index = mDispatchers.indexOfKey(instance->nodeID()); CHECK(index >= 0); mDispatchers.removeItemsAt(index); invalidateNodeID_l(instance->nodeID()); } instance->onObserverDied(mMaster); } Commit Message: Add VPX output buffer size check and handle dead observers more gracefully Bug: 27597103 Change-Id: Id7acb25d5ef69b197da15ec200a9e4f9e7b03518 CWE ID: CWE-264
void OMX::binderDied(const wp<IBinder> &the_late_who) { OMXNodeInstance *instance; { Mutex::Autolock autoLock(mLock); ssize_t index = mLiveNodes.indexOfKey(the_late_who); if (index < 0) { ALOGE("b/27597103, nonexistent observer on binderDied"); android_errorWriteLog(0x534e4554, "27597103"); return; } instance = mLiveNodes.editValueAt(index); mLiveNodes.removeItemsAt(index); index = mDispatchers.indexOfKey(instance->nodeID()); CHECK(index >= 0); mDispatchers.removeItemsAt(index); invalidateNodeID_l(instance->nodeID()); } instance->onObserverDied(mMaster); }
173,881
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string ExtensionTtsController::GetMatchingExtensionId( Utterance* utterance) { ExtensionService* service = utterance->profile()->GetExtensionService(); DCHECK(service); ExtensionEventRouter* event_router = utterance->profile()->GetExtensionEventRouter(); DCHECK(event_router); const ExtensionList* extensions = service->extensions(); ExtensionList::const_iterator iter; for (iter = extensions->begin(); iter != extensions->end(); ++iter) { const Extension* extension = *iter; if (!event_router->ExtensionHasEventListener( extension->id(), events::kOnSpeak) || !event_router->ExtensionHasEventListener( extension->id(), events::kOnStop)) { continue; } const std::vector<Extension::TtsVoice>& tts_voices = extension->tts_voices(); for (size_t i = 0; i < tts_voices.size(); ++i) { const Extension::TtsVoice& voice = tts_voices[i]; if (!voice.voice_name.empty() && !utterance->voice_name().empty() && voice.voice_name != utterance->voice_name()) { continue; } if (!voice.locale.empty() && !utterance->locale().empty() && voice.locale != utterance->locale()) { continue; } if (!voice.gender.empty() && !utterance->gender().empty() && voice.gender != utterance->gender()) { continue; } return extension->id(); } } return std::string(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
std::string ExtensionTtsController::GetMatchingExtensionId( double rate = 1.0; if (options->HasKey(constants::kRateKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetDouble(constants::kRateKey, &rate)); if (rate < 0.1 || rate > 10.0) { error_ = constants::kErrorInvalidRate; return false; }
170,380
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int proxy_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC) { zval **login, **password; if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_login", sizeof("_proxy_login"), (void **)&login) == SUCCESS) { unsigned char* buf; int len; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login)); smart_str_appendc(&auth, ':'); if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_password", sizeof("_proxy_password"), (void **)&password) == SUCCESS) { smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password)); } smart_str_0(&auth); smart_str_appendl(soap_headers, (char*)buf, len); smart_str_append_const(soap_headers, "\r\n"); efree(buf); smart_str_free(&auth); return 1; } return 0; } Commit Message: CWE ID:
int proxy_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC) { zval **login, **password; if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_login", sizeof("_proxy_login"), (void **)&login) == SUCCESS && Z_TYPE_PP(login) == IS_STRING) { unsigned char* buf; int len; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login)); smart_str_appendc(&auth, ':'); if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_password", sizeof("_proxy_password"), (void **)&password) == SUCCESS && Z_TYPE_PP(password) == IS_STRING) { smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password)); } smart_str_0(&auth); smart_str_appendl(soap_headers, (char*)buf, len); smart_str_append_const(soap_headers, "\r\n"); efree(buf); smart_str_free(&auth); return 1; } return 0; }
165,306
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error) { if (x + 1 > 10) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "%s", "x is bigger than 9"); return FALSE; } return x + 1; } Commit Message: CWE ID: CWE-264
my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error)
165,107
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: virtual void ResetModel() { last_pts_ = 0; bits_in_buffer_model_ = cfg_.rc_target_bitrate * cfg_.rc_buf_initial_sz; frame_number_ = 0; first_drop_ = 0; bits_total_ = 0; duration_ = 0.0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void ResetModel() { last_pts_ = 0; bits_in_buffer_model_ = cfg_.rc_target_bitrate * cfg_.rc_buf_initial_sz; frame_number_ = 0; first_drop_ = 0; bits_total_ = 0; duration_ = 0.0; denoiser_offon_test_ = 0; denoiser_offon_period_ = -1; }
174,517