instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebContentsAndroid::OpenURL(JNIEnv* env, jobject obj, jstring url, jboolean user_gesture, jboolean is_renderer_initiated) { GURL gurl(base::android::ConvertJavaStringToUTF8(env, url)); OpenURLParams open_params(gurl, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_LINK, is_renderer_initiated); open_params.user_gesture = user_gesture; web_contents_->OpenURL(open_params); } Commit Message: Revert "Load web contents after tab is created." This reverts commit 4c55f398def3214369aefa9f2f2e8f5940d3799d. BUG=432562 TBR=tedchoc@chromium.org,jbudorick@chromium.org,sky@chromium.org Review URL: https://codereview.chromium.org/894003005 Cr-Commit-Position: refs/heads/master@{#314469} CWE ID: CWE-399
void WebContentsAndroid::OpenURL(JNIEnv* env,
171,138
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DrawingBuffer::RestoreAllState() { client_->DrawingBufferClientRestoreScissorTest(); client_->DrawingBufferClientRestoreMaskAndClearValues(); client_->DrawingBufferClientRestorePixelPackAlignment(); client_->DrawingBufferClientRestoreTexture2DBinding(); client_->DrawingBufferClientRestoreRenderbufferBinding(); client_->DrawingBufferClientRestoreFramebufferBinding(); client_->DrawingBufferClientRestorePixelUnpackBufferBinding(); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test R=kbr@chromium.org,piman@chromium.org Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <piman@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
void DrawingBuffer::RestoreAllState() { client_->DrawingBufferClientRestoreScissorTest(); client_->DrawingBufferClientRestoreMaskAndClearValues(); client_->DrawingBufferClientRestorePixelPackParameters(); client_->DrawingBufferClientRestoreTexture2DBinding(); client_->DrawingBufferClientRestoreRenderbufferBinding(); client_->DrawingBufferClientRestoreFramebufferBinding(); client_->DrawingBufferClientRestorePixelUnpackBufferBinding(); client_->DrawingBufferClientRestorePixelPackBufferBinding(); }
172,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void get_socket_name(SingleInstData* data, char* buf, int len) { const char* dpy = g_getenv("DISPLAY"); char* host = NULL; int dpynum; if(dpy) { const char* p = strrchr(dpy, ':'); host = g_strndup(dpy, (p - dpy)); dpynum = atoi(p + 1); } else dpynum = 0; g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s", g_get_tmp_dir(), data->prog_name, host ? host : "", dpynum, g_get_user_name()); } Commit Message: CWE ID: CWE-20
static void get_socket_name(SingleInstData* data, char* buf, int len) { const char* dpy = g_getenv("DISPLAY"); char* host = NULL; int dpynum; if(dpy) { const char* p = strrchr(dpy, ':'); host = g_strndup(dpy, (p - dpy)); dpynum = atoi(p + 1); } else dpynum = 0; #if GLIB_CHECK_VERSION(2, 28, 0) g_snprintf(buf, len, "%s/%s-socket-%s-%d", g_get_user_runtime_dir(), data->prog_name, host ? host : "", dpynum); #else g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s", g_get_tmp_dir(), data->prog_name, host ? host : "", dpynum, g_get_user_name()); #endif }
164,816
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DataReductionProxyIOData::DataReductionProxyIOData( Client client, PrefService* prefs, network::NetworkConnectionTracker* network_connection_tracker, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, bool enabled, const std::string& user_agent, const std::string& channel) : client_(client), network_connection_tracker_(network_connection_tracker), io_task_runner_(io_task_runner), ui_task_runner_(ui_task_runner), enabled_(enabled), channel_(channel), effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { DCHECK(io_task_runner_); DCHECK(ui_task_runner_); configurator_.reset(new DataReductionProxyConfigurator()); configurator_->SetConfigUpdatedCallback(base::BindRepeating( &DataReductionProxyIOData::OnProxyConfigUpdated, base::Unretained(this))); DataReductionProxyMutableConfigValues* raw_mutable_config = nullptr; std::unique_ptr<DataReductionProxyMutableConfigValues> mutable_config = std::make_unique<DataReductionProxyMutableConfigValues>(); raw_mutable_config = mutable_config.get(); config_.reset(new DataReductionProxyConfig( io_task_runner, ui_task_runner, network_connection_tracker_, std::move(mutable_config), configurator_.get())); request_options_.reset( new DataReductionProxyRequestOptions(client_, config_.get())); request_options_->Init(); request_options_->SetUpdateHeaderCallback(base::BindRepeating( &DataReductionProxyIOData::UpdateProxyRequestHeaders, base::Unretained(this))); config_client_.reset(new DataReductionProxyConfigServiceClient( GetBackoffPolicy(), request_options_.get(), raw_mutable_config, config_.get(), this, network_connection_tracker_, base::BindRepeating(&DataReductionProxyIOData::StoreSerializedConfig, base::Unretained(this)))); network_properties_manager_.reset(new NetworkPropertiesManager( base::DefaultClock::GetInstance(), prefs, ui_task_runner_)); } 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
DataReductionProxyIOData::DataReductionProxyIOData( Client client, PrefService* prefs, network::NetworkConnectionTracker* network_connection_tracker, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, bool enabled, const std::string& user_agent, const std::string& channel) : client_(client), network_connection_tracker_(network_connection_tracker), io_task_runner_(io_task_runner), ui_task_runner_(ui_task_runner), enabled_(enabled), channel_(channel), effective_connection_type_(net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { DCHECK(io_task_runner_); DCHECK(ui_task_runner_); configurator_.reset(new DataReductionProxyConfigurator()); configurator_->SetConfigUpdatedCallback(base::BindRepeating( &DataReductionProxyIOData::OnProxyConfigUpdated, base::Unretained(this))); DataReductionProxyMutableConfigValues* raw_mutable_config = nullptr; std::unique_ptr<DataReductionProxyMutableConfigValues> mutable_config = std::make_unique<DataReductionProxyMutableConfigValues>(); raw_mutable_config = mutable_config.get(); config_.reset(new DataReductionProxyConfig( io_task_runner, ui_task_runner, network_connection_tracker_, std::move(mutable_config), configurator_.get())); request_options_.reset( new DataReductionProxyRequestOptions(client_, config_.get())); request_options_->Init(); request_options_->SetUpdateHeaderCallback(base::BindRepeating( &DataReductionProxyIOData::UpdateProxyRequestHeaders, base::Unretained(this))); if (!params::IsIncludedInHoldbackFieldTrial()) { config_client_.reset(new DataReductionProxyConfigServiceClient( GetBackoffPolicy(), request_options_.get(), raw_mutable_config, config_.get(), this, network_connection_tracker_, base::BindRepeating(&DataReductionProxyIOData::StoreSerializedConfig, base::Unretained(this)))); } network_properties_manager_.reset(new NetworkPropertiesManager( base::DefaultClock::GetInstance(), prefs, ui_task_runner_)); }
172,421
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int itacns_add_data_files(sc_pkcs15_card_t *p15card) { const size_t array_size = sizeof(itacns_data_files)/sizeof(itacns_data_files[0]); unsigned int i; int rv; sc_pkcs15_data_t *p15_personaldata = NULL; sc_pkcs15_data_info_t dinfo; struct sc_pkcs15_object *objs[32]; struct sc_pkcs15_data_info *cinfo; for(i=0; i < array_size; i++) { sc_path_t path; sc_pkcs15_data_info_t data; sc_pkcs15_object_t obj; if (itacns_data_files[i].cie_only && p15card->card->type != SC_CARD_TYPE_ITACNS_CIE_V2) continue; sc_format_path(itacns_data_files[i].path, &path); memset(&data, 0, sizeof(data)); memset(&obj, 0, sizeof(obj)); strlcpy(data.app_label, itacns_data_files[i].label, sizeof(data.app_label)); strlcpy(obj.label, itacns_data_files[i].label, sizeof(obj.label)); data.path = path; rv = sc_pkcs15emu_add_data_object(p15card, &obj, &data); SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, rv, "Could not add data file"); } /* * If we got this far, we can read the Personal Data file and glean * the user's full name. Thus we can use it to put together a * user-friendlier card name. */ memset(&dinfo, 0, sizeof(dinfo)); strcpy(dinfo.app_label, "EF_DatiPersonali"); /* Find EF_DatiPersonali */ rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT, objs, 32); if(rv < 0) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Data enumeration failed"); return SC_SUCCESS; } for(i=0; i<32; i++) { cinfo = (struct sc_pkcs15_data_info *) objs[i]->data; if(!strcmp("EF_DatiPersonali", objs[i]->label)) break; } if(i>=32) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not find EF_DatiPersonali: " "keeping generic card name"); return SC_SUCCESS; } rv = sc_pkcs15_read_data_object(p15card, cinfo, &p15_personaldata); if (rv) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not read EF_DatiPersonali: " "keeping generic card name"); } { char fullname[160]; if(get_name_from_EF_DatiPersonali(p15_personaldata->data, fullname, sizeof(fullname))) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not parse EF_DatiPersonali: " "keeping generic card name"); sc_pkcs15_free_data_object(p15_personaldata); return SC_SUCCESS; } set_string(&p15card->tokeninfo->label, fullname); } sc_pkcs15_free_data_object(p15_personaldata); return SC_SUCCESS; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
static int itacns_add_data_files(sc_pkcs15_card_t *p15card) { const size_t array_size = sizeof(itacns_data_files)/sizeof(itacns_data_files[0]); unsigned int i; int rv; sc_pkcs15_data_t *p15_personaldata = NULL; sc_pkcs15_data_info_t dinfo; struct sc_pkcs15_object *objs[32]; struct sc_pkcs15_data_info *cinfo; for(i=0; i < array_size; i++) { sc_path_t path; sc_pkcs15_data_info_t data; sc_pkcs15_object_t obj; if (itacns_data_files[i].cie_only && p15card->card->type != SC_CARD_TYPE_ITACNS_CIE_V2) continue; sc_format_path(itacns_data_files[i].path, &path); memset(&data, 0, sizeof(data)); memset(&obj, 0, sizeof(obj)); strlcpy(data.app_label, itacns_data_files[i].label, sizeof(data.app_label)); strlcpy(obj.label, itacns_data_files[i].label, sizeof(obj.label)); data.path = path; rv = sc_pkcs15emu_add_data_object(p15card, &obj, &data); SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, rv, "Could not add data file"); } /* * If we got this far, we can read the Personal Data file and glean * the user's full name. Thus we can use it to put together a * user-friendlier card name. */ memset(&dinfo, 0, sizeof(dinfo)); strcpy(dinfo.app_label, "EF_DatiPersonali"); /* Find EF_DatiPersonali */ rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT, objs, 32); if(rv < 0) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Data enumeration failed"); return SC_SUCCESS; } for(i=0; i<32; i++) { cinfo = (struct sc_pkcs15_data_info *) objs[i]->data; if(!strcmp("EF_DatiPersonali", objs[i]->label)) break; } if(i>=32) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not find EF_DatiPersonali: " "keeping generic card name"); return SC_SUCCESS; } rv = sc_pkcs15_read_data_object(p15card, cinfo, &p15_personaldata); if (rv) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not read EF_DatiPersonali: " "keeping generic card name"); return SC_SUCCESS; } { char fullname[160]; if(get_name_from_EF_DatiPersonali(p15_personaldata->data, fullname, sizeof(fullname))) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not parse EF_DatiPersonali: " "keeping generic card name"); sc_pkcs15_free_data_object(p15_personaldata); return SC_SUCCESS; } set_string(&p15card->tokeninfo->label, fullname); } sc_pkcs15_free_data_object(p15_personaldata); return SC_SUCCESS; }
169,066
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool BaseSettingChange::Init(Profile* profile) { DCHECK(profile); profile_ = profile; return true; } Commit Message: [protector] Refactoring of --no-protector code. *) On DSE change, new provider is not pushed to Sync. *) Simplified code in BrowserInit. BUG=None TEST=protector.py Review URL: http://codereview.chromium.org/10065016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132398 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool BaseSettingChange::Init(Profile* profile) { DCHECK(profile && !profile_); profile_ = profile; return true; }
170,756
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BOOL rdp_decrypt(rdpRdp* rdp, STREAM* s, int length, UINT16 securityFlags) { BYTE cmac[8]; BYTE wmac[8]; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { UINT16 len; BYTE version, pad; BYTE* sig; if (stream_get_left(s) < 12) return FALSE; stream_read_UINT16(s, len); /* 0x10 */ stream_read_BYTE(s, version); /* 0x1 */ stream_read_BYTE(s, pad); sig = s->p; stream_seek(s, 8); /* signature */ length -= 12; if (!security_fips_decrypt(s->p, length, rdp)) { printf("FATAL: cannot decrypt\n"); return FALSE; /* TODO */ } if (!security_fips_check_signature(s->p, length - pad, sig, rdp)) { printf("FATAL: invalid packet signature\n"); return FALSE; /* TODO */ } /* is this what needs adjusting? */ s->size -= pad; return TRUE; } if (stream_get_left(s) < 8) return FALSE; stream_read(s, wmac, sizeof(wmac)); length -= sizeof(wmac); security_decrypt(s->p, length, rdp); if (securityFlags & SEC_SECURE_CHECKSUM) security_salted_mac_signature(rdp, s->p, length, FALSE, cmac); else security_mac_signature(rdp, s->p, length, cmac); if (memcmp(wmac, cmac, sizeof(wmac)) != 0) { printf("WARNING: invalid packet signature\n"); /* * Because Standard RDP Security is totally broken, * and cannot protect against MITM, don't treat signature * verification failure as critical. This at least enables * us to work with broken RDP clients and servers that * generate invalid signatures. */ } return TRUE; } Commit Message: security: add a NULL pointer check to fix a server crash. CWE ID: CWE-476
BOOL rdp_decrypt(rdpRdp* rdp, STREAM* s, int length, UINT16 securityFlags) { BYTE cmac[8]; BYTE wmac[8]; if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS) { UINT16 len; BYTE version, pad; BYTE* sig; if (stream_get_left(s) < 12) return FALSE; stream_read_UINT16(s, len); /* 0x10 */ stream_read_BYTE(s, version); /* 0x1 */ stream_read_BYTE(s, pad); sig = s->p; stream_seek(s, 8); /* signature */ length -= 12; if (!security_fips_decrypt(s->p, length, rdp)) { printf("FATAL: cannot decrypt\n"); return FALSE; /* TODO */ } if (!security_fips_check_signature(s->p, length - pad, sig, rdp)) { printf("FATAL: invalid packet signature\n"); return FALSE; /* TODO */ } /* is this what needs adjusting? */ s->size -= pad; return TRUE; } if (stream_get_left(s) < 8) return FALSE; stream_read(s, wmac, sizeof(wmac)); length -= sizeof(wmac); if (!security_decrypt(s->p, length, rdp)) return FALSE; if (securityFlags & SEC_SECURE_CHECKSUM) security_salted_mac_signature(rdp, s->p, length, FALSE, cmac); else security_mac_signature(rdp, s->p, length, cmac); if (memcmp(wmac, cmac, sizeof(wmac)) != 0) { printf("WARNING: invalid packet signature\n"); /* * Because Standard RDP Security is totally broken, * and cannot protect against MITM, don't treat signature * verification failure as critical. This at least enables * us to work with broken RDP clients and servers that * generate invalid signatures. */ } return TRUE; }
167,606
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintWebViewHelper::OnPrintForPrintPreview( const DictionaryValue& job_settings) { DCHECK(is_preview_); if (print_web_view_) return; if (!render_view()->webview()) return; WebFrame* main_frame = render_view()->webview()->mainFrame(); if (!main_frame) return; WebDocument document = main_frame->document(); WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } WebFrame* pdf_frame = pdf_element.document().frame(); scoped_ptr<PrepareFrameAndViewForPrint> prepare; if (!InitPrintSettingsAndPrepareFrame(pdf_frame, &pdf_element, &prepare)) { LOG(ERROR) << "Failed to initialize print page settings"; return; } if (!UpdatePrintSettings(job_settings, false)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } if (!RenderPagesForPrint(pdf_frame, &pdf_element, prepare.get())) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PrintWebViewHelper::OnPrintForPrintPreview( const DictionaryValue& job_settings) { DCHECK(is_preview_); if (print_web_view_) return; if (!render_view()->webview()) return; WebFrame* main_frame = render_view()->webview()->mainFrame(); if (!main_frame) return; WebDocument document = main_frame->document(); WebElement pdf_element = document.getElementById("pdf-viewer"); if (pdf_element.isNull()) { NOTREACHED(); return; } if (!UpdatePrintSettings(job_settings, false)) { LOG(ERROR) << "UpdatePrintSettings failed"; DidFinishPrinting(FAIL_PRINT); return; } WebFrame* pdf_frame = pdf_element.document().frame(); scoped_ptr<PrepareFrameAndViewForPrint> prepare; prepare.reset(new PrepareFrameAndViewForPrint(print_pages_params_->params, pdf_frame, &pdf_element)); UpdatePrintableSizeInPrintParameters(pdf_frame, &pdf_element, prepare.get(), &print_pages_params_->params); if (!RenderPagesForPrint(pdf_frame, &pdf_element, prepare.get())) { LOG(ERROR) << "RenderPagesForPrint failed"; DidFinishPrinting(FAIL_PRINT); } }
170,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GKI_delay(UINT32 timeout_ms) { struct timespec delay; delay.tv_sec = timeout_ms / 1000; delay.tv_nsec = 1000 * 1000 * (timeout_ms % 1000); int err; do { err = nanosleep(&delay, &delay); } while (err == -1 && errno == EINTR); } 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
void GKI_delay(UINT32 timeout_ms) { struct timespec delay; delay.tv_sec = timeout_ms / 1000; delay.tv_nsec = 1000 * 1000 * (timeout_ms % 1000); int err; do { err = TEMP_FAILURE_RETRY(nanosleep(&delay, &delay)); } while (err == -1 && errno == EINTR); }
173,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Local<v8::Value> V8ValueConverterImpl::ToV8Array( v8::Isolate* isolate, v8::Local<v8::Object> creation_context, const base::ListValue* val) const { v8::Local<v8::Array> result(v8::Array::New(isolate, val->GetSize())); for (size_t i = 0; i < val->GetSize(); ++i) { const base::Value* child = NULL; CHECK(val->Get(i, &child)); v8::Local<v8::Value> child_v8 = ToV8ValueImpl(isolate, creation_context, child); CHECK(!child_v8.IsEmpty()); v8::TryCatch try_catch(isolate); result->Set(static_cast<uint32_t>(i), child_v8); if (try_catch.HasCaught()) LOG(ERROR) << "Setter for index " << i << " threw an exception."; } return result; } Commit Message: V8ValueConverter::ToV8Value should not trigger setters BUG=606390 Review URL: https://codereview.chromium.org/1918793003 Cr-Commit-Position: refs/heads/master@{#390045} CWE ID:
v8::Local<v8::Value> V8ValueConverterImpl::ToV8Array( v8::Isolate* isolate, v8::Local<v8::Object> creation_context, const base::ListValue* val) const { v8::Local<v8::Array> result(v8::Array::New(isolate, val->GetSize())); // TODO(robwu): Callers should pass in the context. v8::Local<v8::Context> context = isolate->GetCurrentContext(); for (size_t i = 0; i < val->GetSize(); ++i) { const base::Value* child = NULL; CHECK(val->Get(i, &child)); v8::Local<v8::Value> child_v8 = ToV8ValueImpl(isolate, creation_context, child); CHECK(!child_v8.IsEmpty()); v8::Maybe<bool> maybe = result->CreateDataProperty(context, static_cast<uint32_t>(i), child_v8); if (!maybe.IsJust() || !maybe.FromJust()) LOG(ERROR) << "Failed to set value at index " << i; } return result; }
173,283
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Local<v8::Value> ModuleSystem::RequireForJsInner( v8::Local<v8::String> module_name) { v8::EscapableHandleScope handle_scope(GetIsolate()); v8::Local<v8::Context> v8_context = context()->v8_context(); v8::Context::Scope context_scope(v8_context); v8::Local<v8::Object> global(context()->v8_context()->Global()); v8::Local<v8::Value> modules_value; if (!GetPrivate(global, kModulesField, &modules_value) || modules_value->IsUndefined()) { Warn(GetIsolate(), "Extension view no longer exists"); return v8::Undefined(GetIsolate()); } v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value)); v8::Local<v8::Value> exports; if (!GetProperty(v8_context, modules, module_name, &exports) || !exports->IsUndefined()) return handle_scope.Escape(exports); exports = LoadModule(*v8::String::Utf8Value(module_name)); SetProperty(v8_context, modules, module_name, exports); return handle_scope.Escape(exports); } Commit Message: [Extensions] Harden against bindings interception There's more we can do but this is a start. BUG=590275 BUG=590118 Review URL: https://codereview.chromium.org/1748943002 Cr-Commit-Position: refs/heads/master@{#378621} CWE ID: CWE-284
v8::Local<v8::Value> ModuleSystem::RequireForJsInner( v8::Local<v8::String> module_name) { v8::EscapableHandleScope handle_scope(GetIsolate()); v8::Local<v8::Context> v8_context = context()->v8_context(); v8::Context::Scope context_scope(v8_context); v8::Local<v8::Object> global(context()->v8_context()->Global()); v8::Local<v8::Value> modules_value; if (!GetPrivate(global, kModulesField, &modules_value) || modules_value->IsUndefined()) { Warn(GetIsolate(), "Extension view no longer exists"); return v8::Undefined(GetIsolate()); } v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value)); v8::Local<v8::Value> exports; if (!GetPrivateProperty(v8_context, modules, module_name, &exports) || !exports->IsUndefined()) return handle_scope.Escape(exports); exports = LoadModule(*v8::String::Utf8Value(module_name)); SetPrivateProperty(v8_context, modules, module_name, exports); return handle_scope.Escape(exports); }
173,268
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GCInfoTable::Init() { CHECK(!g_gc_info_table); Resize(); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <mlippautz@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void GCInfoTable::Init() { GCInfoTable::GCInfoTable() { CHECK(!table_); table_ = reinterpret_cast<GCInfo const**>(base::AllocPages( nullptr, MaxTableSize(), base::kPageAllocationGranularity, base::PageInaccessible)); CHECK(table_); Resize(); }
173,135
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct posix_acl *jffs2_get_acl(struct inode *inode, int type) { struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode); struct posix_acl *acl; char *value = NULL; int rc, xprefix; switch (type) { case ACL_TYPE_ACCESS: acl = jffs2_iget_acl(inode, &f->i_acl_access); if (acl != JFFS2_ACL_NOT_CACHED) return acl; xprefix = JFFS2_XPREFIX_ACL_ACCESS; break; case ACL_TYPE_DEFAULT: acl = jffs2_iget_acl(inode, &f->i_acl_default); if (acl != JFFS2_ACL_NOT_CACHED) return acl; xprefix = JFFS2_XPREFIX_ACL_DEFAULT; break; default: return ERR_PTR(-EINVAL); } rc = do_jffs2_getxattr(inode, xprefix, "", NULL, 0); if (rc > 0) { value = kmalloc(rc, GFP_KERNEL); if (!value) return ERR_PTR(-ENOMEM); rc = do_jffs2_getxattr(inode, xprefix, "", value, rc); } if (rc > 0) { acl = jffs2_acl_from_medium(value, rc); } else if (rc == -ENODATA || rc == -ENOSYS) { acl = NULL; } else { acl = ERR_PTR(rc); } if (value) kfree(value); if (!IS_ERR(acl)) { switch (type) { case ACL_TYPE_ACCESS: jffs2_iset_acl(inode, &f->i_acl_access, acl); break; case ACL_TYPE_DEFAULT: jffs2_iset_acl(inode, &f->i_acl_default, acl); break; } } return acl; } Commit Message: CWE ID: CWE-264
static struct posix_acl *jffs2_get_acl(struct inode *inode, int type) struct posix_acl *jffs2_get_acl(struct inode *inode, int type) { struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode); struct posix_acl *acl; char *value = NULL; int rc, xprefix; switch (type) { case ACL_TYPE_ACCESS: acl = jffs2_iget_acl(inode, &f->i_acl_access); if (acl != JFFS2_ACL_NOT_CACHED) return acl; xprefix = JFFS2_XPREFIX_ACL_ACCESS; break; case ACL_TYPE_DEFAULT: acl = jffs2_iget_acl(inode, &f->i_acl_default); if (acl != JFFS2_ACL_NOT_CACHED) return acl; xprefix = JFFS2_XPREFIX_ACL_DEFAULT; break; default: return ERR_PTR(-EINVAL); } rc = do_jffs2_getxattr(inode, xprefix, "", NULL, 0); if (rc > 0) { value = kmalloc(rc, GFP_KERNEL); if (!value) return ERR_PTR(-ENOMEM); rc = do_jffs2_getxattr(inode, xprefix, "", value, rc); } if (rc > 0) { acl = jffs2_acl_from_medium(value, rc); } else if (rc == -ENODATA || rc == -ENOSYS) { acl = NULL; } else { acl = ERR_PTR(rc); } if (value) kfree(value); if (!IS_ERR(acl)) { switch (type) { case ACL_TYPE_ACCESS: jffs2_iset_acl(inode, &f->i_acl_access, acl); break; case ACL_TYPE_DEFAULT: jffs2_iset_acl(inode, &f->i_acl_default, acl); break; } } return acl; }
164,655
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DownloadRequestLimiter::TabDownloadState::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame()) return; if (status_ == ALLOW_ONE_DOWNLOAD || (status_ == PROMPT_BEFORE_DOWNLOAD && !navigation_handle->IsRendererInitiated())) { NotifyCallbacks(false); host_->Remove(this, web_contents()); } } Commit Message: Don't reset TabDownloadState on history back/forward Currently performing forward/backward on a tab will reset the TabDownloadState. Which allows javascript code to do trigger multiple downloads. This CL disables that behavior by not resetting the TabDownloadState on forward/back. It is still possible to reset the TabDownloadState through user gesture or using browser initiated download. BUG=848535 Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863 Reviewed-on: https://chromium-review.googlesource.com/1108959 Commit-Queue: Min Qin <qinmin@chromium.org> Reviewed-by: Xing Liu <xingliu@chromium.org> Cr-Commit-Position: refs/heads/master@{#574437} CWE ID:
void DownloadRequestLimiter::TabDownloadState::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame()) return; if (status_ == ALLOW_ONE_DOWNLOAD || (status_ == PROMPT_BEFORE_DOWNLOAD && !navigation_handle->IsRendererInitiated() && !IsNavigationRestricted(navigation_handle))) { NotifyCallbacks(false); host_->Remove(this, web_contents()); } }
173,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TestFlashMessageLoop::DestroyMessageLoopResourceTask(int32_t unused) { if (message_loop_) { delete message_loop_; message_loop_ = NULL; } else { PP_NOTREACHED(); } } Commit Message: Fix PPB_Flash_MessageLoop. This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop. BUG=569496 Review URL: https://codereview.chromium.org/1559113002 Cr-Commit-Position: refs/heads/master@{#374529} CWE ID: CWE-264
void TestFlashMessageLoop::DestroyMessageLoopResourceTask(int32_t unused) { if (message_loop_) { delete message_loop_; message_loop_ = nullptr; } else { PP_NOTREACHED(); } }
172,124
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CmdBufferImageTransportFactory::DestroySharedSurfaceHandle( const gfx::GLSurfaceHandle& handle) { if (!context_->makeContextCurrent()) { NOTREACHED() << "Failed to make shared graphics context current"; return; } context_->deleteTexture(handle.parent_texture_id[0]); context_->deleteTexture(handle.parent_texture_id[1]); context_->finish(); } 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 CmdBufferImageTransportFactory::DestroySharedSurfaceHandle( const gfx::GLSurfaceHandle& handle) { if (!context_->makeContextCurrent()) { NOTREACHED() << "Failed to make shared graphics context current"; return; } }
171,364
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) { struct ngiflib_gif * p = i->parent; if(v!=i->gce.transparent_color || !i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ *context->frbuff_p.p8 = v; #ifndef NGIFLIB_INDEXED_ONLY } else *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, v); #endif /* NGIFLIB_INDEXED_ONLY */ } if(--(context->Xtogo) <= 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 4; } break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 2; } break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; if(context->curY >= p->height) { context->pass++; context->curY = i->posY + 1; } break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ context->frbuff_p.p8++; #ifndef NGIFLIB_INDEXED_ONLY } else { context->frbuff_p.p32++; } #endif /* NGIFLIB_INDEXED_ONLY */ } } Commit Message: fix deinterlacing for small pictures fixes #12 CWE ID: CWE-119
static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) { struct ngiflib_gif * p = i->parent; if(v!=i->gce.transparent_color || !i->gce.transparent_flag) { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ *context->frbuff_p.p8 = v; #ifndef NGIFLIB_INDEXED_ONLY } else *context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, v); #endif /* NGIFLIB_INDEXED_ONLY */ } if(--(context->Xtogo) <= 0) { #ifdef NGIFLIB_ENABLE_CALLBACKS if(p->line_cb) p->line_cb(p, context->line_p, context->curY); #endif /* NGIFLIB_ENABLE_CALLBACKS */ context->Xtogo = i->width; switch(context->pass) { case 0: context->curY++; break; case 1: /* 1st pass : every eighth row starting from 0 */ context->curY += 8; break; case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY += 8; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY += 4; break; case 4: /* 4th pass : every odd row */ context->curY += 2; break; } while(context->pass > 0 && context->pass < 4 && context->curY >= p->height) { switch(++context->pass) { case 2: /* 2nd pass : every eighth row starting from 4 */ context->curY = i->posY + 4; break; case 3: /* 3rd pass : every fourth row starting from 2 */ context->curY = i->posY + 2; break; case 4: /* 4th pass : every odd row */ context->curY = i->posY + 1; break; } } #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width; context->frbuff_p.p8 = context->line_p.p8 + i->posX; #else context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #ifndef NGIFLIB_INDEXED_ONLY } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width; context->frbuff_p.p32 = context->line_p.p32 + i->posX; #else context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ } else { #ifndef NGIFLIB_INDEXED_ONLY if(p->mode & NGIFLIB_MODE_INDEXED) { #endif /* NGIFLIB_INDEXED_ONLY */ context->frbuff_p.p8++; #ifndef NGIFLIB_INDEXED_ONLY } else { context->frbuff_p.p32++; } #endif /* NGIFLIB_INDEXED_ONLY */ } }
169,511
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_entry_size_and_hooks(struct ip6t_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-264
check_entry_size_and_hooks(struct ip6t_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; err = xt_check_entry_offsets(e, e->elems, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }
167,220
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void SetUpTestCase() { input_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1; output_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kOutputBufferSize)); } 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
static void SetUpTestCase() { input_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1; output_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kOutputBufferSize)); output_ref_ = reinterpret_cast<uint8_t*>( vpx_memalign(kDataAlignment, kOutputBufferSize)); #if CONFIG_VP9_HIGHBITDEPTH input16_ = reinterpret_cast<uint16_t*>( vpx_memalign(kDataAlignment, (kInputBufferSize + 1) * sizeof(uint16_t))) + 1; output16_ = reinterpret_cast<uint16_t*>( vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t))); output16_ref_ = reinterpret_cast<uint16_t*>( vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t))); #endif }
174,506
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SyncManager::SyncInternal::MaybeSetSyncTabsInNigoriNode( const ModelTypeSet enabled_types) { if (initialized_ && enabled_types.Has(syncable::SESSIONS)) { WriteTransaction trans(FROM_HERE, GetUserShare()); WriteNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { LOG(WARNING) << "Unable to set 'sync_tabs' bit because Nigori node not " << "found."; return; } sync_pb::NigoriSpecifics specifics(node.GetNigoriSpecifics()); specifics.set_sync_tabs(true); node.SetNigoriSpecifics(specifics); } } 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 SyncManager::SyncInternal::MaybeSetSyncTabsInNigoriNode( }
170,795
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Block::IsKey() const { return ((m_flags & static_cast<unsigned char>(1 << 7)) != 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
bool Block::IsKey() const void Block::SetKey(bool bKey) { if (bKey) m_flags |= static_cast<unsigned char>(1 << 7); else m_flags &= 0x7F; }
174,392
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void local_socket_close_locked(asocket* s) { D("entered local_socket_close_locked. LS(%d) fd=%d", s->id, s->fd); if (s->peer) { D("LS(%d): closing peer. peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd); /* Note: it's important to call shutdown before disconnecting from * the peer, this ensures that remote sockets can still get the id * of the local socket they're connected to, to send a CLOSE() * protocol event. */ if (s->peer->shutdown) { s->peer->shutdown(s->peer); } s->peer->peer = 0; if (s->peer->close == local_socket_close) { local_socket_close_locked(s->peer); } else { s->peer->close(s->peer); } s->peer = 0; } /* If we are already closing, or if there are no ** pending packets, destroy immediately */ if (s->closing || s->has_write_error || s->pkt_first == NULL) { int id = s->id; local_socket_destroy(s); D("LS(%d): closed", id); return; } /* otherwise, put on the closing list */ D("LS(%d): closing", s->id); s->closing = 1; fdevent_del(&s->fde, FDE_READ); remove_socket(s); D("LS(%d): put on socket_closing_list fd=%d", s->id, s->fd); insert_local_socket(s, &local_socket_closing_list); CHECK_EQ(FDE_WRITE, s->fde.state & FDE_WRITE); } Commit Message: adb: switch the socket list mutex to a recursive_mutex. sockets.cpp was branching on whether a socket close function was local_socket_close in order to avoid a potential deadlock if the socket list lock was held while closing a peer socket. Bug: http://b/28347842 Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3 (cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa) CWE ID: CWE-264
static void local_socket_close_locked(asocket* s) { static void local_socket_close(asocket* s) { D("entered local_socket_close. LS(%d) fd=%d", s->id, s->fd); std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock); if (s->peer) { D("LS(%d): closing peer. peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd); /* Note: it's important to call shutdown before disconnecting from * the peer, this ensures that remote sockets can still get the id * of the local socket they're connected to, to send a CLOSE() * protocol event. */ if (s->peer->shutdown) { s->peer->shutdown(s->peer); } s->peer->peer = nullptr; s->peer->close(s->peer); s->peer = nullptr; } /* If we are already closing, or if there are no ** pending packets, destroy immediately */ if (s->closing || s->has_write_error || s->pkt_first == NULL) { int id = s->id; local_socket_destroy(s); D("LS(%d): closed", id); return; } /* otherwise, put on the closing list */ D("LS(%d): closing", s->id); s->closing = 1; fdevent_del(&s->fde, FDE_READ); remove_socket(s); D("LS(%d): put on socket_closing_list fd=%d", s->id, s->fd); insert_local_socket(s, &local_socket_closing_list); CHECK_EQ(FDE_WRITE, s->fde.state & FDE_WRITE); }
174,154
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChildThread::Shutdown() { file_system_dispatcher_.reset(); quota_dispatcher_.reset(); } Commit Message: [FileAPI] Clean up WebFileSystemImpl before Blink shutdown WebFileSystemImpl should not outlive V8 instance, since it may have references to V8. This CL ensures it deleted before Blink shutdown. BUG=369525 Review URL: https://codereview.chromium.org/270633009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@269345 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void ChildThread::Shutdown() { file_system_dispatcher_.reset(); quota_dispatcher_.reset(); WebFileSystemImpl::DeleteThreadSpecificInstance(); }
171,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BackendIO::ExecuteBackendOperation() { switch (operation_) { case OP_INIT: result_ = backend_->SyncInit(); break; case OP_OPEN: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncOpenEntry(key_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_CREATE: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncCreateEntry(key_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_DOOM: result_ = backend_->SyncDoomEntry(key_); break; case OP_DOOM_ALL: result_ = backend_->SyncDoomAllEntries(); break; case OP_DOOM_BETWEEN: result_ = backend_->SyncDoomEntriesBetween(initial_time_, end_time_); break; case OP_DOOM_SINCE: result_ = backend_->SyncDoomEntriesSince(initial_time_); break; case OP_SIZE_ALL: result_ = backend_->SyncCalculateSizeOfAllEntries(); break; case OP_OPEN_NEXT: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncOpenNextEntry(iterator_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_END_ENUMERATION: backend_->SyncEndEnumeration(std::move(scoped_iterator_)); result_ = net::OK; break; case OP_ON_EXTERNAL_CACHE_HIT: backend_->SyncOnExternalCacheHit(key_); result_ = net::OK; break; case OP_CLOSE_ENTRY: entry_->Release(); result_ = net::OK; break; case OP_DOOM_ENTRY: entry_->DoomImpl(); result_ = net::OK; break; case OP_FLUSH_QUEUE: result_ = net::OK; break; case OP_RUN_TASK: task_.Run(); result_ = net::OK; break; default: NOTREACHED() << "Invalid Operation"; result_ = net::ERR_UNEXPECTED; } DCHECK_NE(net::ERR_IO_PENDING, result_); NotifyController(); } Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem Thanks to nedwilliamson@ (on gmail) for an alternative perspective plus a reduction to make fixing this much easier. Bug: 826626, 518908, 537063, 802886 Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f Reviewed-on: https://chromium-review.googlesource.com/985052 Reviewed-by: Matt Menke <mmenke@chromium.org> Commit-Queue: Maks Orlovich <morlovich@chromium.org> Cr-Commit-Position: refs/heads/master@{#547103} CWE ID: CWE-20
void BackendIO::ExecuteBackendOperation() { switch (operation_) { case OP_INIT: result_ = backend_->SyncInit(); break; case OP_OPEN: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncOpenEntry(key_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_CREATE: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncCreateEntry(key_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_DOOM: result_ = backend_->SyncDoomEntry(key_); break; case OP_DOOM_ALL: result_ = backend_->SyncDoomAllEntries(); break; case OP_DOOM_BETWEEN: result_ = backend_->SyncDoomEntriesBetween(initial_time_, end_time_); break; case OP_DOOM_SINCE: result_ = backend_->SyncDoomEntriesSince(initial_time_); break; case OP_SIZE_ALL: result_ = backend_->SyncCalculateSizeOfAllEntries(); break; case OP_OPEN_NEXT: { scoped_refptr<EntryImpl> entry; result_ = backend_->SyncOpenNextEntry(iterator_, &entry); *entry_ptr_ = LeakEntryImpl(std::move(entry)); break; } case OP_END_ENUMERATION: backend_->SyncEndEnumeration(std::move(scoped_iterator_)); result_ = net::OK; break; case OP_ON_EXTERNAL_CACHE_HIT: backend_->SyncOnExternalCacheHit(key_); result_ = net::OK; break; case OP_CLOSE_ENTRY: entry_->Release(); result_ = net::OK; break; case OP_DOOM_ENTRY: entry_->DoomImpl(); result_ = net::OK; break; case OP_FLUSH_QUEUE: result_ = net::OK; break; case OP_RUN_TASK: task_.Run(); result_ = net::OK; break; default: NOTREACHED() << "Invalid Operation"; result_ = net::ERR_UNEXPECTED; } DCHECK_NE(net::ERR_IO_PENDING, result_); NotifyController(); backend_->OnSyncBackendOpComplete(); }
172,699
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IHEVCD_ERROR_T ihevcd_cabac_init(cab_ctxt_t *ps_cabac, bitstrm_t *ps_bitstrm, WORD32 qp, WORD32 cabac_init_idc, const UWORD8 *pu1_init_ctxt) { /* Sanity checks */ ASSERT(ps_cabac != NULL); ASSERT(ps_bitstrm != NULL); ASSERT((qp >= 0) && (qp < 52)); ASSERT((cabac_init_idc >= 0) && (cabac_init_idc < 3)); UNUSED(qp); UNUSED(cabac_init_idc); /* CABAC engine uses 32 bit range instead of 9 bits as specified by * the spec. This is done to reduce number of renormalizations */ /* cabac engine initialization */ #if FULLRANGE ps_cabac->u4_range = (UWORD32)510 << RANGE_SHIFT; BITS_GET(ps_cabac->u4_ofst, ps_bitstrm->pu4_buf, ps_bitstrm->u4_bit_ofst, ps_bitstrm->u4_cur_word, ps_bitstrm->u4_nxt_word, (9 + RANGE_SHIFT)); #else ps_cabac->u4_range = (UWORD32)510; BITS_GET(ps_cabac->u4_ofst, ps_bitstrm->pu4_buf, ps_bitstrm->u4_bit_ofst, ps_bitstrm->u4_cur_word, ps_bitstrm->u4_nxt_word, 9); #endif /* cabac context initialization based on init idc and slice qp */ memcpy(ps_cabac->au1_ctxt_models, pu1_init_ctxt, IHEVC_CAB_CTXT_END); DEBUG_RANGE_OFST("init", ps_cabac->u4_range, ps_cabac->u4_ofst); return ((IHEVCD_ERROR_T)IHEVCD_SUCCESS); } Commit Message: Return error from cabac init if offset is greater than range When the offset was greater than range, the bitstream was read more than the valid range in leaf-level cabac parsing modules. Error check was added to cabac init to fix this issue. Additionally end of slice and slice error were signalled to suppress further parsing of current slice. Bug: 34897036 Change-Id: I1263f1d1219684ffa6e952c76e5a08e9a933c9d2 (cherry picked from commit 3b175da88a1807d19cdd248b74bce60e57f05c6a) (cherry picked from commit b92314c860d01d754ef579eafe55d7377962b3ba) CWE ID: CWE-119
IHEVCD_ERROR_T ihevcd_cabac_init(cab_ctxt_t *ps_cabac, bitstrm_t *ps_bitstrm, WORD32 qp, WORD32 cabac_init_idc, const UWORD8 *pu1_init_ctxt) { /* Sanity checks */ ASSERT(ps_cabac != NULL); ASSERT(ps_bitstrm != NULL); ASSERT((qp >= 0) && (qp < 52)); ASSERT((cabac_init_idc >= 0) && (cabac_init_idc < 3)); UNUSED(qp); UNUSED(cabac_init_idc); /* CABAC engine uses 32 bit range instead of 9 bits as specified by * the spec. This is done to reduce number of renormalizations */ /* cabac engine initialization */ #if FULLRANGE ps_cabac->u4_range = (UWORD32)510 << RANGE_SHIFT; BITS_GET(ps_cabac->u4_ofst, ps_bitstrm->pu4_buf, ps_bitstrm->u4_bit_ofst, ps_bitstrm->u4_cur_word, ps_bitstrm->u4_nxt_word, (9 + RANGE_SHIFT)); #else ps_cabac->u4_range = (UWORD32)510; BITS_GET(ps_cabac->u4_ofst, ps_bitstrm->pu4_buf, ps_bitstrm->u4_bit_ofst, ps_bitstrm->u4_cur_word, ps_bitstrm->u4_nxt_word, 9); #endif /* cabac context initialization based on init idc and slice qp */ memcpy(ps_cabac->au1_ctxt_models, pu1_init_ctxt, IHEVC_CAB_CTXT_END); DEBUG_RANGE_OFST("init", ps_cabac->u4_range, ps_cabac->u4_ofst); /* * If the offset is greater than or equal to range, return fail. */ if(ps_cabac->u4_ofst >= ps_cabac->u4_range) { return ((IHEVCD_ERROR_T)IHEVCD_FAIL); } return ((IHEVCD_ERROR_T)IHEVCD_SUCCESS); }
174,029
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_GetObjectItem( cJSON *object, const char *string ) { cJSON *c = object->child; while ( c && cJSON_strcasecmp( c->string, string ) ) c = c->next; return c; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
cJSON *cJSON_GetObjectItem( cJSON *object, const char *string )
167,289
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8023_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)", bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)", bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)", tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s", bittok2str(lldp_mdi_values, "none", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)), tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u", bittok2str(lldp_aggregation_values, "none", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; } Commit Message: CVE-2017-13054/LLDP: add a missing length check In lldp_private_8023_print() the case block for subtype 4 (Maximum Frame Size TLV, IEEE 802.3bc-2009 Section 79.3.4) did not include the length check and could over-read the input buffer, put it right. 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
lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8023_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)", bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)", bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)", tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s", bittok2str(lldp_mdi_values, "none", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)), tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u", bittok2str(lldp_aggregation_values, "none", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: if (tlv_len < 6) { return hexdump; } ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; }
167,819
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: produce_output() { char *str; FILE *mailer; MyString subject,szTmp; subject.sprintf("condor_preen results %s: %d old file%s found", my_full_hostname(), BadFiles->number(), (BadFiles->number() > 1)?"s":""); if( MailFlag ) { if( (mailer=email_open(PreenAdmin, subject.Value())) == NULL ) { EXCEPT( "Can't do email_open(\"%s\", \"%s\")\n",PreenAdmin,subject.Value()); } } else { mailer = stdout; } szTmp.sprintf("The condor_preen process has found the following stale condor files on <%s>:\n\n", get_local_hostname().Value()); dprintf(D_ALWAYS, szTmp.Value()); if( MailFlag ) { fprintf( mailer, "\n" ); fprintf( mailer, szTmp.Value()); } for( BadFiles->rewind(); (str = BadFiles->next()); ) { szTmp.sprintf(" %s\n", str); dprintf(D_ALWAYS, szTmp.Value() ); fprintf( mailer, szTmp.Value() ); } if( MailFlag ) { const char *explanation = "\n\nWhat is condor_preen?\n\n" "The condor_preen tool examines the directories belonging to Condor, and\n" "removes extraneous files and directories which may be left over from Condor\n" "processes which terminated abnormally either due to internal errors or a\n" "system crash. The directories checked are the LOG, EXECUTE, and SPOOL\n" "directories as defined in the Condor configuration files. The condor_preen\n" "tool is intended to be run as user root (or user condor) periodically as a\n" "backup method to ensure reasonable file system cleanliness in the face of\n" "errors. This is done automatically by default by the condor_master daemon.\n" "It may also be explicitly invoked on an as needed basis.\n\n" "See the Condor manual section on condor_preen for more details.\n"; fprintf( mailer, "%s\n", explanation ); email_close( mailer ); } } Commit Message: CWE ID: CWE-134
produce_output() { char *str; FILE *mailer; MyString subject,szTmp; subject.sprintf("condor_preen results %s: %d old file%s found", my_full_hostname(), BadFiles->number(), (BadFiles->number() > 1)?"s":""); if( MailFlag ) { if( (mailer=email_open(PreenAdmin, subject.Value())) == NULL ) { EXCEPT( "Can't do email_open(\"%s\", \"%s\")\n",PreenAdmin,subject.Value()); } } else { mailer = stdout; } szTmp.sprintf("The condor_preen process has found the following stale condor files on <%s>:\n\n", get_local_hostname().Value()); dprintf(D_ALWAYS, "%s", szTmp.Value()); if( MailFlag ) { fprintf( mailer, "\n" ); fprintf( mailer, "%s", szTmp.Value()); } for( BadFiles->rewind(); (str = BadFiles->next()); ) { szTmp.sprintf(" %s\n", str); dprintf(D_ALWAYS, "%s", szTmp.Value() ); fprintf( mailer, "%s", szTmp.Value() ); } if( MailFlag ) { const char *explanation = "\n\nWhat is condor_preen?\n\n" "The condor_preen tool examines the directories belonging to Condor, and\n" "removes extraneous files and directories which may be left over from Condor\n" "processes which terminated abnormally either due to internal errors or a\n" "system crash. The directories checked are the LOG, EXECUTE, and SPOOL\n" "directories as defined in the Condor configuration files. The condor_preen\n" "tool is intended to be run as user root (or user condor) periodically as a\n" "backup method to ensure reasonable file system cleanliness in the face of\n" "errors. This is done automatically by default by the condor_master daemon.\n" "It may also be explicitly invoked on an as needed basis.\n\n" "See the Condor manual section on condor_preen for more details.\n"; fprintf( mailer, "%s\n", explanation ); email_close( mailer ); } }
165,381
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: UWORD32 ihevcd_cabac_decode_bypass_bins_egk(cab_ctxt_t *ps_cabac, bitstrm_t *ps_bitstrm, WORD32 k) { UWORD32 u4_sym; WORD32 numones; WORD32 bin; /* Sanity checks */ ASSERT((k >= 0)); numones = k; bin = 1; u4_sym = 0; while(bin) { IHEVCD_CABAC_DECODE_BYPASS_BIN(bin, ps_cabac, ps_bitstrm); u4_sym += bin << numones++; } numones -= 1; numones = CLIP3(numones, 0, 16); if(numones) { UWORD32 u4_suffix; IHEVCD_CABAC_DECODE_BYPASS_BINS(u4_suffix, ps_cabac, ps_bitstrm, numones); u4_sym += u4_suffix; } return (u4_sym); } Commit Message: Fix in handling wrong cu_qp_delta cu_qp_delta is now checked for the range as specified in the spec Bug: 33966031 Change-Id: I00420bf68081af92e9f2be9af7ce58d0683094ca CWE ID: CWE-119
UWORD32 ihevcd_cabac_decode_bypass_bins_egk(cab_ctxt_t *ps_cabac, bitstrm_t *ps_bitstrm, WORD32 k) { UWORD32 u4_sym; WORD32 numones; WORD32 bin; /* Sanity checks */ ASSERT((k >= 0)); numones = k; bin = 1; u4_sym = 0; while(bin && (numones <= 16)) { IHEVCD_CABAC_DECODE_BYPASS_BIN(bin, ps_cabac, ps_bitstrm); u4_sym += bin << numones++; } numones -= 1; if(numones) { UWORD32 u4_suffix; IHEVCD_CABAC_DECODE_BYPASS_BINS(u4_suffix, ps_cabac, ps_bitstrm, numones); u4_sym += u4_suffix; } return (u4_sym); }
174,051
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UsbDeviceImpl::OnPathAccessRequestComplete(const OpenCallback& callback, bool success) { if (success) { blocking_task_runner_->PostTask( FROM_HERE, base::Bind(&UsbDeviceImpl::OpenOnBlockingThread, this, callback)); } else { chromeos::PermissionBrokerClient* client = chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient(); DCHECK(client) << "Could not get permission broker client."; client->OpenPath( device_path_, base::Bind(&UsbDeviceImpl::OnOpenRequestComplete, this, callback)); } } Commit Message: Remove fallback when requesting a single USB interface. This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The permission broker now supports opening devices that are partially claimed through the OpenPath method and RequestPathAccess will always fail for these devices so the fallback path from RequestPathAccess to OpenPath is always taken. BUG=500057 Review URL: https://codereview.chromium.org/1227313003 Cr-Commit-Position: refs/heads/master@{#338354} CWE ID: CWE-399
void UsbDeviceImpl::OnPathAccessRequestComplete(const OpenCallback& callback,
171,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate, Handle<JSObject> object, Handle<Object> value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *object)); Handle<Map> original_map = handle(object->map(), isolate); Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()), isolate); for (uint32_t k = start_from; k < length; ++k) { uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k, ALL_PROPERTIES); if (entry == kMaxUInt32) { continue; } Handle<Object> element_k = Subclass::GetImpl(isolate, *parameter_map, entry); if (element_k->IsAccessorPair()) { LookupIterator it(isolate, object, k, LookupIterator::OWN); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k, Object::GetPropertyWithAccessor(&it), Nothing<int64_t>()); if (value->StrictEquals(*element_k)) { return Just<int64_t>(k); } if (object->map() != *original_map) { return IndexOfValueSlowPath(isolate, object, value, k + 1, length); } } else if (value->StrictEquals(*element_k)) { return Just<int64_t>(k); } } return Just<int64_t>(-1); } Commit Message: Backport: Fix Object.entries/values with changing elements Bug: 111274046 Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \ /data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb (cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99) CWE ID: CWE-704
static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate, Handle<JSObject> object, Handle<Object> value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *object)); Handle<Map> original_map(object->map(), isolate); Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()), isolate); for (uint32_t k = start_from; k < length; ++k) { DCHECK_EQ(object->map(), *original_map); uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k, ALL_PROPERTIES); if (entry == kMaxUInt32) { continue; } Handle<Object> element_k = Subclass::GetImpl(isolate, *parameter_map, entry); if (element_k->IsAccessorPair()) { LookupIterator it(isolate, object, k, LookupIterator::OWN); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k, Object::GetPropertyWithAccessor(&it), Nothing<int64_t>()); if (value->StrictEquals(*element_k)) { return Just<int64_t>(k); } if (object->map() != *original_map) { return IndexOfValueSlowPath(isolate, object, value, k + 1, length); } } else if (value->StrictEquals(*element_k)) { return Just<int64_t>(k); } } return Just<int64_t>(-1); }
174,099
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ServiceWorkerHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; if (!process_host) { ClearForceUpdate(); context_ = nullptr; return; } StoragePartition* partition = process_host->GetStoragePartition(); DCHECK(partition); context_ = static_cast<ServiceWorkerContextWrapper*>( partition->GetServiceWorkerContext()); } 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 ServiceWorkerHandler::SetRenderer(RenderProcessHost* process_host, void ServiceWorkerHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { RenderProcessHost* process_host = RenderProcessHost::FromID(process_host_id); if (!process_host) { ClearForceUpdate(); context_ = nullptr; return; } storage_partition_ = static_cast<StoragePartitionImpl*>(process_host->GetStoragePartition()); DCHECK(storage_partition_); context_ = static_cast<ServiceWorkerContextWrapper*>( storage_partition_->GetServiceWorkerContext()); }
172,769
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppCacheHost::MarkAsForeignEntry(const GURL& document_url, int64 cache_document_was_loaded_from) { storage()->MarkEntryAsForeign( main_resource_was_namespace_entry_ ? namespace_entry_url_ : document_url, cache_document_was_loaded_from); SelectCache(document_url, kAppCacheNoCacheId, GURL()); } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
void AppCacheHost::MarkAsForeignEntry(const GURL& document_url, bool AppCacheHost::MarkAsForeignEntry(const GURL& document_url, int64 cache_document_was_loaded_from) { if (was_select_cache_called_) return false; storage()->MarkEntryAsForeign( main_resource_was_namespace_entry_ ? namespace_entry_url_ : document_url, cache_document_was_loaded_from); SelectCache(document_url, kAppCacheNoCacheId, GURL()); return true; }
171,739
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ResourceCoordinatorService::OnStart() { ref_factory_.reset(new service_manager::ServiceContextRefFactory( base::Bind(&service_manager::ServiceContext::RequestQuit, base::Unretained(context())))); ukm_recorder_ = ukm::MojoUkmRecorder::Create(context()->connector()); registry_.AddInterface( base::Bind(&CoordinationUnitIntrospectorImpl::BindToInterface, base::Unretained(&introspector_))); auto page_signal_generator_impl = std::make_unique<PageSignalGeneratorImpl>(); registry_.AddInterface( base::Bind(&PageSignalGeneratorImpl::BindToInterface, base::Unretained(page_signal_generator_impl.get()))); coordination_unit_manager_.RegisterObserver( std::move(page_signal_generator_impl)); coordination_unit_manager_.RegisterObserver( std::make_unique<MetricsCollector>()); coordination_unit_manager_.RegisterObserver( std::make_unique<IPCVolumeReporter>( std::make_unique<base::OneShotTimer>())); coordination_unit_manager_.OnStart(&registry_, ref_factory_.get()); coordination_unit_manager_.set_ukm_recorder(ukm_recorder_.get()); memory_instrumentation_coordinator_ = std::make_unique<memory_instrumentation::CoordinatorImpl>( context()->connector()); registry_.AddInterface(base::BindRepeating( &memory_instrumentation::CoordinatorImpl::BindCoordinatorRequest, base::Unretained(memory_instrumentation_coordinator_.get()))); tracing_agent_registry_ = std::make_unique<tracing::AgentRegistry>(); registry_.AddInterface( base::BindRepeating(&tracing::AgentRegistry::BindAgentRegistryRequest, base::Unretained(tracing_agent_registry_.get()))); tracing_coordinator_ = std::make_unique<tracing::Coordinator>(); registry_.AddInterface( base::BindRepeating(&tracing::Coordinator::BindCoordinatorRequest, base::Unretained(tracing_coordinator_.get()))); } Commit Message: memory-infra: split up memory-infra coordinator service into two This allows for heap profiler to use its own service with correct capabilities and all other instances to use the existing coordinator service. Bug: 792028 Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd Reviewed-on: https://chromium-review.googlesource.com/836896 Commit-Queue: Lalit Maganti <lalitm@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: oysteine <oysteine@chromium.org> Reviewed-by: Albert J. Wong <ajwong@chromium.org> Reviewed-by: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#529059} CWE ID: CWE-269
void ResourceCoordinatorService::OnStart() { ref_factory_.reset(new service_manager::ServiceContextRefFactory( base::Bind(&service_manager::ServiceContext::RequestQuit, base::Unretained(context())))); ukm_recorder_ = ukm::MojoUkmRecorder::Create(context()->connector()); registry_.AddInterface( base::Bind(&CoordinationUnitIntrospectorImpl::BindToInterface, base::Unretained(&introspector_))); auto page_signal_generator_impl = std::make_unique<PageSignalGeneratorImpl>(); registry_.AddInterface( base::Bind(&PageSignalGeneratorImpl::BindToInterface, base::Unretained(page_signal_generator_impl.get()))); coordination_unit_manager_.RegisterObserver( std::move(page_signal_generator_impl)); coordination_unit_manager_.RegisterObserver( std::make_unique<MetricsCollector>()); coordination_unit_manager_.RegisterObserver( std::make_unique<IPCVolumeReporter>( std::make_unique<base::OneShotTimer>())); coordination_unit_manager_.OnStart(&registry_, ref_factory_.get()); coordination_unit_manager_.set_ukm_recorder(ukm_recorder_.get()); memory_instrumentation_coordinator_ = std::make_unique<memory_instrumentation::CoordinatorImpl>( context()->connector()); registry_.AddInterface(base::BindRepeating( &memory_instrumentation::CoordinatorImpl::BindCoordinatorRequest, base::Unretained(memory_instrumentation_coordinator_.get()))); registry_.AddInterface(base::BindRepeating( &memory_instrumentation::CoordinatorImpl::BindHeapProfilerHelperRequest, base::Unretained(memory_instrumentation_coordinator_.get()))); tracing_agent_registry_ = std::make_unique<tracing::AgentRegistry>(); registry_.AddInterface( base::BindRepeating(&tracing::AgentRegistry::BindAgentRegistryRequest, base::Unretained(tracing_agent_registry_.get()))); tracing_coordinator_ = std::make_unique<tracing::Coordinator>(); registry_.AddInterface( base::BindRepeating(&tracing::Coordinator::BindCoordinatorRequest, base::Unretained(tracing_coordinator_.get()))); }
172,919
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::fillBuffer(OMX::buffer_id buffer, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); header->nFilledLen = 0; header->nOffset = 0; header->nFlags = 0; status_t res = storeFenceInMeta_l(header, fenceFd, kPortIndexOutput); if (res != OK) { CLOG_ERROR(fillBuffer::storeFenceInMeta, res, EMPTY_BUFFER(buffer, header, fenceFd)); return res; } { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.add(header); CLOG_BUMPED_BUFFER(fillBuffer, WITH_STATS(EMPTY_BUFFER(buffer, header, fenceFd))); } OMX_ERRORTYPE err = OMX_FillThisBuffer(mHandle, header); if (err != OMX_ErrorNone) { CLOG_ERROR(fillBuffer, err, EMPTY_BUFFER(buffer, header, fenceFd)); Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(header); } return StatusFromOMXError(err); } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::fillBuffer(OMX::buffer_id buffer, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexOutput); if (header == NULL) { return BAD_VALUE; } header->nFilledLen = 0; header->nOffset = 0; header->nFlags = 0; status_t res = storeFenceInMeta_l(header, fenceFd, kPortIndexOutput); if (res != OK) { CLOG_ERROR(fillBuffer::storeFenceInMeta, res, EMPTY_BUFFER(buffer, header, fenceFd)); return res; } { Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.add(header); CLOG_BUMPED_BUFFER(fillBuffer, WITH_STATS(EMPTY_BUFFER(buffer, header, fenceFd))); } OMX_ERRORTYPE err = OMX_FillThisBuffer(mHandle, header); if (err != OMX_ErrorNone) { CLOG_ERROR(fillBuffer, err, EMPTY_BUFFER(buffer, header, fenceFd)); Mutex::Autolock _l(mDebugLock); mOutputBuffersWithCodec.remove(header); } return StatusFromOMXError(err); }
173,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_GetArrayItem( cJSON *array, int item ) { cJSON *c = array->child; while ( c && item > 0 ) { --item; c = c->next; } return c; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
cJSON *cJSON_GetArrayItem( cJSON *array, int item )
167,286
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static future_t *init(void) { pthread_mutex_init(&lock, NULL); config = config_new(CONFIG_FILE_PATH); if (!config) { LOG_WARN("%s unable to load config file; attempting to transcode legacy file.", __func__); config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH); if (!config) { LOG_WARN("%s unable to transcode legacy file, starting unconfigured.", __func__); config = config_new_empty(); if (!config) { LOG_ERROR("%s unable to allocate a config object.", __func__); goto error; } } if (config_save(config, CONFIG_FILE_PATH)) unlink(LEGACY_CONFIG_FILE_PATH); } btif_config_remove_unpaired(config); alarm_timer = alarm_new(); if (!alarm_timer) { LOG_ERROR("%s unable to create alarm.", __func__); goto error; } return future_new_immediate(FUTURE_SUCCESS); error:; alarm_free(alarm_timer); config_free(config); pthread_mutex_destroy(&lock); alarm_timer = NULL; config = NULL; return future_new_immediate(FUTURE_FAIL); } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
static future_t *init(void) { pthread_mutex_init(&lock, NULL); config = config_new(CONFIG_FILE_PATH); if (!config) { LOG_WARN("%s unable to load config file; attempting to transcode legacy file.", __func__); config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH); if (!config) { LOG_WARN("%s unable to transcode legacy file, starting unconfigured.", __func__); config = config_new_empty(); if (!config) { LOG_ERROR("%s unable to allocate a config object.", __func__); goto error; } } if (config_save(config, CONFIG_FILE_PATH)) unlink(LEGACY_CONFIG_FILE_PATH); } btif_config_remove_unpaired(config); // Cleanup temporary pairings if we have left guest mode if (!is_restricted_mode()) btif_config_remove_restricted(config); alarm_timer = alarm_new(); if (!alarm_timer) { LOG_ERROR("%s unable to create alarm.", __func__); goto error; } return future_new_immediate(FUTURE_SUCCESS); error:; alarm_free(alarm_timer); config_free(config); pthread_mutex_destroy(&lock); alarm_timer = NULL; config = NULL; return future_new_immediate(FUTURE_FAIL); }
173,553
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltCopyTextString(xsltTransformContextPtr ctxt, xmlNodePtr target, const xmlChar *string, int noescape) { xmlNodePtr copy; int len; if (string == NULL) return(NULL); #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_TEXT,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyTextString: copy text %s\n", string)); #endif /* * Play safe and reset the merging mechanism for every new * target node. */ if ((target == NULL) || (target->children == NULL)) { ctxt->lasttext = NULL; } /* handle coalescing of text nodes here */ len = xmlStrlen(string); if ((ctxt->type == XSLT_OUTPUT_XML) && (ctxt->style->cdataSection != NULL) && (target != NULL) && (target->type == XML_ELEMENT_NODE) && (((target->ns == NULL) && (xmlHashLookup2(ctxt->style->cdataSection, target->name, NULL) != NULL)) || ((target->ns != NULL) && (xmlHashLookup2(ctxt->style->cdataSection, target->name, target->ns->href) != NULL)))) { /* * Process "cdata-section-elements". */ if ((target->last != NULL) && (target->last->type == XML_CDATA_SECTION_NODE)) { return(xsltAddTextString(ctxt, target->last, string, len)); } copy = xmlNewCDataBlock(ctxt->output, string, len); } else if (noescape) { /* * Process "disable-output-escaping". */ if ((target != NULL) && (target->last != NULL) && (target->last->type == XML_TEXT_NODE) && (target->last->name == xmlStringTextNoenc)) { return(xsltAddTextString(ctxt, target->last, string, len)); } copy = xmlNewTextLen(string, len); if (copy != NULL) copy->name = xmlStringTextNoenc; } else { /* * Default processing. */ if ((target != NULL) && (target->last != NULL) && (target->last->type == XML_TEXT_NODE) && (target->last->name == xmlStringText)) { return(xsltAddTextString(ctxt, target->last, string, len)); } copy = xmlNewTextLen(string, len); } if (copy != NULL) { if (target != NULL) copy = xsltAddChild(target, copy); ctxt->lasttext = copy->content; ctxt->lasttsize = len; ctxt->lasttuse = len; } else { xsltTransformError(ctxt, NULL, target, "xsltCopyTextString: text copy failed\n"); ctxt->lasttext = NULL; } return(copy); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltCopyTextString(xsltTransformContextPtr ctxt, xmlNodePtr target, const xmlChar *string, int noescape) { xmlNodePtr copy; int len; if (string == NULL) return(NULL); #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_TEXT,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyTextString: copy text %s\n", string)); #endif /* * Play safe and reset the merging mechanism for every new * target node. */ if ((target == NULL) || (target->children == NULL)) { ctxt->lasttext = NULL; } /* handle coalescing of text nodes here */ len = xmlStrlen(string); if ((ctxt->type == XSLT_OUTPUT_XML) && (ctxt->style->cdataSection != NULL) && (target != NULL) && (target->type == XML_ELEMENT_NODE) && (((target->ns == NULL) && (xmlHashLookup2(ctxt->style->cdataSection, target->name, NULL) != NULL)) || ((target->ns != NULL) && (xmlHashLookup2(ctxt->style->cdataSection, target->name, target->ns->href) != NULL)))) { /* * Process "cdata-section-elements". */ if ((target->last != NULL) && (target->last->type == XML_CDATA_SECTION_NODE)) { return(xsltAddTextString(ctxt, target->last, string, len)); } copy = xmlNewCDataBlock(ctxt->output, string, len); } else if (noescape) { /* * Process "disable-output-escaping". */ if ((target != NULL) && (target->last != NULL) && (target->last->type == XML_TEXT_NODE) && (target->last->name == xmlStringTextNoenc)) { return(xsltAddTextString(ctxt, target->last, string, len)); } copy = xmlNewTextLen(string, len); if (copy != NULL) copy->name = xmlStringTextNoenc; } else { /* * Default processing. */ if ((target != NULL) && (target->last != NULL) && (target->last->type == XML_TEXT_NODE) && (target->last->name == xmlStringText)) { return(xsltAddTextString(ctxt, target->last, string, len)); } copy = xmlNewTextLen(string, len); } if (copy != NULL && target != NULL) copy = xsltAddChild(target, copy); if (copy != NULL) { ctxt->lasttext = copy->content; ctxt->lasttsize = len; ctxt->lasttuse = len; } else { xsltTransformError(ctxt, NULL, target, "xsltCopyTextString: text copy failed\n"); ctxt->lasttext = NULL; } return(copy); }
173,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: rpl_dio_printopt(netdissect_options *ndo, const struct rpl_dio_genoption *opt, u_int length) { if(length < RPL_DIO_GENOPTION_LEN) return; length -= RPL_DIO_GENOPTION_LEN; ND_TCHECK(opt->rpl_dio_len); while((opt->rpl_dio_type == RPL_OPT_PAD0 && (const u_char *)opt < ndo->ndo_snapend) || ND_TTEST2(*opt,(opt->rpl_dio_len+2))) { unsigned int optlen = opt->rpl_dio_len+2; if(opt->rpl_dio_type == RPL_OPT_PAD0) { optlen = 1; ND_PRINT((ndo, " opt:pad0")); } else { ND_PRINT((ndo, " opt:%s len:%u ", tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type), optlen)); if(ndo->ndo_vflag > 2) { unsigned int paylen = opt->rpl_dio_len; if(paylen > length) paylen = length; hex_print(ndo, " ", ((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */ paylen); } } opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen); length -= optlen; } return; trunc: ND_PRINT((ndo," [|truncated]")); return; } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
rpl_dio_printopt(netdissect_options *ndo, const struct rpl_dio_genoption *opt, u_int length) { if(length < RPL_DIO_GENOPTION_LEN) return; length -= RPL_DIO_GENOPTION_LEN; ND_TCHECK(opt->rpl_dio_len); while((opt->rpl_dio_type == RPL_OPT_PAD0 && (const u_char *)opt < ndo->ndo_snapend) || ND_TTEST2(*opt,(opt->rpl_dio_len+2))) { unsigned int optlen = opt->rpl_dio_len+2; if(opt->rpl_dio_type == RPL_OPT_PAD0) { optlen = 1; ND_PRINT((ndo, " opt:pad0")); } else { ND_PRINT((ndo, " opt:%s len:%u ", tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type), optlen)); if(ndo->ndo_vflag > 2) { unsigned int paylen = opt->rpl_dio_len; if(paylen > length) paylen = length; hex_print(ndo, " ", ((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */ paylen); } } opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen); length -= optlen; ND_TCHECK(opt->rpl_dio_len); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; }
169,831
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct key *key_get_instantiation_authkey(key_serial_t target_id) { char description[16]; struct keyring_search_context ctx = { .index_key.type = &key_type_request_key_auth, .index_key.description = description, .cred = current_cred(), .match_data.cmp = user_match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *authkey; key_ref_t authkey_ref; sprintf(description, "%x", target_id); authkey_ref = search_process_keyrings(&ctx); if (IS_ERR(authkey_ref)) { authkey = ERR_CAST(authkey_ref); if (authkey == ERR_PTR(-EAGAIN)) authkey = ERR_PTR(-ENOKEY); goto error; } authkey = key_ref_to_ptr(authkey_ref); if (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) { key_put(authkey); authkey = ERR_PTR(-EKEYREVOKED); } error: return authkey; } 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
struct key *key_get_instantiation_authkey(key_serial_t target_id) { char description[16]; struct keyring_search_context ctx = { .index_key.type = &key_type_request_key_auth, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *authkey; key_ref_t authkey_ref; sprintf(description, "%x", target_id); authkey_ref = search_process_keyrings(&ctx); if (IS_ERR(authkey_ref)) { authkey = ERR_CAST(authkey_ref); if (authkey == ERR_PTR(-EAGAIN)) authkey = ERR_PTR(-ENOKEY); goto error; } authkey = key_ref_to_ptr(authkey_ref); if (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) { key_put(authkey); authkey = ERR_PTR(-EKEYREVOKED); } error: return authkey; }
168,442
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int fanout_add(struct sock *sk, u16 id, u16 type_flags) { struct packet_sock *po = pkt_sk(sk); struct packet_fanout *f, *match; u8 type = type_flags & 0xff; u8 flags = type_flags >> 8; int err; switch (type) { case PACKET_FANOUT_ROLLOVER: if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER) return -EINVAL; case PACKET_FANOUT_HASH: case PACKET_FANOUT_LB: case PACKET_FANOUT_CPU: case PACKET_FANOUT_RND: case PACKET_FANOUT_QM: case PACKET_FANOUT_CBPF: case PACKET_FANOUT_EBPF: break; default: return -EINVAL; } if (!po->running) return -EINVAL; if (po->fanout) return -EALREADY; if (type == PACKET_FANOUT_ROLLOVER || (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) { po->rollover = kzalloc(sizeof(*po->rollover), GFP_KERNEL); if (!po->rollover) return -ENOMEM; atomic_long_set(&po->rollover->num, 0); atomic_long_set(&po->rollover->num_huge, 0); atomic_long_set(&po->rollover->num_failed, 0); } mutex_lock(&fanout_mutex); match = NULL; list_for_each_entry(f, &fanout_list, list) { if (f->id == id && read_pnet(&f->net) == sock_net(sk)) { match = f; break; } } err = -EINVAL; if (match && match->flags != flags) goto out; if (!match) { err = -ENOMEM; match = kzalloc(sizeof(*match), GFP_KERNEL); if (!match) goto out; write_pnet(&match->net, sock_net(sk)); match->id = id; match->type = type; match->flags = flags; INIT_LIST_HEAD(&match->list); spin_lock_init(&match->lock); atomic_set(&match->sk_ref, 0); fanout_init_data(match); match->prot_hook.type = po->prot_hook.type; match->prot_hook.dev = po->prot_hook.dev; match->prot_hook.func = packet_rcv_fanout; match->prot_hook.af_packet_priv = match; match->prot_hook.id_match = match_fanout_group; dev_add_pack(&match->prot_hook); list_add(&match->list, &fanout_list); } err = -EINVAL; if (match->type == type && match->prot_hook.type == po->prot_hook.type && match->prot_hook.dev == po->prot_hook.dev) { err = -ENOSPC; if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) { __dev_remove_pack(&po->prot_hook); po->fanout = match; atomic_inc(&match->sk_ref); __fanout_link(sk, po); err = 0; } } out: mutex_unlock(&fanout_mutex); if (err) { kfree(po->rollover); po->rollover = NULL; } return err; } Commit Message: packet: fix races in fanout_add() Multiple threads can call fanout_add() at the same time. We need to grab fanout_mutex earlier to avoid races that could lead to one thread freeing po->rollover that was set by another thread. Do the same in fanout_release(), for peace of mind, and to help us finding lockdep issues earlier. Fixes: dc99f600698d ("packet: Add fanout support.") Fixes: 0648ab70afe6 ("packet: rollover prepare: per-socket state") Signed-off-by: Eric Dumazet <edumazet@google.com> Cc: Willem de Bruijn <willemb@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
static int fanout_add(struct sock *sk, u16 id, u16 type_flags) { struct packet_rollover *rollover = NULL; struct packet_sock *po = pkt_sk(sk); struct packet_fanout *f, *match; u8 type = type_flags & 0xff; u8 flags = type_flags >> 8; int err; switch (type) { case PACKET_FANOUT_ROLLOVER: if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER) return -EINVAL; case PACKET_FANOUT_HASH: case PACKET_FANOUT_LB: case PACKET_FANOUT_CPU: case PACKET_FANOUT_RND: case PACKET_FANOUT_QM: case PACKET_FANOUT_CBPF: case PACKET_FANOUT_EBPF: break; default: return -EINVAL; } mutex_lock(&fanout_mutex); err = -EINVAL; if (!po->running) goto out; err = -EALREADY; if (po->fanout) goto out; if (type == PACKET_FANOUT_ROLLOVER || (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) { err = -ENOMEM; rollover = kzalloc(sizeof(*rollover), GFP_KERNEL); if (!rollover) goto out; atomic_long_set(&rollover->num, 0); atomic_long_set(&rollover->num_huge, 0); atomic_long_set(&rollover->num_failed, 0); po->rollover = rollover; } match = NULL; list_for_each_entry(f, &fanout_list, list) { if (f->id == id && read_pnet(&f->net) == sock_net(sk)) { match = f; break; } } err = -EINVAL; if (match && match->flags != flags) goto out; if (!match) { err = -ENOMEM; match = kzalloc(sizeof(*match), GFP_KERNEL); if (!match) goto out; write_pnet(&match->net, sock_net(sk)); match->id = id; match->type = type; match->flags = flags; INIT_LIST_HEAD(&match->list); spin_lock_init(&match->lock); atomic_set(&match->sk_ref, 0); fanout_init_data(match); match->prot_hook.type = po->prot_hook.type; match->prot_hook.dev = po->prot_hook.dev; match->prot_hook.func = packet_rcv_fanout; match->prot_hook.af_packet_priv = match; match->prot_hook.id_match = match_fanout_group; dev_add_pack(&match->prot_hook); list_add(&match->list, &fanout_list); } err = -EINVAL; if (match->type == type && match->prot_hook.type == po->prot_hook.type && match->prot_hook.dev == po->prot_hook.dev) { err = -ENOSPC; if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) { __dev_remove_pack(&po->prot_hook); po->fanout = match; atomic_inc(&match->sk_ref); __fanout_link(sk, po); err = 0; } } out: if (err && rollover) { kfree(rollover); po->rollover = NULL; } mutex_unlock(&fanout_mutex); return err; }
168,346
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_vdec::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr) { unsigned int index = 0; if (bufferHdr == NULL || m_inp_mem_ptr == NULL) { return OMX_ErrorBadParameter; } index = bufferHdr - m_inp_mem_ptr; DEBUG_PRINT_LOW("Free Input Buffer index = %d",index); if (index < drv_ctx.ip_buf.actualcount && drv_ctx.ptr_inputbuffer) { DEBUG_PRINT_LOW("Free Input Buffer index = %d",index); if (drv_ctx.ptr_inputbuffer[index].pmem_fd > 0) { struct vdec_setbuffer_cmd setbuffers; setbuffers.buffer_type = VDEC_BUFFER_TYPE_INPUT; memcpy (&setbuffers.buffer,&drv_ctx.ptr_inputbuffer[index], sizeof (vdec_bufferpayload)); if (!secure_mode) { DEBUG_PRINT_LOW("unmap the input buffer fd=%d", drv_ctx.ptr_inputbuffer[index].pmem_fd); DEBUG_PRINT_LOW("unmap the input buffer size=%u address = %p", (unsigned int)drv_ctx.ptr_inputbuffer[index].mmaped_size, drv_ctx.ptr_inputbuffer[index].bufferaddr); munmap (drv_ctx.ptr_inputbuffer[index].bufferaddr, drv_ctx.ptr_inputbuffer[index].mmaped_size); } close (drv_ctx.ptr_inputbuffer[index].pmem_fd); drv_ctx.ptr_inputbuffer[index].pmem_fd = -1; if (m_desc_buffer_ptr && m_desc_buffer_ptr[index].buf_addr) { free(m_desc_buffer_ptr[index].buf_addr); m_desc_buffer_ptr[index].buf_addr = NULL; m_desc_buffer_ptr[index].desc_data_size = 0; } #ifdef USE_ION free_ion_memory(&drv_ctx.ip_buf_ion_info[index]); #endif } } return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27890802 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVdec problem #6) CRs-Fixed: 1008882 Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e CWE ID:
OMX_ERRORTYPE omx_vdec::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr) { unsigned int index = 0; if (bufferHdr == NULL || m_inp_mem_ptr == NULL) { return OMX_ErrorBadParameter; } index = bufferHdr - m_inp_mem_ptr; DEBUG_PRINT_LOW("Free Input Buffer index = %d",index); auto_lock l(buf_lock); bufferHdr->pInputPortPrivate = NULL; if (index < drv_ctx.ip_buf.actualcount && drv_ctx.ptr_inputbuffer) { DEBUG_PRINT_LOW("Free Input Buffer index = %d",index); if (drv_ctx.ptr_inputbuffer[index].pmem_fd > 0) { struct vdec_setbuffer_cmd setbuffers; setbuffers.buffer_type = VDEC_BUFFER_TYPE_INPUT; memcpy (&setbuffers.buffer,&drv_ctx.ptr_inputbuffer[index], sizeof (vdec_bufferpayload)); if (!secure_mode) { DEBUG_PRINT_LOW("unmap the input buffer fd=%d", drv_ctx.ptr_inputbuffer[index].pmem_fd); DEBUG_PRINT_LOW("unmap the input buffer size=%u address = %p", (unsigned int)drv_ctx.ptr_inputbuffer[index].mmaped_size, drv_ctx.ptr_inputbuffer[index].bufferaddr); munmap (drv_ctx.ptr_inputbuffer[index].bufferaddr, drv_ctx.ptr_inputbuffer[index].mmaped_size); } close (drv_ctx.ptr_inputbuffer[index].pmem_fd); drv_ctx.ptr_inputbuffer[index].pmem_fd = -1; if (m_desc_buffer_ptr && m_desc_buffer_ptr[index].buf_addr) { free(m_desc_buffer_ptr[index].buf_addr); m_desc_buffer_ptr[index].buf_addr = NULL; m_desc_buffer_ptr[index].desc_data_size = 0; } #ifdef USE_ION free_ion_memory(&drv_ctx.ip_buf_ion_info[index]); #endif } } return OMX_ErrorNone; }
173,752
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ipt_entry *)e); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-119
check_compat_entry_size_and_hooks(struct compat_ipt_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ipt_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ipt_entry *)e); if (ret) return ret; off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ip, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ipt_get_target(e); target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; }
167,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) * and so must be adjusted for low bit depth grayscale: */ if (out_depth <= 8) { if (pm->log8 == 0) /* switched off */ return 256; if (out_depth < 8) return pm->log8 / 255 * ((1<<out_depth)-1); return pm->log8; } if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) { if (pm->log16 == 0) return 65536; return pm->log16; } /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ if (pm->log8 == 0) return 65536; return pm->log8 * 257; } 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 outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth) static double outlog(const png_modifier *pm, int in_depth, int out_depth) { /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) * and so must be adjusted for low bit depth grayscale: */ if (out_depth <= 8) { if (pm->log8 == 0) /* switched off */ return 256; if (out_depth < 8) return pm->log8 / 255 * ((1<<out_depth)-1); return pm->log8; } if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) { if (pm->log16 == 0) return 65536; return pm->log16; } /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ if (pm->log8 == 0) return 65536; return pm->log8 * 257; }
173,675
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PP_Bool StartPpapiProxy(PP_Instance instance) { if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableNaClIPCProxy)) { ChannelHandleMap& map = g_channel_handle_map.Get(); ChannelHandleMap::iterator it = map.find(instance); if (it == map.end()) return PP_FALSE; IPC::ChannelHandle channel_handle = it->second; map.erase(it); webkit::ppapi::PluginInstance* plugin_instance = content::GetHostGlobals()->GetInstance(instance); if (!plugin_instance) return PP_FALSE; WebView* web_view = plugin_instance->container()->element().document().frame()->view(); RenderView* render_view = content::RenderView::FromWebView(web_view); webkit::ppapi::PluginModule* plugin_module = plugin_instance->module(); scoped_refptr<SyncMessageStatusReceiver> status_receiver(new SyncMessageStatusReceiver()); scoped_ptr<OutOfProcessProxy> out_of_process_proxy(new OutOfProcessProxy); if (out_of_process_proxy->Init( channel_handle, plugin_module->pp_module(), webkit::ppapi::PluginModule::GetLocalGetInterfaceFunc(), ppapi::Preferences(render_view->GetWebkitPreferences()), status_receiver.get())) { plugin_module->InitAsProxiedNaCl( out_of_process_proxy.PassAs<PluginDelegate::OutOfProcessProxy>(), instance); return PP_TRUE; } } return PP_FALSE; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
PP_Bool StartPpapiProxy(PP_Instance instance) { return PP_FALSE; }
170,739
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_scale_16_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_scale_16(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_scale_16_set(PNG_CONST image_transform *this, image_transform_png_set_scale_16_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_scale_16(pp); # if PNG_LIBPNG_VER < 10700 /* libpng will limit the gamma table size: */ that->max_gamma_8 = PNG_MAX_GAMMA_8; # endif this->next->set(this->next, that, pp, pi); }
173,647
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ResourcePrefetchPredictor::PredictPreconnectOrigins( const GURL& url, PreconnectPrediction* prediction) const { DCHECK(!prediction || prediction->requests.empty()); DCHECK_CURRENTLY_ON(BrowserThread::UI); if (initialization_state_ != INITIALIZED) return false; url::Origin url_origin = url::Origin::Create(url); url::Origin redirect_origin; bool has_any_prediction = GetRedirectEndpointsForPreconnect( url_origin, *host_redirect_data_, prediction); if (!GetRedirectOrigin(url_origin, *host_redirect_data_, &redirect_origin)) { return has_any_prediction; } OriginData data; if (!origin_data_->TryGetData(redirect_origin.host(), &data)) { return has_any_prediction; } if (prediction) { prediction->host = redirect_origin.host(); prediction->is_redirected = (redirect_origin != url_origin); } net::NetworkIsolationKey network_isolation_key(redirect_origin, redirect_origin); for (const OriginStat& origin : data.origins()) { float confidence = static_cast<float>(origin.number_of_hits()) / (origin.number_of_hits() + origin.number_of_misses()); if (confidence < kMinOriginConfidenceToTriggerPreresolve) continue; has_any_prediction = true; if (prediction) { if (confidence > kMinOriginConfidenceToTriggerPreconnect) { prediction->requests.emplace_back(GURL(origin.origin()), 1, network_isolation_key); } else { prediction->requests.emplace_back(GURL(origin.origin()), 0, network_isolation_key); } } } return has_any_prediction; } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
bool ResourcePrefetchPredictor::PredictPreconnectOrigins( const GURL& url, PreconnectPrediction* prediction) const { DCHECK(!prediction || prediction->requests.empty()); DCHECK_CURRENTLY_ON(BrowserThread::UI); if (initialization_state_ != INITIALIZED) return false; url::Origin url_origin = url::Origin::Create(url); url::Origin redirect_origin; bool has_any_prediction = GetRedirectEndpointsForPreconnect( url_origin, *host_redirect_data_, prediction); if (!GetRedirectOrigin(url_origin, *host_redirect_data_, &redirect_origin)) { return has_any_prediction; } OriginData data; if (!origin_data_->TryGetData(redirect_origin.host(), &data)) { return has_any_prediction; } if (prediction) { prediction->host = redirect_origin.host(); prediction->is_redirected = (redirect_origin != url_origin); } net::NetworkIsolationKey network_isolation_key(redirect_origin, redirect_origin); for (const OriginStat& origin : data.origins()) { float confidence = static_cast<float>(origin.number_of_hits()) / (origin.number_of_hits() + origin.number_of_misses()); if (confidence < kMinOriginConfidenceToTriggerPreresolve) continue; has_any_prediction = true; if (prediction) { if (confidence > kMinOriginConfidenceToTriggerPreconnect) { prediction->requests.emplace_back( url::Origin::Create(GURL(origin.origin())), 1, network_isolation_key); } else { prediction->requests.emplace_back( url::Origin::Create(GURL(origin.origin())), 0, network_isolation_key); } } } return has_any_prediction; }
172,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TestingPlatformSupport::cryptographicallyRandomValues(unsigned char* buffer, size_t length) { } Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used. These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect. BUG=552749 Review URL: https://codereview.chromium.org/1419293005 Cr-Commit-Position: refs/heads/master@{#359229} CWE ID: CWE-310
void TestingPlatformSupport::cryptographicallyRandomValues(unsigned char* buffer, size_t length) { RELEASE_ASSERT_NOT_REACHED(); }
172,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ID3::ID3(const uint8_t *data, size_t size, bool ignoreV1) : mIsValid(false), mData(NULL), mSize(0), mFirstFrameOffset(0), mVersion(ID3_UNKNOWN), mRawSize(0) { sp<MemorySource> source = new MemorySource(data, size); mIsValid = parseV2(source, 0); if (!mIsValid && !ignoreV1) { mIsValid = parseV1(source); } } Commit Message: better validation lengths of strings in ID3 tags Validate lengths on strings in ID3 tags, particularly around 0. Also added code to handle cases when we can't get memory for copies of strings we want to extract from these tags. Affects L/M/N/master, same patch for all of them. Bug: 30744884 Change-Id: I2675a817a39f0927ec1f7e9f9c09f2e61020311e Test: play mp3 file which caused a <0 length. (cherry picked from commit d23c01546c4f82840a01a380def76ab6cae5d43f) CWE ID: CWE-20
ID3::ID3(const uint8_t *data, size_t size, bool ignoreV1) : mIsValid(false), mData(NULL), mSize(0), mFirstFrameOffset(0), mVersion(ID3_UNKNOWN), mRawSize(0) { sp<MemorySource> source = new (std::nothrow) MemorySource(data, size); if (source == NULL) return; mIsValid = parseV2(source, 0); if (!mIsValid && !ignoreV1) { mIsValid = parseV1(source); } }
173,392
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DiscardAndExplicitlyReloadTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); background_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false)); tab_strip_model_->GetWebContentsAt(0)->GetController().Reload( content::ReloadType::NORMAL, false); testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void DiscardAndExplicitlyReloadTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); background_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, false)); tab_strip_model_->GetWebContentsAt(0)->GetController().Reload( content::ReloadType::NORMAL, false); ::testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); }
172,225
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_surface *user_srf; struct vmw_surface *srf; struct vmw_resource *res; struct vmw_resource *tmp; union drm_vmw_gb_surface_create_arg *arg = (union drm_vmw_gb_surface_create_arg *)data; struct drm_vmw_gb_surface_create_req *req = &arg->req; struct drm_vmw_gb_surface_create_rep *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret; uint32_t size; uint32_t backup_handle; if (req->multisample_count != 0) return -EINVAL; if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS) return -EINVAL; if (unlikely(vmw_user_surface_size == 0)) vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) + 128; size = vmw_user_surface_size + 128; /* Define a surface based on the parameters. */ ret = vmw_surface_gb_priv_define(dev, size, req->svga3d_flags, req->format, req->drm_surface_flags & drm_vmw_surface_flag_scanout, req->mip_levels, req->multisample_count, req->array_size, req->base_size, &srf); if (unlikely(ret != 0)) return ret; user_srf = container_of(srf, struct vmw_user_surface, srf); if (drm_is_primary_client(file_priv)) user_srf->master = drm_master_get(file_priv->master); ret = ttm_read_lock(&dev_priv->reservation_sem, true); if (unlikely(ret != 0)) return ret; res = &user_srf->srf.res; if (req->buffer_handle != SVGA3D_INVALID_ID) { ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle, &res->backup, &user_srf->backup_base); if (ret == 0 && res->backup->base.num_pages * PAGE_SIZE < res->backup_size) { DRM_ERROR("Surface backup buffer is too small.\n"); vmw_dmabuf_unreference(&res->backup); ret = -EINVAL; goto out_unlock; } } else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer) ret = vmw_user_dmabuf_alloc(dev_priv, tfile, res->backup_size, req->drm_surface_flags & drm_vmw_surface_flag_shareable, &backup_handle, &res->backup, &user_srf->backup_base); if (unlikely(ret != 0)) { vmw_resource_unreference(&res); goto out_unlock; } tmp = vmw_resource_reference(res); ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime, req->drm_surface_flags & drm_vmw_surface_flag_shareable, VMW_RES_SURFACE, &vmw_user_surface_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); vmw_resource_unreference(&res); goto out_unlock; } rep->handle = user_srf->prime.base.hash.key; rep->backup_size = res->backup_size; if (res->backup) { rep->buffer_map_handle = drm_vma_node_offset_addr(&res->backup->base.vma_node); rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE; rep->buffer_handle = backup_handle; } else { rep->buffer_map_handle = 0; rep->buffer_size = 0; rep->buffer_handle = SVGA3D_INVALID_ID; } vmw_resource_unreference(&res); out_unlock: ttm_read_unlock(&dev_priv->reservation_sem); return ret; } Commit Message: drm/vmwgfx: Make sure backup_handle is always valid When vmw_gb_surface_define_ioctl() is called with an existing buffer, we end up returning an uninitialized variable in the backup_handle. The fix is to first initialize backup_handle to 0 just to be sure, and second, when a user-provided buffer is found, we will use the req->buffer_handle as the backup_handle. Cc: <stable@vger.kernel.org> Reported-by: Murray McAllister <murray.mcallister@insomniasec.com> Signed-off-by: Sinclair Yeh <syeh@vmware.com> Reviewed-by: Deepak Rawat <drawat@vmware.com> CWE ID: CWE-200
int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_surface *user_srf; struct vmw_surface *srf; struct vmw_resource *res; struct vmw_resource *tmp; union drm_vmw_gb_surface_create_arg *arg = (union drm_vmw_gb_surface_create_arg *)data; struct drm_vmw_gb_surface_create_req *req = &arg->req; struct drm_vmw_gb_surface_create_rep *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret; uint32_t size; uint32_t backup_handle = 0; if (req->multisample_count != 0) return -EINVAL; if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS) return -EINVAL; if (unlikely(vmw_user_surface_size == 0)) vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) + 128; size = vmw_user_surface_size + 128; /* Define a surface based on the parameters. */ ret = vmw_surface_gb_priv_define(dev, size, req->svga3d_flags, req->format, req->drm_surface_flags & drm_vmw_surface_flag_scanout, req->mip_levels, req->multisample_count, req->array_size, req->base_size, &srf); if (unlikely(ret != 0)) return ret; user_srf = container_of(srf, struct vmw_user_surface, srf); if (drm_is_primary_client(file_priv)) user_srf->master = drm_master_get(file_priv->master); ret = ttm_read_lock(&dev_priv->reservation_sem, true); if (unlikely(ret != 0)) return ret; res = &user_srf->srf.res; if (req->buffer_handle != SVGA3D_INVALID_ID) { ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle, &res->backup, &user_srf->backup_base); if (ret == 0) { if (res->backup->base.num_pages * PAGE_SIZE < res->backup_size) { DRM_ERROR("Surface backup buffer is too small.\n"); vmw_dmabuf_unreference(&res->backup); ret = -EINVAL; goto out_unlock; } else { backup_handle = req->buffer_handle; } } } else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer) ret = vmw_user_dmabuf_alloc(dev_priv, tfile, res->backup_size, req->drm_surface_flags & drm_vmw_surface_flag_shareable, &backup_handle, &res->backup, &user_srf->backup_base); if (unlikely(ret != 0)) { vmw_resource_unreference(&res); goto out_unlock; } tmp = vmw_resource_reference(res); ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime, req->drm_surface_flags & drm_vmw_surface_flag_shareable, VMW_RES_SURFACE, &vmw_user_surface_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); vmw_resource_unreference(&res); goto out_unlock; } rep->handle = user_srf->prime.base.hash.key; rep->backup_size = res->backup_size; if (res->backup) { rep->buffer_map_handle = drm_vma_node_offset_addr(&res->backup->base.vma_node); rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE; rep->buffer_handle = backup_handle; } else { rep->buffer_map_handle = 0; rep->buffer_size = 0; rep->buffer_handle = SVGA3D_INVALID_ID; } vmw_resource_unreference(&res); out_unlock: ttm_read_unlock(&dev_priv->reservation_sem); return ret; }
168,093
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DeviceTokenFetcher::StopAutoRetry() { scheduler_->CancelDelayedWork(); backend_.reset(); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void DeviceTokenFetcher::StopAutoRetry() { void DeviceTokenFetcher::Reset() { SetState(STATE_INACTIVE); }
170,285
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfsd_cross_mnt(struct svc_rqst *rqstp, struct dentry **dpp, struct svc_export **expp) { struct svc_export *exp = *expp, *exp2 = NULL; struct dentry *dentry = *dpp; struct path path = {.mnt = mntget(exp->ex_path.mnt), .dentry = dget(dentry)}; int err = 0; err = follow_down(&path); if (err < 0) goto out; exp2 = rqst_exp_get_by_name(rqstp, &path); if (IS_ERR(exp2)) { err = PTR_ERR(exp2); /* * We normally allow NFS clients to continue * "underneath" a mountpoint that is not exported. * The exception is V4ROOT, where no traversal is ever * allowed without an explicit export of the new * directory. */ if (err == -ENOENT && !(exp->ex_flags & NFSEXP_V4ROOT)) err = 0; path_put(&path); goto out; } if (nfsd_v4client(rqstp) || (exp->ex_flags & NFSEXP_CROSSMOUNT) || EX_NOHIDE(exp2)) { /* successfully crossed mount point */ /* * This is subtle: path.dentry is *not* on path.mnt * at this point. The only reason we are safe is that * original mnt is pinned down by exp, so we should * put path *before* putting exp */ *dpp = path.dentry; path.dentry = dentry; *expp = exp2; exp2 = exp; } path_put(&path); exp_put(exp2); out: return err; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfsd_cross_mnt(struct svc_rqst *rqstp, struct dentry **dpp, struct svc_export **expp) { struct svc_export *exp = *expp, *exp2 = NULL; struct dentry *dentry = *dpp; struct path path = {.mnt = mntget(exp->ex_path.mnt), .dentry = dget(dentry)}; int err = 0; err = follow_down(&path); if (err < 0) goto out; if (path.mnt == exp->ex_path.mnt && path.dentry == dentry && nfsd_mountpoint(dentry, exp) == 2) { /* This is only a mountpoint in some other namespace */ path_put(&path); goto out; } exp2 = rqst_exp_get_by_name(rqstp, &path); if (IS_ERR(exp2)) { err = PTR_ERR(exp2); /* * We normally allow NFS clients to continue * "underneath" a mountpoint that is not exported. * The exception is V4ROOT, where no traversal is ever * allowed without an explicit export of the new * directory. */ if (err == -ENOENT && !(exp->ex_flags & NFSEXP_V4ROOT)) err = 0; path_put(&path); goto out; } if (nfsd_v4client(rqstp) || (exp->ex_flags & NFSEXP_CROSSMOUNT) || EX_NOHIDE(exp2)) { /* successfully crossed mount point */ /* * This is subtle: path.dentry is *not* on path.mnt * at this point. The only reason we are safe is that * original mnt is pinned down by exp, so we should * put path *before* putting exp */ *dpp = path.dentry; path.dentry = dentry; *expp = exp2; exp2 = exp; } path_put(&path); exp_put(exp2); out: return err; }
168,153
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Metadata* EntrySync::getMetadata(ExceptionState& exceptionState) { RefPtr<MetadataSyncCallbackHelper> helper = MetadataSyncCallbackHelper::create(); m_fileSystem->getMetadata(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return helper->getResult(exceptionState); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
Metadata* EntrySync::getMetadata(ExceptionState& exceptionState) { MetadataSyncCallbackHelper* helper = MetadataSyncCallbackHelper::create(); m_fileSystem->getMetadata(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return helper->getResult(exceptionState); }
171,421
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool TradQT_Manager::ParseCachedBoxes ( const MOOV_Manager & moovMgr ) { MOOV_Manager::BoxInfo udtaInfo; MOOV_Manager::BoxRef udtaRef = moovMgr.GetBox ( "moov/udta", &udtaInfo ); if ( udtaRef == 0 ) return false; for ( XMP_Uns32 i = 0; i < udtaInfo.childCount; ++i ) { MOOV_Manager::BoxInfo currInfo; MOOV_Manager::BoxRef currRef = moovMgr.GetNthChild ( udtaRef, i, &currInfo ); if ( currRef == 0 ) break; // Sanity check, should not happen. if ( (currInfo.boxType >> 24) != 0xA9 ) continue; if ( currInfo.contentSize < 2+2+1 ) continue; // Want enough for a non-empty value. InfoMapPos newInfo = this->parsedBoxes.insert ( this->parsedBoxes.end(), InfoMap::value_type ( currInfo.boxType, ParsedBoxInfo ( currInfo.boxType ) ) ); std::vector<ValueInfo> * newValues = &newInfo->second.values; XMP_Uns8 * boxPtr = (XMP_Uns8*) currInfo.content; XMP_Uns8 * boxEnd = boxPtr + currInfo.contentSize; XMP_Uns16 miniLen, macLang; for ( ; boxPtr < boxEnd-4; boxPtr += miniLen ) { miniLen = 4 + GetUns16BE ( boxPtr ); // ! Include header in local miniLen. macLang = GetUns16BE ( boxPtr+2); if ( (miniLen <= 4) || (miniLen > (boxEnd - boxPtr)) ) continue; // Ignore bad or empty values. XMP_StringPtr valuePtr = (char*)(boxPtr+4); size_t valueLen = miniLen - 4; newValues->push_back ( ValueInfo() ); ValueInfo * newValue = &newValues->back(); newValue->macLang = macLang; if ( IsMacLangKnown ( macLang ) ) newValue->xmpLang = GetXMPLang ( macLang ); newValue->macValue.assign ( valuePtr, valueLen ); } } return (! this->parsedBoxes.empty()); } // TradQT_Manager::ParseCachedBoxes Commit Message: CWE ID: CWE-835
bool TradQT_Manager::ParseCachedBoxes ( const MOOV_Manager & moovMgr ) { MOOV_Manager::BoxInfo udtaInfo; MOOV_Manager::BoxRef udtaRef = moovMgr.GetBox ( "moov/udta", &udtaInfo ); if ( udtaRef == 0 ) return false; for ( XMP_Uns32 i = 0; i < udtaInfo.childCount; ++i ) { MOOV_Manager::BoxInfo currInfo; MOOV_Manager::BoxRef currRef = moovMgr.GetNthChild ( udtaRef, i, &currInfo ); if ( currRef == 0 ) break; // Sanity check, should not happen. if ( (currInfo.boxType >> 24) != 0xA9 ) continue; if ( currInfo.contentSize < 2+2+1 ) continue; // Want enough for a non-empty value. InfoMapPos newInfo = this->parsedBoxes.insert ( this->parsedBoxes.end(), InfoMap::value_type ( currInfo.boxType, ParsedBoxInfo ( currInfo.boxType ) ) ); std::vector<ValueInfo> * newValues = &newInfo->second.values; XMP_Uns8 * boxPtr = (XMP_Uns8*) currInfo.content; XMP_Uns8 * boxEnd = boxPtr + currInfo.contentSize; XMP_Uns16 miniLen, macLang; for ( ; boxPtr < boxEnd-4; boxPtr += miniLen ) { miniLen = 4 + GetUns16BE ( boxPtr ); // ! Include header in local miniLen. macLang = GetUns16BE ( boxPtr+2); if ( (miniLen <= 4) || (miniLen > (boxEnd - boxPtr)) ) break; // Ignore bad or empty values. XMP_StringPtr valuePtr = (char*)(boxPtr+4); size_t valueLen = miniLen - 4; newValues->push_back ( ValueInfo() ); ValueInfo * newValue = &newValues->back(); newValue->macLang = macLang; if ( IsMacLangKnown ( macLang ) ) newValue->xmpLang = GetXMPLang ( macLang ); newValue->macValue.assign ( valuePtr, valueLen ); } } return (! this->parsedBoxes.empty()); } // TradQT_Manager::ParseCachedBoxes
165,364
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst) { if (src == NULL || src_len == 0 || dst == NULL) { return; } const char16_t* cur_utf16 = src; const char16_t* const end_utf16 = src + src_len; char *cur = dst; while (cur_utf16 < end_utf16) { char32_t utf32; if((*cur_utf16 & 0xFC00) == 0xD800 && (cur_utf16 + 1) < end_utf16 && (*(cur_utf16 + 1) & 0xFC00) == 0xDC00) { utf32 = (*cur_utf16++ - 0xD800) << 10; utf32 |= *cur_utf16++ - 0xDC00; utf32 += 0x10000; } else { utf32 = (char32_t) *cur_utf16++; } const size_t len = utf32_codepoint_utf8_length(utf32); utf32_codepoint_to_utf8((uint8_t*)cur, utf32, len); cur += len; } *cur = '\0'; } Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8 Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length is causing a heap overflow. Correcting the length computation and adding bound checks to the conversion functions. Test: ran libutils_tests Bug: 29250543 Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb (cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1) CWE ID: CWE-119
void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst) void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst, size_t dst_len) { if (src == NULL || src_len == 0 || dst == NULL) { return; } const char16_t* cur_utf16 = src; const char16_t* const end_utf16 = src + src_len; char *cur = dst; while (cur_utf16 < end_utf16) { char32_t utf32; if((*cur_utf16 & 0xFC00) == 0xD800 && (cur_utf16 + 1) < end_utf16 && (*(cur_utf16 + 1) & 0xFC00) == 0xDC00) { utf32 = (*cur_utf16++ - 0xD800) << 10; utf32 |= *cur_utf16++ - 0xDC00; utf32 += 0x10000; } else { utf32 = (char32_t) *cur_utf16++; } const size_t len = utf32_codepoint_utf8_length(utf32); LOG_ALWAYS_FATAL_IF(dst_len < len, "%zu < %zu", dst_len, len); utf32_codepoint_to_utf8((uint8_t*)cur, utf32, len); cur += len; dst_len -= len; } LOG_ALWAYS_FATAL_IF(dst_len < 1, "%zu < 1", dst_len); *cur = '\0'; }
173,419
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScreenLockLibrary* CrosLibrary::GetScreenLockLibrary() { return screen_lock_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
ScreenLockLibrary* CrosLibrary::GetScreenLockLibrary() {
170,629
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; /* We don't support symlinks longer than one block */ if (inode->i_size > inode->i_sb->s_blocksize) { err = -ENAMETOOLONG; goto out_unmap; } iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) { err = -EIO; goto out_unlock_inode; } symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out_unlock_inode: up_read(&iinfo->i_data_sem); SetPageError(page); out_unmap: kunmap(page); unlock_page(page); return err; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: stable@vger.kernel.org Reported-by: Carl Henrik Lunde <chlunde@ping.uio.no> Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-17
static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; /* We don't support symlinks longer than one block */ if (inode->i_size > inode->i_sb->s_blocksize) { err = -ENAMETOOLONG; goto out_unmap; } iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) { err = -EIO; goto out_unlock_inode; } symlink = bh->b_data; } err = udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p, PAGE_SIZE); brelse(bh); if (err) goto out_unlock_inode; up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out_unlock_inode: up_read(&iinfo->i_data_sem); SetPageError(page); out_unmap: kunmap(page); unlock_page(page); return err; }
166,758
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int prepare_binprm(struct linux_binprm *bprm) { struct inode *inode = file_inode(bprm->file); umode_t mode = inode->i_mode; int retval; /* clear any previous set[ug]id data from a previous binary */ bprm->cred->euid = current_euid(); bprm->cred->egid = current_egid(); if (!(bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) && !task_no_new_privs(current) && kuid_has_mapping(bprm->cred->user_ns, inode->i_uid) && kgid_has_mapping(bprm->cred->user_ns, inode->i_gid)) { /* Set-uid? */ if (mode & S_ISUID) { bprm->per_clear |= PER_CLEAR_ON_SETID; bprm->cred->euid = inode->i_uid; } /* Set-gid? */ /* * If setgid is set but no group execute bit then this * is a candidate for mandatory locking, not a setgid * executable. */ if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) { bprm->per_clear |= PER_CLEAR_ON_SETID; bprm->cred->egid = inode->i_gid; } } /* fill in binprm security blob */ retval = security_bprm_set_creds(bprm); if (retval) return retval; bprm->cred_prepared = 1; memset(bprm->buf, 0, BINPRM_BUF_SIZE); return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE); } Commit Message: fs: take i_mutex during prepare_binprm for set[ug]id executables This prevents a race between chown() and execve(), where chowning a setuid-user binary to root would momentarily make the binary setuid root. This patch was mostly written by Linus Torvalds. Signed-off-by: Jann Horn <jann@thejh.net> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-362
int prepare_binprm(struct linux_binprm *bprm) { int retval; bprm_fill_uid(bprm); /* fill in binprm security blob */ retval = security_bprm_set_creds(bprm); if (retval) return retval; bprm->cred_prepared = 1; memset(bprm->buf, 0, BINPRM_BUF_SIZE); return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE); }
166,625
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_zalloc(voidpf png_ptr, uInt items, uInt size) { png_voidp ptr; png_structp p=(png_structp)png_ptr; png_uint_32 save_flags=p->flags; png_uint_32 num_bytes; if (png_ptr == NULL) return (NULL); if (items > PNG_UINT_32_MAX/size) { png_warning (p, "Potential overflow in png_zalloc()"); return (NULL); } num_bytes = (png_uint_32)items * size; p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK; ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes); p->flags=save_flags; #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO) if (ptr == NULL) return ((voidpf)ptr); if (num_bytes > (png_uint_32)0x8000L) { png_memset(ptr, 0, (png_size_t)0x8000L); png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0, (png_size_t)(num_bytes - (png_uint_32)0x8000L)); } else { png_memset(ptr, 0, (png_size_t)num_bytes); } #endif return ((voidpf)ptr); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_zalloc(voidpf png_ptr, uInt items, uInt size) { png_voidp ptr; png_structp p; png_uint_32 save_flags; png_uint_32 num_bytes; if (png_ptr == NULL) return (NULL); p=(png_structp)png_ptr; save_flags=p->flags; if (items > PNG_UINT_32_MAX/size) { png_warning (p, "Potential overflow in png_zalloc()"); return (NULL); } num_bytes = (png_uint_32)items * size; p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK; ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes); p->flags=save_flags; #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO) if (ptr == NULL) return ((voidpf)ptr); if (num_bytes > (png_uint_32)0x8000L) { png_memset(ptr, 0, (png_size_t)0x8000L); png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0, (png_size_t)(num_bytes - (png_uint_32)0x8000L)); } else { png_memset(ptr, 0, (png_size_t)num_bytes); } #endif return ((voidpf)ptr); }
172,164
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, unsigned long data_len, int noblock, int *errcode) { struct sk_buff *skb; gfp_t gfp_mask; long timeo; int err; gfp_mask = sk->sk_allocation; if (gfp_mask & __GFP_WAIT) gfp_mask |= __GFP_REPEAT; timeo = sock_sndtimeo(sk, noblock); while (1) { err = sock_error(sk); if (err != 0) goto failure; err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) goto failure; if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { skb = alloc_skb(header_len, gfp_mask); if (skb) { int npages; int i; /* No pages, we're done... */ if (!data_len) break; npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT; skb->truesize += data_len; skb_shinfo(skb)->nr_frags = npages; for (i = 0; i < npages; i++) { struct page *page; page = alloc_pages(sk->sk_allocation, 0); if (!page) { err = -ENOBUFS; skb_shinfo(skb)->nr_frags = i; kfree_skb(skb); goto failure; } __skb_fill_page_desc(skb, i, page, 0, (data_len >= PAGE_SIZE ? PAGE_SIZE : data_len)); data_len -= PAGE_SIZE; } /* Full success... */ break; } err = -ENOBUFS; goto failure; } set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); err = -EAGAIN; if (!timeo) goto failure; if (signal_pending(current)) goto interrupted; timeo = sock_wait_for_wmem(sk, timeo); } skb_set_owner_w(skb, sk); return skb; interrupted: err = sock_intr_errno(timeo); failure: *errcode = err; return NULL; } Commit Message: net: sock: validate data_len before allocating skb in sock_alloc_send_pskb() We need to validate the number of pages consumed by data_len, otherwise frags array could be overflowed by userspace. So this patch validate data_len and return -EMSGSIZE when data_len may occupies more frags than MAX_SKB_FRAGS. Signed-off-by: Jason Wang <jasowang@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, unsigned long data_len, int noblock, int *errcode) { struct sk_buff *skb; gfp_t gfp_mask; long timeo; int err; int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT; err = -EMSGSIZE; if (npages > MAX_SKB_FRAGS) goto failure; gfp_mask = sk->sk_allocation; if (gfp_mask & __GFP_WAIT) gfp_mask |= __GFP_REPEAT; timeo = sock_sndtimeo(sk, noblock); while (1) { err = sock_error(sk); if (err != 0) goto failure; err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) goto failure; if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { skb = alloc_skb(header_len, gfp_mask); if (skb) { int i; /* No pages, we're done... */ if (!data_len) break; skb->truesize += data_len; skb_shinfo(skb)->nr_frags = npages; for (i = 0; i < npages; i++) { struct page *page; page = alloc_pages(sk->sk_allocation, 0); if (!page) { err = -ENOBUFS; skb_shinfo(skb)->nr_frags = i; kfree_skb(skb); goto failure; } __skb_fill_page_desc(skb, i, page, 0, (data_len >= PAGE_SIZE ? PAGE_SIZE : data_len)); data_len -= PAGE_SIZE; } /* Full success... */ break; } err = -ENOBUFS; goto failure; } set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); err = -EAGAIN; if (!timeo) goto failure; if (signal_pending(current)) goto interrupted; timeo = sock_wait_for_wmem(sk, timeo); } skb_set_owner_w(skb, sk); return skb; interrupted: err = sock_intr_errno(timeo); failure: *errcode = err; return NULL; }
165,602
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MidiManagerUsb::DispatchSendMidiData(MidiManagerClient* client, uint32_t port_index, const std::vector<uint8>& data, double timestamp) { DCHECK_LT(port_index, output_streams_.size()); output_streams_[port_index]->Send(data); client->AccumulateMidiBytesSent(data.size()); } Commit Message: MidiManagerUsb should not trust indices provided by renderer. MidiManagerUsb::DispatchSendMidiData takes |port_index| parameter. As it is provided by a renderer possibly under the control of an attacker, we must validate the given index before using it. BUG=456516 Review URL: https://codereview.chromium.org/907793002 Cr-Commit-Position: refs/heads/master@{#315303} CWE ID: CWE-119
void MidiManagerUsb::DispatchSendMidiData(MidiManagerClient* client, uint32_t port_index, const std::vector<uint8>& data, double timestamp) { if (port_index >= output_streams_.size()) { // |port_index| is provided by a renderer so we can't believe that it is // in the valid range. // TODO(toyoshim): Move this check to MidiHost and kill the renderer when // it fails. return; } output_streams_[port_index]->Send(data); client->AccumulateMidiBytesSent(data.size()); }
172,014
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static jboolean enableNative(JNIEnv* env, jobject obj) { ALOGV("%s:",__FUNCTION__); jboolean result = JNI_FALSE; if (!sBluetoothInterface) return result; int ret = sBluetoothInterface->enable(); result = (ret == BT_STATUS_SUCCESS || ret == BT_STATUS_DONE) ? JNI_TRUE : JNI_FALSE; return result; } Commit Message: Add guest mode functionality (3/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: If4a8855faf362d7f6de509d7ddc7197d1ac75cee CWE ID: CWE-20
static jboolean enableNative(JNIEnv* env, jobject obj) { static jboolean enableNative(JNIEnv* env, jobject obj, jboolean isGuest) { ALOGV("%s:",__FUNCTION__); jboolean result = JNI_FALSE; if (!sBluetoothInterface) return result; int ret = sBluetoothInterface->enable(isGuest == JNI_TRUE ? 1 : 0); result = (ret == BT_STATUS_SUCCESS || ret == BT_STATUS_DONE) ? JNI_TRUE : JNI_FALSE; return result; }
174,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, createDefaultStub) { char *index = NULL, *webindex = NULL, *error; zend_string *stub; size_t index_len = 0, webindex_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|ss", &index, &index_len, &webindex, &webindex_len) == FAILURE) { return; } stub = phar_create_default_stub(index, webindex, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); return; } RETURN_NEW_STR(stub); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, createDefaultStub) { char *index = NULL, *webindex = NULL, *error; zend_string *stub; size_t index_len = 0, webindex_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|pp", &index, &index_len, &webindex, &webindex_len) == FAILURE) { return; } stub = phar_create_default_stub(index, webindex, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); return; } RETURN_NEW_STR(stub); }
165,057
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info, Image *images,const char *filename,ExceptionInfo *exception) { #define WriteImageTag "Write/Image" ExceptionInfo *sans_exception; ImageInfo *write_info; MagickBooleanType proceed; MagickOffsetType progress; MagickProgressMonitor progress_monitor; MagickSizeType number_images; MagickStatusType status; register Image *p; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); write_info=CloneImageInfo(image_info); *write_info->magick='\0'; images=GetFirstImageInList(images); if (filename != (const char *) NULL) for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) (void) CopyMagickString(p->filename,filename,MagickPathExtent); (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent); sans_exception=AcquireExceptionInfo(); (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images), sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (*write_info->magick == '\0') (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent); p=images; for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p)) if (p->scene >= GetNextImageInList(p)->scene) { register ssize_t i; /* Generate consistent scene numbers. */ i=(ssize_t) images->scene; for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) p->scene=(size_t) i++; break; } /* Write images. */ status=MagickTrue; progress_monitor=(MagickProgressMonitor) NULL; progress=0; number_images=GetImageListLength(images); for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) { if (number_images != 1) progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL, p->client_data); status&=WriteImage(write_info,p,exception); if (number_images != 1) (void) SetImageProgressMonitor(p,progress_monitor,p->client_data); if (write_info->adjoin != MagickFalse) break; if (number_images != 1) { proceed=SetImageProgress(p,WriteImageTag,progress++,number_images); if (proceed == MagickFalse) break; } } write_info=DestroyImageInfo(write_info); return(status != 0 ? MagickTrue : MagickFalse); } Commit Message: https://github.com/ImageMagick/ImageMagick/pull/34 CWE ID: CWE-476
MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info, Image *images,const char *filename,ExceptionInfo *exception) { #define WriteImageTag "Write/Image" ExceptionInfo *sans_exception; ImageInfo *write_info; MagickBooleanType proceed; MagickOffsetType progress; MagickProgressMonitor progress_monitor; MagickSizeType number_images; MagickStatusType status; register Image *p; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); write_info=CloneImageInfo(image_info); *write_info->magick='\0'; images=GetFirstImageInList(images); if (filename != (const char *) NULL) for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) (void) CopyMagickString(p->filename,filename,MagickPathExtent); (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent); sans_exception=AcquireExceptionInfo(); (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images), sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (*write_info->magick == '\0') (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent); p=images; for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p)) { register Image *next; next=GetNextImageInList(p); if (next == (Image *) NULL) break; if (p->scene >= next->scene) { register ssize_t i; /* Generate consistent scene numbers. */ i=(ssize_t) images->scene; for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) p->scene=(size_t) i++; break; } } /* Write images. */ status=MagickTrue; progress_monitor=(MagickProgressMonitor) NULL; progress=0; number_images=GetImageListLength(images); for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) { if (number_images != 1) progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL, p->client_data); status&=WriteImage(write_info,p,exception); if (number_images != 1) (void) SetImageProgressMonitor(p,progress_monitor,p->client_data); if (write_info->adjoin != MagickFalse) break; if (number_images != 1) { proceed=SetImageProgress(p,WriteImageTag,progress++,number_images); if (proceed == MagickFalse) break; } } write_info=DestroyImageInfo(write_info); return(status != 0 ? MagickTrue : MagickFalse); }
168,857
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) { _cleanup_close_ int fd; int r; assert(path); if (parents) mkdir_parents(path, 0755); fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644); if (fd < 0) return -errno; if (mode > 0) { r = fchmod(fd, mode); if (r < 0) return -errno; } if (uid != UID_INVALID || gid != GID_INVALID) { r = fchown(fd, uid, gid); if (r < 0) return -errno; } if (stamp != USEC_INFINITY) { struct timespec ts[2]; timespec_store(&ts[0], stamp); ts[1] = ts[0]; r = futimens(fd, ts); } else r = futimens(fd, NULL); if (r < 0) return -errno; return 0; } Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere CWE ID: CWE-264
int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) { _cleanup_close_ int fd; int r; assert(path); if (parents) mkdir_parents(path, 0755); fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644); if (fd < 0) return -errno; if (mode != MODE_INVALID) { r = fchmod(fd, mode); if (r < 0) return -errno; } if (uid != UID_INVALID || gid != GID_INVALID) { r = fchown(fd, uid, gid); if (r < 0) return -errno; } if (stamp != USEC_INFINITY) { struct timespec ts[2]; timespec_store(&ts[0], stamp); ts[1] = ts[0]; r = futimens(fd, ts); } else r = futimens(fd, NULL); if (r < 0) return -errno; return 0; }
170,105
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Segment::~Segment() { const long count = m_clusterCount + m_clusterPreloadCount; Cluster** i = m_clusters; Cluster** j = m_clusters + count; while (i != j) { Cluster* const p = *i++; assert(p); delete p; } delete[] m_clusters; delete m_pTracks; delete m_pInfo; delete m_pCues; delete m_pChapters; delete m_pSeekHead; } 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
Segment::~Segment() assert((total < 0) || (available <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; assert((segment_stop < 0) || (total < 0) || (segment_stop <= total)); assert((segment_stop < 0) || (m_pos <= segment_stop)); for (;;) { if ((total >= 0) && (m_pos >= total)) break; if ((segment_stop >= 0) && (m_pos >= segment_stop)) break; long long pos = m_pos; const long long element_start = pos;
174,470
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SpdyWriteQueue::RemovePendingWritesForStream( const base::WeakPtr<SpdyStream>& stream) { CHECK(!removing_writes_); removing_writes_ = true; RequestPriority priority = stream->priority(); CHECK_GE(priority, MINIMUM_PRIORITY); CHECK_LE(priority, MAXIMUM_PRIORITY); DCHECK(stream.get()); #if DCHECK_IS_ON for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { if (priority == i) continue; for (std::deque<PendingWrite>::const_iterator it = queue_[i].begin(); it != queue_[i].end(); ++it) { DCHECK_NE(it->stream.get(), stream.get()); } } #endif std::deque<PendingWrite>* queue = &queue_[priority]; std::deque<PendingWrite>::iterator out_it = queue->begin(); for (std::deque<PendingWrite>::const_iterator it = queue->begin(); it != queue->end(); ++it) { if (it->stream.get() == stream.get()) { delete it->frame_producer; } else { *out_it = *it; ++out_it; } } queue->erase(out_it, queue->end()); removing_writes_ = false; } Commit Message: These can post callbacks which re-enter into SpdyWriteQueue. BUG=369539 Review URL: https://codereview.chromium.org/265933007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void SpdyWriteQueue::RemovePendingWritesForStream( const base::WeakPtr<SpdyStream>& stream) { CHECK(!removing_writes_); removing_writes_ = true; RequestPriority priority = stream->priority(); CHECK_GE(priority, MINIMUM_PRIORITY); CHECK_LE(priority, MAXIMUM_PRIORITY); DCHECK(stream.get()); #if DCHECK_IS_ON for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) { if (priority == i) continue; for (std::deque<PendingWrite>::const_iterator it = queue_[i].begin(); it != queue_[i].end(); ++it) { DCHECK_NE(it->stream.get(), stream.get()); } } #endif // Defer deletion until queue iteration is complete, as // SpdyBuffer::~SpdyBuffer() can result in callbacks into SpdyWriteQueue. std::vector<SpdyBufferProducer*> erased_buffer_producers; std::deque<PendingWrite>* queue = &queue_[priority]; std::deque<PendingWrite>::iterator out_it = queue->begin(); for (std::deque<PendingWrite>::const_iterator it = queue->begin(); it != queue->end(); ++it) { if (it->stream.get() == stream.get()) { erased_buffer_producers.push_back(it->frame_producer); } else { *out_it = *it; ++out_it; } } queue->erase(out_it, queue->end()); removing_writes_ = false; STLDeleteElements(&erased_buffer_producers); // Invokes callbacks. }
171,674
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_get_copyright(png_structp png_ptr) { PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */ #ifdef PNG_STRING_COPYRIGHT return PNG_STRING_COPYRIGHT #else #ifdef __STDC__ return ((png_charp) PNG_STRING_NEWLINE \ "libpng version 1.2.52 - November 20, 2014" PNG_STRING_NEWLINE \ "Copyright (c) 1998-2014 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \ "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \ "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \ PNG_STRING_NEWLINE); #else return ((png_charp) "libpng version 1.2.52 - November 20, 2014\ Copyright (c) 1998-2014 Glenn Randers-Pehrson\ Copyright (c) 1996-1997 Andreas Dilger\ Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc."); #endif #endif } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_copyright(png_structp png_ptr) { PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */ #ifdef PNG_STRING_COPYRIGHT return PNG_STRING_COPYRIGHT #else #ifdef __STDC__ return ((png_charp) PNG_STRING_NEWLINE \ "libpng version 1.2.54 - November 12, 2015" PNG_STRING_NEWLINE \ "Copyright (c) 1998-2015 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \ "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \ "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \ PNG_STRING_NEWLINE); #else return ((png_charp) "libpng version 1.2.54 - November 12, 2015\ Copyright (c) 1998-2015 Glenn Randers-Pehrson\ Copyright (c) 1996-1997 Andreas Dilger\ Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc."); #endif #endif }
172,162
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OnImageDecoded(const gfx::Image& decoded_image) { image_decoded_callback_.Run(decoded_image.AsBitmap()); delete this; } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <sdefresne@chromium.org> Reviewed-by: Marc Treib <treib@chromium.org> Commit-Queue: Chris Pickel <sfiera@chromium.org> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void OnImageDecoded(const gfx::Image& decoded_image) {
171,957
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *cJSON_Print( cJSON *item ) { return print_value( item, 0, 1 ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
char *cJSON_Print( cJSON *item )
167,293
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ImportCbYCrYQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 10: { Quantum cbcr[4]; pixel=0; if (quantum_info->pack == MagickFalse) { register ssize_t i; size_t quantum; ssize_t n; n=0; quantum=0; for (x=0; x < (ssize_t) number_pixels; x+=2) { for (i=0; i < 4; i++) { switch (n % 3) { case 0: { p=PushLongPixel(quantum_info->endian,p,&pixel); quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 22) & 0x3ff) << 6))); break; } case 1: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 12) & 0x3ff) << 6))); break; } case 2: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 2) & 0x3ff) << 6))); break; } } cbcr[i]=(Quantum) (quantum); n++; } p+=quantum_info->pad; SetPixelRed(image,cbcr[1],q); SetPixelGreen(image,cbcr[0],q); SetPixelBlue(image,cbcr[2],q); q+=GetPixelChannels(image); SetPixelRed(image,cbcr[3],q); SetPixelGreen(image,cbcr[0],q); SetPixelBlue(image,cbcr[2],q); q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/126 CWE ID: CWE-125
static void ImportCbYCrYQuantum(const Image *image,QuantumInfo *quantum_info, const MagickSizeType number_pixels,const unsigned char *magick_restrict p, Quantum *magick_restrict q,ExceptionInfo *exception) { QuantumAny range; register ssize_t x; unsigned int pixel; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); switch (quantum_info->depth) { case 10: { Quantum cbcr[4]; pixel=0; if (quantum_info->pack == MagickFalse) { register ssize_t i; size_t quantum; ssize_t n; n=0; quantum=0; for (x=0; x < (ssize_t) number_pixels; x+=4) { for (i=0; i < 4; i++) { switch (n % 3) { case 0: { p=PushLongPixel(quantum_info->endian,p,&pixel); quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 22) & 0x3ff) << 6))); break; } case 1: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 12) & 0x3ff) << 6))); break; } case 2: { quantum=(size_t) (ScaleShortToQuantum((unsigned short) (((pixel >> 2) & 0x3ff) << 6))); break; } } cbcr[i]=(Quantum) (quantum); n++; } p+=quantum_info->pad; SetPixelRed(image,cbcr[1],q); SetPixelGreen(image,cbcr[0],q); SetPixelBlue(image,cbcr[2],q); q+=GetPixelChannels(image); SetPixelRed(image,cbcr[3],q); SetPixelGreen(image,cbcr[0],q); SetPixelBlue(image,cbcr[2],q); q+=GetPixelChannels(image); } break; } } default: { range=GetQuantumRange(quantum_info->depth); for (x=0; x < (ssize_t) number_pixels; x++) { p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q); p=PushQuantumPixel(quantum_info,p,&pixel); SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q); q+=GetPixelChannels(image); } break; } } }
168,793
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int parse_arguments(int *argc_p, const char ***argv_p) { static poptContext pc; char *ref = lp_refuse_options(module_id); const char *arg, **argv = *argv_p; int argc = *argc_p; int opt; if (ref && *ref) set_refuse_options(ref); set_refuse_options("log-file*"); #ifdef ICONV_OPTION if (!*lp_charset(module_id)) set_refuse_options("iconv"); #endif } Commit Message: CWE ID:
int parse_arguments(int *argc_p, const char ***argv_p) { static poptContext pc; char *ref = lp_refuse_options(module_id); const char *arg, **argv = *argv_p; int argc = *argc_p; int opt; int orig_protect_args = protect_args; if (ref && *ref) set_refuse_options(ref); set_refuse_options("log-file*"); #ifdef ICONV_OPTION if (!*lp_charset(module_id)) set_refuse_options("iconv"); #endif }
165,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ConnectPanelServiceSignals() { if (!ibus_) { return; } IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (!ibus_panel_service) { LOG(ERROR) << "IBusPanelService is NOT available."; return; } g_signal_connect(ibus_panel_service, "focus-in", G_CALLBACK(FocusInCallback), this); g_signal_connect(ibus_panel_service, "register-properties", G_CALLBACK(RegisterPropertiesCallback), this); g_signal_connect(ibus_panel_service, "update-property", G_CALLBACK(UpdatePropertyCallback), this); } 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 ConnectPanelServiceSignals() { if (!ibus_) { return; } IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (!ibus_panel_service) { LOG(ERROR) << "IBusPanelService is NOT available."; return; } g_signal_connect(ibus_panel_service, "focus-in", G_CALLBACK(FocusInThunk), this); g_signal_connect(ibus_panel_service, "register-properties", G_CALLBACK(RegisterPropertiesThunk), this); g_signal_connect(ibus_panel_service, "update-property", G_CALLBACK(UpdatePropertyThunk), this); }
170,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LogoService::LogoService( const base::FilePath& cache_directory, TemplateURLService* template_url_service, std::unique_ptr<image_fetcher::ImageDecoder> image_decoder, scoped_refptr<net::URLRequestContextGetter> request_context_getter, bool use_gray_background) : cache_directory_(cache_directory), template_url_service_(template_url_service), request_context_getter_(request_context_getter), use_gray_background_(use_gray_background), image_decoder_(std::move(image_decoder)) {} Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <sdefresne@chromium.org> Reviewed-by: Marc Treib <treib@chromium.org> Commit-Queue: Chris Pickel <sfiera@chromium.org> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
LogoService::LogoService(
171,955
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ImageBitmapFactories::ImageBitmapLoader::Trace(blink::Visitor* visitor) { visitor->Trace(factory_); visitor->Trace(resolver_); visitor->Trace(options_); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Marijn Kruisselbrink <mek@chromium.org> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416
void ImageBitmapFactories::ImageBitmapLoader::Trace(blink::Visitor* visitor) { ContextLifecycleObserver::Trace(visitor); visitor->Trace(factory_); visitor->Trace(resolver_); visitor->Trace(options_); }
173,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static entity_table_opt determine_entity_table(int all, int doctype) { entity_table_opt retval = {NULL}; assert(!(doctype == ENT_HTML_DOC_XML1 && all)); if (all) { retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ? entity_ms_table_html5 : entity_ms_table_html4; } else { retval.table = (doctype == ENT_HTML_DOC_HTML401) ? stage3_table_be_noapos_00000 : stage3_table_be_apos_00000; } return retval; } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190
static entity_table_opt determine_entity_table(int all, int doctype) { entity_table_opt retval = {NULL}; assert(!(doctype == ENT_HTML_DOC_XML1 && all)); if (all) { retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ? entity_ms_table_html5 : entity_ms_table_html4; } else { retval.table = (doctype == ENT_HTML_DOC_HTML401) ? stage3_table_be_noapos_00000 : stage3_table_be_apos_00000; } return retval; }
167,170
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len, struct iovec iov[], int iov_size) { const struct vhost_memory_region *reg; struct vhost_memory *mem; struct iovec *_iov; u64 s = 0; int ret = 0; rcu_read_lock(); mem = rcu_dereference(dev->memory); while ((u64)len > s) { u64 size; if (unlikely(ret >= iov_size)) { ret = -ENOBUFS; break; } reg = find_region(mem, addr, len); if (unlikely(!reg)) { ret = -EFAULT; break; } _iov = iov + ret; size = reg->memory_size - addr + reg->guest_phys_addr; _iov->iov_len = min((u64)len, size); _iov->iov_base = (void __user *)(unsigned long) (reg->userspace_addr + addr - reg->guest_phys_addr); s += size; addr += size; ++ret; } rcu_read_unlock(); return ret; } Commit Message: vhost: fix length for cross region descriptor If a single descriptor crosses a region, the second chunk length should be decremented by size translated so far, instead it includes the full descriptor length. Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Acked-by: Jason Wang <jasowang@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len, struct iovec iov[], int iov_size) { const struct vhost_memory_region *reg; struct vhost_memory *mem; struct iovec *_iov; u64 s = 0; int ret = 0; rcu_read_lock(); mem = rcu_dereference(dev->memory); while ((u64)len > s) { u64 size; if (unlikely(ret >= iov_size)) { ret = -ENOBUFS; break; } reg = find_region(mem, addr, len); if (unlikely(!reg)) { ret = -EFAULT; break; } _iov = iov + ret; size = reg->memory_size - addr + reg->guest_phys_addr; _iov->iov_len = min((u64)len - s, size); _iov->iov_base = (void __user *)(unsigned long) (reg->userspace_addr + addr - reg->guest_phys_addr); s += size; addr += size; ++ret; } rcu_read_unlock(); return ret; }
166,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int getStrrtokenPos(char* str, int savedPos) { int result =-1; int i; for(i=savedPos-1; i>=0; i--) { if(isIDSeparator(*(str+i)) ){ /* delimiter found; check for singleton */ if(i>=2 && isIDSeparator(*(str+i-2)) ){ /* a singleton; so send the position of token before the singleton */ result = i-2; } else { result = i; } break; } } if(result < 1){ /* Just in case inavlid locale e.g. '-x-xyz' or '-sl_Latn' */ result =-1; } return result; } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static int getStrrtokenPos(char* str, int savedPos) { int result =-1; int i; for(i=savedPos-1; i>=0; i--) { if(isIDSeparator(*(str+i)) ){ /* delimiter found; check for singleton */ if(i>=2 && isIDSeparator(*(str+i-2)) ){ /* a singleton; so send the position of token before the singleton */ result = i-2; } else { result = i; } break; } } if(result < 1){ /* Just in case inavlid locale e.g. '-x-xyz' or '-sl_Latn' */ result =-1; } return result; }
167,203
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserProcessMainImpl::Shutdown() { if (state_ != STATE_STARTED) { CHECK_NE(state_, STATE_SHUTTING_DOWN); return; MessagePump::Get()->Stop(); WebContentsUnloader::GetInstance()->Shutdown(); if (process_model_ != PROCESS_MODEL_SINGLE_PROCESS) { BrowserContext::AssertNoContextsExist(); } browser_main_runner_->Shutdown(); browser_main_runner_.reset(); if (process_model_ != PROCESS_MODEL_SINGLE_PROCESS) { BrowserContext::AssertNoContextsExist(); } browser_main_runner_->Shutdown(); browser_main_runner_.reset(); exit_manager_.reset(); main_delegate_.reset(); platform_delegate_.reset(); state_ = STATE_SHUTDOWN; } BrowserProcessMain::BrowserProcessMain() {} BrowserProcessMain::~BrowserProcessMain() {} ProcessModel BrowserProcessMain::GetProcessModelOverrideFromEnv() { static bool g_initialized = false; static ProcessModel g_process_model = PROCESS_MODEL_UNDEFINED; if (g_initialized) { return g_process_model; } g_initialized = true; std::unique_ptr<base::Environment> env = base::Environment::Create(); if (IsEnvironmentOptionEnabled("SINGLE_PROCESS", env.get())) { g_process_model = PROCESS_MODEL_SINGLE_PROCESS; } else { std::string model = GetEnvironmentOption("PROCESS_MODEL", env.get()); if (!model.empty()) { if (model == "multi-process") { g_process_model = PROCESS_MODEL_MULTI_PROCESS; } else if (model == "single-process") { g_process_model = PROCESS_MODEL_SINGLE_PROCESS; } else if (model == "process-per-site-instance") { g_process_model = PROCESS_MODEL_PROCESS_PER_SITE_INSTANCE; } else if (model == "process-per-view") { g_process_model = PROCESS_MODEL_PROCESS_PER_VIEW; } else if (model == "process-per-site") { g_process_model = PROCESS_MODEL_PROCESS_PER_SITE; } else if (model == "site-per-process") { g_process_model = PROCESS_MODEL_SITE_PER_PROCESS; } else { LOG(WARNING) << "Invalid process mode: " << model; } } } return g_process_model; } BrowserProcessMain* BrowserProcessMain::GetInstance() { static BrowserProcessMainImpl g_instance; return &g_instance; } } // namespace oxide Commit Message: CWE ID: CWE-20
void BrowserProcessMainImpl::Shutdown() { if (state_ != STATE_STARTED) { CHECK_NE(state_, STATE_SHUTTING_DOWN); return; MessagePump::Get()->Stop(); browser_main_runner_->Shutdown(); browser_main_runner_.reset(); if (process_model_ != PROCESS_MODEL_SINGLE_PROCESS) { BrowserContext::AssertNoContextsExist(); } browser_main_runner_->Shutdown(); browser_main_runner_.reset(); exit_manager_.reset(); main_delegate_.reset(); platform_delegate_.reset(); state_ = STATE_SHUTDOWN; } BrowserProcessMain::BrowserProcessMain() {} BrowserProcessMain::~BrowserProcessMain() {} ProcessModel BrowserProcessMain::GetProcessModelOverrideFromEnv() { static bool g_initialized = false; static ProcessModel g_process_model = PROCESS_MODEL_UNDEFINED; if (g_initialized) { return g_process_model; } g_initialized = true; std::unique_ptr<base::Environment> env = base::Environment::Create(); if (IsEnvironmentOptionEnabled("SINGLE_PROCESS", env.get())) { g_process_model = PROCESS_MODEL_SINGLE_PROCESS; } else { std::string model = GetEnvironmentOption("PROCESS_MODEL", env.get()); if (!model.empty()) { if (model == "multi-process") { g_process_model = PROCESS_MODEL_MULTI_PROCESS; } else if (model == "single-process") { g_process_model = PROCESS_MODEL_SINGLE_PROCESS; } else if (model == "process-per-site-instance") { g_process_model = PROCESS_MODEL_PROCESS_PER_SITE_INSTANCE; } else if (model == "process-per-view") { g_process_model = PROCESS_MODEL_PROCESS_PER_VIEW; } else if (model == "process-per-site") { g_process_model = PROCESS_MODEL_PROCESS_PER_SITE; } else if (model == "site-per-process") { g_process_model = PROCESS_MODEL_SITE_PER_PROCESS; } else { LOG(WARNING) << "Invalid process mode: " << model; } } } return g_process_model; } BrowserProcessMain* BrowserProcessMain::GetInstance() { static BrowserProcessMainImpl g_instance; return &g_instance; } } // namespace oxide
165,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void tv_details_row_activated( GtkTreeView *tree_view, GtkTreePath *tree_path_UNUSED, GtkTreeViewColumn *column, gpointer user_data) { gchar *item_name; struct problem_item *item = get_current_problem_item_or_NULL(tree_view, &item_name); if (!item || !(item->flags & CD_FLAG_TXT)) goto ret; if (!strchr(item->content, '\n')) /* one line? */ goto ret; /* yes */ gint exitcode; gchar *arg[3]; arg[0] = (char *) "xdg-open"; arg[1] = concat_path_file(g_dump_dir_name, item_name); arg[2] = NULL; const gboolean spawn_ret = g_spawn_sync(NULL, arg, NULL, G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL, NULL, NULL, NULL, NULL, &exitcode, NULL); if (spawn_ret == FALSE || exitcode != EXIT_SUCCESS) { GtkWidget *dialog = gtk_dialog_new_with_buttons(_("View/edit a text file"), GTK_WINDOW(g_wnd_assistant), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, NULL, NULL); GtkWidget *vbox = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); GtkWidget *scrolled = gtk_scrolled_window_new(NULL, NULL); GtkWidget *textview = gtk_text_view_new(); gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Save"), GTK_RESPONSE_OK); gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Cancel"), GTK_RESPONSE_CANCEL); gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 0); gtk_widget_set_size_request(scrolled, 640, 480); gtk_widget_show(scrolled); #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 7) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 7 && GTK_MICRO_VERSION < 8)) /* http://developer.gnome.org/gtk3/unstable/GtkScrolledWindow.html#gtk-scrolled-window-add-with-viewport */ /* gtk_scrolled_window_add_with_viewport has been deprecated since version 3.8 and should not be used in newly-written code. */ gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled), textview); #else /* gtk_container_add() will now automatically add a GtkViewport if the child doesn't implement GtkScrollable. */ gtk_container_add(GTK_CONTAINER(scrolled), textview); #endif gtk_widget_show(textview); load_text_to_text_view(GTK_TEXT_VIEW(textview), item_name); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) save_text_from_text_view(GTK_TEXT_VIEW(textview), item_name); gtk_widget_destroy(textview); gtk_widget_destroy(scrolled); gtk_widget_destroy(dialog); } free(arg[1]); ret: g_free(item_name); } Commit Message: wizard: fix save users changes after reviewing dump dir files If the user reviewed the dump dir's files during reporting the crash, the changes was thrown away and original data was passed to the bugzilla bug report. report-gtk saves the first text view buffer and then reloads data from the reported problem directory, which causes that the changes made to those text views are thrown away. Function save_text_if_changed(), except of saving text, also reload the files from dump dir and update gui state from the dump dir. The commit moves the reloading and updating gui functions away from this function. Related to rhbz#1270235 Signed-off-by: Matej Habrnal <mhabrnal@redhat.com> CWE ID: CWE-200
static void tv_details_row_activated( GtkTreeView *tree_view, GtkTreePath *tree_path_UNUSED, GtkTreeViewColumn *column, gpointer user_data) { gchar *item_name; struct problem_item *item = get_current_problem_item_or_NULL(tree_view, &item_name); if (!item || !(item->flags & CD_FLAG_TXT)) goto ret; if (!strchr(item->content, '\n')) /* one line? */ goto ret; /* yes */ gint exitcode; gchar *arg[3]; arg[0] = (char *) "xdg-open"; arg[1] = concat_path_file(g_dump_dir_name, item_name); arg[2] = NULL; const gboolean spawn_ret = g_spawn_sync(NULL, arg, NULL, G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL, NULL, NULL, NULL, NULL, &exitcode, NULL); if (spawn_ret == FALSE || exitcode != EXIT_SUCCESS) { GtkWidget *dialog = gtk_dialog_new_with_buttons(_("View/edit a text file"), GTK_WINDOW(g_wnd_assistant), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, NULL, NULL); GtkWidget *vbox = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); GtkWidget *scrolled = gtk_scrolled_window_new(NULL, NULL); GtkWidget *textview = gtk_text_view_new(); gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Save"), GTK_RESPONSE_OK); gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Cancel"), GTK_RESPONSE_CANCEL); gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 0); gtk_widget_set_size_request(scrolled, 640, 480); gtk_widget_show(scrolled); #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 7) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 7 && GTK_MICRO_VERSION < 8)) /* http://developer.gnome.org/gtk3/unstable/GtkScrolledWindow.html#gtk-scrolled-window-add-with-viewport */ /* gtk_scrolled_window_add_with_viewport has been deprecated since version 3.8 and should not be used in newly-written code. */ gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled), textview); #else /* gtk_container_add() will now automatically add a GtkViewport if the child doesn't implement GtkScrollable. */ gtk_container_add(GTK_CONTAINER(scrolled), textview); #endif gtk_widget_show(textview); load_text_to_text_view(GTK_TEXT_VIEW(textview), item_name); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) { save_text_from_text_view(GTK_TEXT_VIEW(textview), item_name); problem_data_reload_from_dump_dir(); update_gui_state_from_problem_data(/* don't update selected event */ 0); } gtk_widget_destroy(textview); gtk_widget_destroy(scrolled); gtk_widget_destroy(dialog); } free(arg[1]); ret: g_free(item_name); }
166,603
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed 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; 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); } } } Commit Message: Sonivox: add SafetyNet log. Bug: 26366256 Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0 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"); android_errorWriteLog(0x534e4554, "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); } } }
174,604
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: buffer_add_range(int fd, struct evbuffer *evb, struct range *range) { char buf[BUFSIZ]; size_t n, range_sz; ssize_t nread; if (lseek(fd, range->start, SEEK_SET) == -1) return (0); range_sz = range->end - range->start + 1; while (range_sz) { n = MINIMUM(range_sz, sizeof(buf)); if ((nread = read(fd, buf, n)) == -1) return (0); evbuffer_add(evb, buf, nread); range_sz -= nread; } return (1); } Commit Message: Reimplement httpd's support for byte ranges. The previous implementation loaded all the output into a single output buffer and used its size to determine the Content-Length of the body. The new implementation calculates the body length first and writes the individual ranges in an async way using the bufferevent mechanism. This prevents httpd from using too much memory and applies the watermark and throttling mechanisms to range requests. Problem reported by Pierre Kim (pierre.kim.sec at gmail.com) OK benno@ sunil@ CWE ID: CWE-770
buffer_add_range(int fd, struct evbuffer *evb, struct range *range)
168,375
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void timer_enter_running(Timer *t) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; int r; assert(t); /* Don't start job if we are supposed to go down */ if (unit_stop_pending(UNIT(t))) return; r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)), JOB_REPLACE, true, &error, NULL); if (r < 0) goto fail; dual_timestamp_get(&t->last_trigger); if (t->stamp_path) touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, 0); timer_set_state(t, TIMER_RUNNING); return; fail: log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r)); timer_enter_dead(t, TIMER_FAILURE_RESOURCES); } Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere CWE ID: CWE-264
static void timer_enter_running(Timer *t) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; int r; assert(t); /* Don't start job if we are supposed to go down */ if (unit_stop_pending(UNIT(t))) return; r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)), JOB_REPLACE, true, &error, NULL); if (r < 0) goto fail; dual_timestamp_get(&t->last_trigger); if (t->stamp_path) touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID); timer_set_state(t, TIMER_RUNNING); return; fail: log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r)); timer_enter_dead(t, TIMER_FAILURE_RESOURCES); }
170,106
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int blk_rq_map_user_iov(struct request_queue *q, struct request *rq, struct rq_map_data *map_data, const struct iov_iter *iter, gfp_t gfp_mask) { bool copy = false; unsigned long align = q->dma_pad_mask | queue_dma_alignment(q); struct bio *bio = NULL; struct iov_iter i; int ret; if (map_data) copy = true; else if (iov_iter_alignment(iter) & align) copy = true; else if (queue_virt_boundary(q)) copy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter); i = *iter; do { ret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy); if (ret) goto unmap_rq; if (!bio) bio = rq->bio; } while (iov_iter_count(&i)); if (!bio_flagged(bio, BIO_USER_MAPPED)) rq->cmd_flags |= REQ_COPY_USER; return 0; unmap_rq: __blk_rq_unmap_user(bio); rq->bio = NULL; return -EINVAL; } Commit Message: Don't feed anything but regular iovec's to blk_rq_map_user_iov In theory we could map other things, but there's a reason that function is called "user_iov". Using anything else (like splice can do) just confuses it. Reported-and-tested-by: Johannes Thumshirn <jthumshirn@suse.de> Cc: Al Viro <viro@ZenIV.linux.org.uk> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-416
int blk_rq_map_user_iov(struct request_queue *q, struct request *rq, struct rq_map_data *map_data, const struct iov_iter *iter, gfp_t gfp_mask) { bool copy = false; unsigned long align = q->dma_pad_mask | queue_dma_alignment(q); struct bio *bio = NULL; struct iov_iter i; int ret; if (!iter_is_iovec(iter)) goto fail; if (map_data) copy = true; else if (iov_iter_alignment(iter) & align) copy = true; else if (queue_virt_boundary(q)) copy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter); i = *iter; do { ret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy); if (ret) goto unmap_rq; if (!bio) bio = rq->bio; } while (iov_iter_count(&i)); if (!bio_flagged(bio, BIO_USER_MAPPED)) rq->cmd_flags |= REQ_COPY_USER; return 0; unmap_rq: __blk_rq_unmap_user(bio); fail: rq->bio = NULL; return -EINVAL; }
166,858
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; VpxVideoReader *reader = NULL; const VpxVideoInfo *info = NULL; const VpxInterface *decoder = NULL; exec_name = argv[0]; if (argc != 3) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing.", argv[2]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->interface())); if (vpx_codec_dec_init(&codec, decoder->interface(), NULL, 0)) die_codec(&codec, "Failed to initialize decoder"); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0)) die_codec(&codec, "Failed to decode frame"); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) { unsigned char digest[16]; get_image_md5(img, digest); print_md5(outfile, digest); fprintf(outfile, " img-%dx%d-%04d.i420\n", img->d_w, img->d_h, ++frame_cnt); } } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; } 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
int main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; VpxVideoReader *reader = NULL; const VpxVideoInfo *info = NULL; const VpxInterface *decoder = NULL; exec_name = argv[0]; if (argc != 3) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing.", argv[2]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->codec_interface())); if (vpx_codec_dec_init(&codec, decoder->codec_interface(), NULL, 0)) die_codec(&codec, "Failed to initialize decoder"); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0)) die_codec(&codec, "Failed to decode frame"); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) { unsigned char digest[16]; get_image_md5(img, digest); print_md5(outfile, digest); fprintf(outfile, " img-%dx%d-%04d.i420\n", img->d_w, img->d_h, ++frame_cnt); } } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; }
174,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ref_param_read_signal_error(gs_param_list * plist, gs_param_name pkey, int code) { iparam_list *const iplist = (iparam_list *) plist; iparam_loc loc; ref_param_read(iplist, pkey, &loc, -1); /* can't fail */ *loc.presult = code; switch (ref_param_read_get_policy(plist, pkey)) { case gs_param_policy_ignore: return 0; return_error(gs_error_configurationerror); default: return code; } } Commit Message: CWE ID: CWE-704
ref_param_read_signal_error(gs_param_list * plist, gs_param_name pkey, int code) { iparam_list *const iplist = (iparam_list *) plist; iparam_loc loc = {0}; ref_param_read(iplist, pkey, &loc, -1); if (loc.presult) *loc.presult = code; switch (ref_param_read_get_policy(plist, pkey)) { case gs_param_policy_ignore: return 0; return_error(gs_error_configurationerror); default: return code; } }
164,705
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) { NOTREACHED(); return false; } policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); 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 AddPolicyForRenderer(sandbox::TargetPolicy* policy) { // Renderers need to copy sections for plugin DIBs and GPU. sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; // Renderers need to share events with plugins. result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; }
170,945
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) { int i, j, sym, wordsize; ut32 stype; wordsize = MACH0_(get_bits)(bin) / 8; if (idx < 0 || idx >= bin->nsymtab) { return 0; } if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) { stype = S_LAZY_SYMBOL_POINTERS; } else { stype = S_NON_LAZY_SYMBOL_POINTERS; } reloc->offset = 0; reloc->addr = 0; reloc->addend = 0; #define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break switch (wordsize) { CASE(8); CASE(16); CASE(32); CASE(64); default: return false; } #undef CASE for (i = 0; i < bin->nsects; i++) { if ((bin->sects[i].flags & SECTION_TYPE) == stype) { for (j=0, sym=-1; bin->sects[i].reserved1+j < bin->nindirectsyms; j++) if (idx == bin->indirectsyms[bin->sects[i].reserved1 + j]) { sym = j; break; } reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize; reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize; return true; } } return false; } Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026) CWE ID: CWE-125
static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) { int i, j, sym, wordsize; ut32 stype; wordsize = MACH0_(get_bits)(bin) / 8; if (idx < 0 || idx >= bin->nsymtab) { return 0; } if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) { stype = S_LAZY_SYMBOL_POINTERS; } else { stype = S_NON_LAZY_SYMBOL_POINTERS; } reloc->offset = 0; reloc->addr = 0; reloc->addend = 0; #define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break switch (wordsize) { CASE(8); CASE(16); CASE(32); CASE(64); default: return false; } #undef CASE for (i = 0; i < bin->nsects; i++) { if ((bin->sects[i].flags & SECTION_TYPE) == stype) { for (j = 0, sym = -1; bin->sects[i].reserved1 + j < bin->nindirectsyms; j++) { int indidx = bin->sects[i].reserved1 + j; if (indidx < 0 || indidx >= bin->nindirectsyms) { break; } if (idx == bin->indirectsyms[indidx]) { sym = j; break; } } reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize; reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize; return true; } } return false; }
169,227
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { assert((size_t)CDF_SEC_SIZE(h) == len); return cdf_read(info, (off_t)CDF_SEC_POS(h, id), ((char *)buf) + offs, len); } Commit Message: add more check found by cert's fuzzer. CWE ID: CWE-119
cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SEC_SIZE(h); size_t pos = CDF_SEC_POS(h, id); assert(ss == len); return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len); }
169,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void test_parser(void) { int i, retval; bzrtpPacket_t *zrtpPacket; /* Create zrtp Context to use H0-H3 chains and others */ bzrtpContext_t *context87654321 = bzrtp_createBzrtpContext(0x87654321); bzrtpContext_t *context12345678 = bzrtp_createBzrtpContext(0x12345678); /* replace created H by the patterns one to be able to generate the correct packet */ memcpy (context12345678->channelContext[0]->selfH[0], H12345678[0], 32); memcpy (context12345678->channelContext[0]->selfH[1], H12345678[1], 32); memcpy (context12345678->channelContext[0]->selfH[2], H12345678[2], 32); memcpy (context12345678->channelContext[0]->selfH[3], H12345678[3], 32); memcpy (context87654321->channelContext[0]->selfH[0], H87654321[0], 32); memcpy (context87654321->channelContext[0]->selfH[1], H87654321[1], 32); memcpy (context87654321->channelContext[0]->selfH[2], H87654321[2], 32); memcpy (context87654321->channelContext[0]->selfH[3], H87654321[3], 32); /* preset the key agreement algo in the contexts */ context87654321->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context12345678->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context87654321->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context12345678->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context87654321->channelContext[0]->hashAlgo = ZRTP_HASH_S256; context12345678->channelContext[0]->hashAlgo = ZRTP_HASH_S256; updateCryptoFunctionPointers(context87654321->channelContext[0]); updateCryptoFunctionPointers(context12345678->channelContext[0]); /* set the zrtp and mac keys */ context87654321->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context87654321->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context87654321->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context87654321->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); memcpy(context12345678->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context12345678->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context12345678->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context12345678->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); memcpy(context87654321->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context87654321->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context87654321->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context87654321->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); /* set the role: 87654321 is initiator in our exchange pattern */ context12345678->channelContext[0]->role = RESPONDER; for (i=0; i<TEST_PACKET_NUMBER; i++) { uint8_t freePacketFlag = 1; /* parse a packet string from patterns */ zrtpPacket = bzrtp_packetCheck(patternZRTPPackets[i], patternZRTPMetaData[i][0], (patternZRTPMetaData[i][1])-1, &retval); retval += bzrtp_packetParser((patternZRTPMetaData[i][2]==0x87654321)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x87654321)?context12345678->channelContext[0]:context87654321->channelContext[0], patternZRTPPackets[i], patternZRTPMetaData[i][0], zrtpPacket); /*printf("parsing Ret val is %x index is %d\n", retval, i);*/ /* We must store some packets in the context if we want to be able to parse further packets */ if (zrtpPacket->messageType==MSGTYPE_HELLO) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_DHPART1 || zrtpPacket->messageType==MSGTYPE_DHPART2) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } /* free the packet string as will be created again by the packetBuild function and might have been copied by packetParser */ free(zrtpPacket->packetString); /* build a packet string from the parser packet*/ retval = bzrtp_packetBuild((patternZRTPMetaData[i][2]==0x12345678)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x12345678)?context12345678->channelContext[0]:context87654321->channelContext[0], zrtpPacket, patternZRTPMetaData[i][1]); /* if (retval ==0) { packetDump(zrtpPacket, 1); } else { bzrtp_message("Ret val is %x index is %d\n", retval, i); }*/ /* check they are the same */ if (zrtpPacket->packetString != NULL) { CU_ASSERT_TRUE(memcmp(zrtpPacket->packetString, patternZRTPPackets[i], patternZRTPMetaData[i][0]) == 0); } else { CU_FAIL("Unable to build packet"); } if (freePacketFlag == 1) { bzrtp_freeZrtpPacket(zrtpPacket); } } bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); } Commit Message: Add ZRTP Commit packet hvi check on DHPart2 packet reception CWE ID: CWE-254
void test_parser(void) { void test_parser_param(uint8_t hvi_trick) { int i, retval; bzrtpPacket_t *zrtpPacket; /* Create zrtp Context to use H0-H3 chains and others */ bzrtpContext_t *context87654321 = bzrtp_createBzrtpContext(0x87654321); bzrtpContext_t *context12345678 = bzrtp_createBzrtpContext(0x12345678); /* replace created H by the patterns one to be able to generate the correct packet */ memcpy (context12345678->channelContext[0]->selfH[0], H12345678[0], 32); memcpy (context12345678->channelContext[0]->selfH[1], H12345678[1], 32); memcpy (context12345678->channelContext[0]->selfH[2], H12345678[2], 32); memcpy (context12345678->channelContext[0]->selfH[3], H12345678[3], 32); memcpy (context87654321->channelContext[0]->selfH[0], H87654321[0], 32); memcpy (context87654321->channelContext[0]->selfH[1], H87654321[1], 32); memcpy (context87654321->channelContext[0]->selfH[2], H87654321[2], 32); memcpy (context87654321->channelContext[0]->selfH[3], H87654321[3], 32); /* preset the key agreement algo in the contexts */ context87654321->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context12345678->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context87654321->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context12345678->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context87654321->channelContext[0]->hashAlgo = ZRTP_HASH_S256; context12345678->channelContext[0]->hashAlgo = ZRTP_HASH_S256; updateCryptoFunctionPointers(context87654321->channelContext[0]); updateCryptoFunctionPointers(context12345678->channelContext[0]); /* set the zrtp and mac keys */ context87654321->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context87654321->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context87654321->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context87654321->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); memcpy(context12345678->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context12345678->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context12345678->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context12345678->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); memcpy(context87654321->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context87654321->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context87654321->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context87654321->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); /* set the role: 87654321 is initiator in our exchange pattern */ context12345678->channelContext[0]->role = RESPONDER; for (i=0; i<TEST_PACKET_NUMBER; i++) { uint8_t freePacketFlag = 1; /* parse a packet string from patterns */ zrtpPacket = bzrtp_packetCheck(patternZRTPPackets[i], patternZRTPMetaData[i][0], (patternZRTPMetaData[i][1])-1, &retval); retval += bzrtp_packetParser((patternZRTPMetaData[i][2]==0x87654321)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x87654321)?context12345678->channelContext[0]:context87654321->channelContext[0], patternZRTPPackets[i], patternZRTPMetaData[i][0], zrtpPacket); if (hvi_trick==0) { CU_ASSERT_EQUAL_FATAL(retval,0); } else { /* when hvi trick is enable, the DH2 parsing shall fail and return BZRTP_PARSER_ERROR_UNMATCHINGHVI */ if (zrtpPacket->messageType==MSGTYPE_DHPART2) { CU_ASSERT_EQUAL_FATAL(retval, BZRTP_PARSER_ERROR_UNMATCHINGHVI); /* We shall then anyway skip the end of the test */ /* reset pointers to selfHello packet in order to avoid double free */ context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); return; } else { CU_ASSERT_EQUAL_FATAL(retval,0); } } bzrtp_message("parsing Ret val is %x index is %d\n", retval, i); /* We must store some packets in the context if we want to be able to parse further packets */ if (zrtpPacket->messageType==MSGTYPE_HELLO) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_DHPART1 || zrtpPacket->messageType==MSGTYPE_DHPART2) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } /* free the packet string as will be created again by the packetBuild function and might have been copied by packetParser */ free(zrtpPacket->packetString); /* build a packet string from the parser packet*/ retval = bzrtp_packetBuild((patternZRTPMetaData[i][2]==0x12345678)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x12345678)?context12345678->channelContext[0]:context87654321->channelContext[0], zrtpPacket, patternZRTPMetaData[i][1]); /* if (retval ==0) { packetDump(zrtpPacket, 1); } else { bzrtp_message("Ret val is %x index is %d\n", retval, i); }*/ /* check they are the same */ if (zrtpPacket->packetString != NULL) { CU_ASSERT_TRUE(memcmp(zrtpPacket->packetString, patternZRTPPackets[i], patternZRTPMetaData[i][0]) == 0); } else { CU_FAIL("Unable to build packet"); } if (freePacketFlag == 1) { bzrtp_freeZrtpPacket(zrtpPacket); } /* modify the hvi stored in the peerPackets, this shall result in parsing failure on DH2 packet */ if (hvi_trick == 1) { if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { bzrtpCommitMessage_t *peerCommitMessageData; peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpPacket->messageData; peerCommitMessageData->hvi[0]=0xFF; } } } } /* reset pointers to selfHello packet in order to avoid double free */ context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); }
168,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n"); if (!CDROM_CAN(CDC_SELECT_DISC)) return -ENOSYS; if (arg != CDSL_CURRENT && arg != CDSL_NONE) { if ((int)arg >= cdi->capacity) return -EINVAL; } /* * ->select_disc is a hook to allow a driver-specific way of * seleting disc. However, since there is no equivalent hook for * cdrom_slot_status this may not actually be useful... */ if (cdi->ops->select_disc) return cdi->ops->select_disc(cdi, arg); cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n"); return cdrom_select_disc(cdi, arg); } Commit Message: cdrom: fix improper type cast, which can leat to information leak. There is another cast from unsigned long to int which causes a bounds check to fail with specially crafted input. The value is then used as an index in the slot array in cdrom_slot_status(). This issue is similar to CVE-2018-16658 and CVE-2018-10940. Signed-off-by: Young_X <YangX92@hotmail.com> Signed-off-by: Jens Axboe <axboe@kernel.dk> CWE ID: CWE-200
static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n"); if (!CDROM_CAN(CDC_SELECT_DISC)) return -ENOSYS; if (arg != CDSL_CURRENT && arg != CDSL_NONE) { if (arg >= cdi->capacity) return -EINVAL; } /* * ->select_disc is a hook to allow a driver-specific way of * seleting disc. However, since there is no equivalent hook for * cdrom_slot_status this may not actually be useful... */ if (cdi->ops->select_disc) return cdi->ops->select_disc(cdi, arg); cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n"); return cdrom_select_disc(cdi, arg); }
168,999
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int treo_attach(struct usb_serial *serial) { struct usb_serial_port *swap_port; /* Only do this endpoint hack for the Handspring devices with * interrupt in endpoints, which for now are the Treo devices. */ if (!((le16_to_cpu(serial->dev->descriptor.idVendor) == HANDSPRING_VENDOR_ID) || (le16_to_cpu(serial->dev->descriptor.idVendor) == KYOCERA_VENDOR_ID)) || (serial->num_interrupt_in == 0)) return 0; /* * It appears that Treos and Kyoceras want to use the * 1st bulk in endpoint to communicate with the 2nd bulk out endpoint, * so let's swap the 1st and 2nd bulk in and interrupt endpoints. * Note that swapping the bulk out endpoints would break lots of * apps that want to communicate on the second port. */ #define COPY_PORT(dest, src) \ do { \ int i; \ \ for (i = 0; i < ARRAY_SIZE(src->read_urbs); ++i) { \ dest->read_urbs[i] = src->read_urbs[i]; \ dest->read_urbs[i]->context = dest; \ dest->bulk_in_buffers[i] = src->bulk_in_buffers[i]; \ } \ dest->read_urb = src->read_urb; \ dest->bulk_in_endpointAddress = src->bulk_in_endpointAddress;\ dest->bulk_in_buffer = src->bulk_in_buffer; \ dest->bulk_in_size = src->bulk_in_size; \ dest->interrupt_in_urb = src->interrupt_in_urb; \ dest->interrupt_in_urb->context = dest; \ dest->interrupt_in_endpointAddress = \ src->interrupt_in_endpointAddress;\ dest->interrupt_in_buffer = src->interrupt_in_buffer; \ } while (0); swap_port = kmalloc(sizeof(*swap_port), GFP_KERNEL); if (!swap_port) return -ENOMEM; COPY_PORT(swap_port, serial->port[0]); COPY_PORT(serial->port[0], serial->port[1]); COPY_PORT(serial->port[1], swap_port); kfree(swap_port); return 0; } Commit Message: USB: visor: fix null-deref at probe Fix null-pointer dereference at probe should a (malicious) Treo device lack the expected endpoints. Specifically, the Treo port-setup hack was dereferencing the bulk-in and interrupt-in urbs without first making sure they had been allocated by core. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <stable@vger.kernel.org> Signed-off-by: Johan Hovold <johan@kernel.org> CWE ID:
static int treo_attach(struct usb_serial *serial) { struct usb_serial_port *swap_port; /* Only do this endpoint hack for the Handspring devices with * interrupt in endpoints, which for now are the Treo devices. */ if (!((le16_to_cpu(serial->dev->descriptor.idVendor) == HANDSPRING_VENDOR_ID) || (le16_to_cpu(serial->dev->descriptor.idVendor) == KYOCERA_VENDOR_ID)) || (serial->num_interrupt_in == 0)) return 0; if (serial->num_bulk_in < 2 || serial->num_interrupt_in < 2) { dev_err(&serial->interface->dev, "missing endpoints\n"); return -ENODEV; } /* * It appears that Treos and Kyoceras want to use the * 1st bulk in endpoint to communicate with the 2nd bulk out endpoint, * so let's swap the 1st and 2nd bulk in and interrupt endpoints. * Note that swapping the bulk out endpoints would break lots of * apps that want to communicate on the second port. */ #define COPY_PORT(dest, src) \ do { \ int i; \ \ for (i = 0; i < ARRAY_SIZE(src->read_urbs); ++i) { \ dest->read_urbs[i] = src->read_urbs[i]; \ dest->read_urbs[i]->context = dest; \ dest->bulk_in_buffers[i] = src->bulk_in_buffers[i]; \ } \ dest->read_urb = src->read_urb; \ dest->bulk_in_endpointAddress = src->bulk_in_endpointAddress;\ dest->bulk_in_buffer = src->bulk_in_buffer; \ dest->bulk_in_size = src->bulk_in_size; \ dest->interrupt_in_urb = src->interrupt_in_urb; \ dest->interrupt_in_urb->context = dest; \ dest->interrupt_in_endpointAddress = \ src->interrupt_in_endpointAddress;\ dest->interrupt_in_buffer = src->interrupt_in_buffer; \ } while (0); swap_port = kmalloc(sizeof(*swap_port), GFP_KERNEL); if (!swap_port) return -ENOMEM; COPY_PORT(swap_port, serial->port[0]); COPY_PORT(serial->port[0], serial->port[1]); COPY_PORT(serial->port[1], swap_port); kfree(swap_port); return 0; }
167,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;" "[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;" "[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;" "ұ > y; [χҳӽӿ] > x;" #if defined(OS_WIN) "ӏ > i;" #else "ӏ > l;" #endif "ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;" "[зӡ] > 3"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Map U+04CF to lowercase L as well. U+04CF (ӏ) has the confusability skeleton of 'i' (lowercase I), but it can be confused for 'l' (lowercase L) or '1' (digit) if rendered in some fonts. If a host name contains it, calculate the confusability skeleton twice, once with the default mapping to 'i' (lowercase I) and the 2nd time with an alternative mapping to 'l'. Mapping them to 'l' (lowercase L) also gets it treated as similar to digit 1 because the confusability skeleton of digit 1 is 'l'. Bug: 817247 Test: components_unittests --gtest_filter=*IDN* Change-Id: I7442b950c9457eea285e17f01d1f43c9acc5d79c Reviewed-on: https://chromium-review.googlesource.com/974165 Commit-Queue: Jungshik Shin <jshin@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Reviewed-by: Eric Lawrence <elawrence@chromium.org> Cr-Commit-Position: refs/heads/master@{#551263} CWE ID:
IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;" "[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;" "[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;" "ұ > y; [χҳӽӿ] > x;" "ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;" "[зӡ] > 3"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); }
173,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DictionaryValue* NigoriSpecificsToValue( const sync_pb::NigoriSpecifics& proto) { DictionaryValue* value = new DictionaryValue(); SET(encrypted, EncryptedDataToValue); SET_BOOL(using_explicit_passphrase); SET_BOOL(encrypt_bookmarks); SET_BOOL(encrypt_preferences); SET_BOOL(encrypt_autofill_profile); SET_BOOL(encrypt_autofill); SET_BOOL(encrypt_themes); SET_BOOL(encrypt_typed_urls); SET_BOOL(encrypt_extension_settings); SET_BOOL(encrypt_extensions); SET_BOOL(encrypt_sessions); SET_BOOL(encrypt_app_settings); SET_BOOL(encrypt_apps); SET_BOOL(encrypt_search_engines); SET_BOOL(sync_tabs); SET_BOOL(encrypt_everything); SET_REP(device_information, DeviceInformationToValue); SET_BOOL(sync_tab_favicons); return value; } 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
DictionaryValue* NigoriSpecificsToValue( const sync_pb::NigoriSpecifics& proto) { DictionaryValue* value = new DictionaryValue(); SET(encrypted, EncryptedDataToValue); SET_BOOL(using_explicit_passphrase); SET_BOOL(encrypt_bookmarks); SET_BOOL(encrypt_preferences); SET_BOOL(encrypt_autofill_profile); SET_BOOL(encrypt_autofill); SET_BOOL(encrypt_themes); SET_BOOL(encrypt_typed_urls); SET_BOOL(encrypt_extension_settings); SET_BOOL(encrypt_extensions); SET_BOOL(encrypt_sessions); SET_BOOL(encrypt_app_settings); SET_BOOL(encrypt_apps); SET_BOOL(encrypt_search_engines); SET_BOOL(encrypt_everything); SET_REP(device_information, DeviceInformationToValue); SET_BOOL(sync_tab_favicons); return value; }
170,800
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ogg_uint32_t decpack(long entry,long used_entry,long quantvals, codebook *b,oggpack_buffer *opb,int maptype){ ogg_uint32_t ret=0; int j; switch(b->dec_type){ case 0: return (ogg_uint32_t)entry; case 1: if(maptype==1){ /* vals are already read into temporary column vector here */ for(j=0;j<b->dim;j++){ ogg_uint32_t off=entry%quantvals; entry/=quantvals; ret|=((ogg_uint16_t *)(b->q_val))[off]<<(b->q_bits*j); } }else{ for(j=0;j<b->dim;j++) ret|=oggpack_read(opb,b->q_bits)<<(b->q_bits*j); } return ret; case 2: for(j=0;j<b->dim;j++){ ogg_uint32_t off=entry%quantvals; entry/=quantvals; ret|=off<<(b->q_pack*j); } return ret; case 3: return (ogg_uint32_t)used_entry; } return 0; /* silence compiler */ } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
static ogg_uint32_t decpack(long entry,long used_entry,long quantvals, codebook *b,oggpack_buffer *opb,int maptype){ ogg_uint32_t ret=0; int j; switch(b->dec_type){ case 0: return (ogg_uint32_t)entry; case 1: if(maptype==1){ /* vals are already read into temporary column vector here */ for(j=0;j<b->dim;j++){ ogg_uint32_t off=entry%quantvals; entry/=quantvals; ret|=((ogg_uint16_t *)(b->q_val))[off]<<(b->q_bits*j); } }else{ for(j=0;j<b->dim;j++) ret|=oggpack_read(opb,b->q_bits)<<(b->q_bits*j); } return ret; case 2: for(j=0;j<b->dim;j++){ ogg_uint32_t off=entry%quantvals; entry/=quantvals; ret|=off<<(b->q_pack*j); } return ret; case 3: return (ogg_uint32_t)used_entry; } return 0; /* silence compiler */ }
173,985
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != NULL || 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]); mTimeToSample = new uint32_t[mTimeToSampleCount * 2]; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } return OK; } Commit Message: SampleTable: check integer overflow during table alloc Bug: 15328708 Bug: 15342615 Bug: 15342751 Change-Id: I6bb110a1eba46506799c73be8ff9a4f71c7e7053 CWE ID: CWE-189
status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != NULL || 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]); uint64_t allocSize = mTimeToSampleCount * 2 * sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mTimeToSample = new uint32_t[mTimeToSampleCount * 2]; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } return OK; }
173,377
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb) { struct llc_sock *llc = llc_sk(skb->sk); if (llc->cmsg_flags & LLC_CMSG_PKTINFO) { struct llc_pktinfo info; info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex; llc_pdu_decode_dsap(skb, &info.lpi_sap); llc_pdu_decode_da(skb, info.lpi_mac); put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info); } } Commit Message: net: fix infoleak in llc The stack object “info” has a total size of 12 bytes. Its last byte is padding which is not initialized and leaked via “put_cmsg”. Signed-off-by: Kangjie Lu <kjlu@gatech.edu> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
static void llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb) { struct llc_sock *llc = llc_sk(skb->sk); if (llc->cmsg_flags & LLC_CMSG_PKTINFO) { struct llc_pktinfo info; memset(&info, 0, sizeof(info)); info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex; llc_pdu_decode_dsap(skb, &info.lpi_sap); llc_pdu_decode_da(skb, info.lpi_mac); put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info); } }
167,258