instruction
stringclasses
1 value
input
stringlengths
90
9.34k
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: static inline int btif_hl_select_close_connected(void){ char sig_on = btif_hl_signal_select_close_connected; BTIF_TRACE_DEBUG("btif_hl_select_close_connected"); return send(signal_fds[1], &sig_on, sizeof(sig_on), 0); } 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
static inline int btif_hl_select_close_connected(void){ char sig_on = btif_hl_signal_select_close_connected; BTIF_TRACE_DEBUG("btif_hl_select_close_connected"); return TEMP_FAILURE_RETRY(send(signal_fds[1], &sig_on, sizeof(sig_on), 0)); }
173,440
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: const Block* Track::EOSBlock::GetBlock() const { return NULL; } 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
const Block* Track::EOSBlock::GetBlock() const
174,284
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 RenderFrameDevToolsAgentHost::UpdateFrameHost( RenderFrameHostImpl* frame_host) { if (frame_host == frame_host_) { if (frame_host && !render_frame_alive_) { render_frame_alive_ = true; MaybeReattachToRenderFrame(); } return; } if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) { DestroyOnRenderFrameGone(); return; } if (IsAttached()) RevokePolicy(); frame_host_ = frame_host; agent_ptr_.reset(); render_frame_alive_ = true; if (IsAttached()) { GrantPolicy(); for (DevToolsSession* session : sessions()) { session->SetRenderer(frame_host ? frame_host->GetProcess() : nullptr, frame_host); } MaybeReattachToRenderFrame(); } } 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 <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void RenderFrameDevToolsAgentHost::UpdateFrameHost( RenderFrameHostImpl* frame_host) { if (frame_host == frame_host_) { if (frame_host && !render_frame_alive_) { render_frame_alive_ = true; MaybeReattachToRenderFrame(); } return; } if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) { DestroyOnRenderFrameGone(); return; } if (IsAttached()) RevokePolicy(); frame_host_ = frame_host; agent_ptr_.reset(); render_frame_alive_ = true; if (IsAttached()) { GrantPolicy(); for (DevToolsSession* session : sessions()) { session->SetRenderer(frame_host ? frame_host->GetProcess()->GetID() : -1, frame_host); } MaybeReattachToRenderFrame(); } }
172,782
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: void InputConnectionImpl::CommitText(const base::string16& text, int new_cursor_pos) { StartStateUpdateTimer(); std::string error; if (!ime_engine_->ClearComposition(input_context_id_, &error)) LOG(ERROR) << "ClearComposition failed: error=\"" << error << "\""; if (IsControlChar(text)) { SendControlKeyEvent(text); return; } if (!ime_engine_->CommitText(input_context_id_, base::UTF16ToUTF8(text).c_str(), &error)) LOG(ERROR) << "CommitText failed: error=\"" << error << "\""; } Commit Message: Clear |composing_text_| after CommitText() is called. |composing_text_| of InputConnectionImpl should be cleared after CommitText() is called. Otherwise, FinishComposingText() will commit the same text twice. Bug: 899736 Test: unit_tests Change-Id: Idb22d968ffe95d946789fbe62454e8e79cb0b384 Reviewed-on: https://chromium-review.googlesource.com/c/1304773 Commit-Queue: Yusuke Sato <[email protected]> Reviewed-by: Yusuke Sato <[email protected]> Cr-Commit-Position: refs/heads/master@{#603518} CWE ID: CWE-119
void InputConnectionImpl::CommitText(const base::string16& text, int new_cursor_pos) { StartStateUpdateTimer(); std::string error; if (!ime_engine_->ClearComposition(input_context_id_, &error)) LOG(ERROR) << "ClearComposition failed: error=\"" << error << "\""; if (IsControlChar(text)) { SendControlKeyEvent(text); return; } if (!ime_engine_->CommitText(input_context_id_, base::UTF16ToUTF8(text).c_str(), &error)) LOG(ERROR) << "CommitText failed: error=\"" << error << "\""; composing_text_.clear(); }
173,333
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 crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_rng rrng; snprintf(rrng.type, CRYPTO_MAX_ALG_NAME, "%s", "rng"); rrng.seedsize = alg->cra_rng.seedsize; if (nla_put(skb, CRYPTOCFGA_REPORT_RNG, sizeof(struct crypto_report_rng), &rrng)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Commit Message: crypto: user - fix info leaks in report API Three errors resulting in kernel memory disclosure: 1/ The structures used for the netlink based crypto algorithm report API are located on the stack. As snprintf() does not fill the remainder of the buffer with null bytes, those stack bytes will be disclosed to users of the API. Switch to strncpy() to fix this. 2/ crypto_report_one() does not initialize all field of struct crypto_user_alg. Fix this to fix the heap info leak. 3/ For the module name we should copy only as many bytes as module_name() returns -- not as much as the destination buffer could hold. But the current code does not and therefore copies random data from behind the end of the module name, as the module name is always shorter than CRYPTO_MAX_ALG_NAME. Also switch to use strncpy() to copy the algorithm's name and driver_name. They are strings, after all. Signed-off-by: Mathias Krause <[email protected]> Cc: Steffen Klassert <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-310
static int crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_rng rrng; strncpy(rrng.type, "rng", sizeof(rrng.type)); rrng.seedsize = alg->cra_rng.seedsize; if (nla_put(skb, CRYPTOCFGA_REPORT_RNG, sizeof(struct crypto_report_rng), &rrng)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; }
166,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: xsltProcessUserParamInternal(xsltTransformContextPtr ctxt, const xmlChar * name, const xmlChar * value, int eval) { xsltStylesheetPtr style; const xmlChar *prefix; const xmlChar *href; xmlXPathCompExprPtr xpExpr; xmlXPathObjectPtr result; xsltStackElemPtr elem; int res; void *res_ptr; if (ctxt == NULL) return(-1); if (name == NULL) return(0); if (value == NULL) return(0); style = ctxt->style; #ifdef WITH_XSLT_DEBUG_VARIABLE XSLT_TRACE(ctxt,XSLT_TRACE_VARIABLES,xsltGenericDebug(xsltGenericDebugContext, "Evaluating user parameter %s=%s\n", name, value)); #endif /* * Name lookup */ name = xsltSplitQName(ctxt->dict, name, &prefix); href = NULL; if (prefix != NULL) { xmlNsPtr ns; ns = xmlSearchNs(style->doc, xmlDocGetRootElement(style->doc), prefix); if (ns == NULL) { xsltTransformError(ctxt, style, NULL, "user param : no namespace bound to prefix %s\n", prefix); href = NULL; } else { href = ns->href; } } if (name == NULL) return (-1); res_ptr = xmlHashLookup2(ctxt->globalVars, name, href); if (res_ptr != 0) { xsltTransformError(ctxt, style, NULL, "Global parameter %s already defined\n", name); } if (ctxt->globalVars == NULL) ctxt->globalVars = xmlHashCreate(20); /* * do not overwrite variables with parameters from the command line */ while (style != NULL) { elem = ctxt->style->variables; while (elem != NULL) { if ((elem->comp != NULL) && (elem->comp->type == XSLT_FUNC_VARIABLE) && (xmlStrEqual(elem->name, name)) && (xmlStrEqual(elem->nameURI, href))) { return(0); } elem = elem->next; } style = xsltNextImport(style); } style = ctxt->style; elem = NULL; /* * Do the evaluation if @eval is non-zero. */ result = NULL; if (eval != 0) { xpExpr = xmlXPathCompile(value); if (xpExpr != NULL) { xmlDocPtr oldXPDoc; xmlNodePtr oldXPContextNode; int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; xmlNsPtr *oldXPNamespaces; xmlXPathContextPtr xpctxt = ctxt->xpathCtxt; /* * Save context states. */ oldXPDoc = xpctxt->doc; oldXPContextNode = xpctxt->node; oldXPProximityPosition = xpctxt->proximityPosition; oldXPContextSize = xpctxt->contextSize; oldXPNamespaces = xpctxt->namespaces; oldXPNsNr = xpctxt->nsNr; /* * SPEC XSLT 1.0: * "At top-level, the expression or template specifying the * variable value is evaluated with the same context as that used * to process the root node of the source document: the current * node is the root node of the source document and the current * node list is a list containing just the root node of the source * document." */ xpctxt->doc = ctxt->initialContextDoc; xpctxt->node = ctxt->initialContextNode; xpctxt->contextSize = 1; xpctxt->proximityPosition = 1; /* * There is really no in scope namespace for parameters on the * command line. */ xpctxt->namespaces = NULL; xpctxt->nsNr = 0; result = xmlXPathCompiledEval(xpExpr, xpctxt); /* * Restore Context states. */ xpctxt->doc = oldXPDoc; xpctxt->node = oldXPContextNode; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->namespaces = oldXPNamespaces; xpctxt->nsNr = oldXPNsNr; xmlXPathFreeCompExpr(xpExpr); } if (result == NULL) { xsltTransformError(ctxt, style, NULL, "Evaluating user parameter %s failed\n", name); ctxt->state = XSLT_STATE_STOPPED; return(-1); } } /* * If @eval is 0 then @value is to be taken literally and result is NULL * * If @eval is not 0, then @value is an XPath expression and has been * successfully evaluated and result contains the resulting value and * is not NULL. * * Now create an xsltStackElemPtr for insertion into the context's * global variable/parameter hash table. */ #ifdef WITH_XSLT_DEBUG_VARIABLE #ifdef LIBXML_DEBUG_ENABLED if ((xsltGenericDebugContext == stdout) || (xsltGenericDebugContext == stderr)) xmlXPathDebugDumpObject((FILE *)xsltGenericDebugContext, result, 0); #endif #endif elem = xsltNewStackElem(NULL); if (elem != NULL) { elem->name = name; elem->select = xmlDictLookup(ctxt->dict, value, -1); if (href != NULL) elem->nameURI = xmlDictLookup(ctxt->dict, href, -1); elem->tree = NULL; elem->computed = 1; if (eval == 0) { elem->value = xmlXPathNewString(value); } else { elem->value = result; } } /* * Global parameters are stored in the XPath context variables pool. */ res = xmlHashAddEntry2(ctxt->globalVars, name, href, elem); if (res != 0) { xsltFreeStackElem(elem); xsltTransformError(ctxt, style, NULL, "Global parameter %s already defined\n", name); } return(0); } 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
xsltProcessUserParamInternal(xsltTransformContextPtr ctxt, const xmlChar * name, const xmlChar * value, int eval) { xsltStylesheetPtr style; const xmlChar *prefix; const xmlChar *href; xmlXPathCompExprPtr xpExpr; xmlXPathObjectPtr result; xsltStackElemPtr elem; int res; void *res_ptr; if (ctxt == NULL) return(-1); if (name == NULL) return(0); if (value == NULL) return(0); style = ctxt->style; #ifdef WITH_XSLT_DEBUG_VARIABLE XSLT_TRACE(ctxt,XSLT_TRACE_VARIABLES,xsltGenericDebug(xsltGenericDebugContext, "Evaluating user parameter %s=%s\n", name, value)); #endif /* * Name lookup */ href = NULL; if (name[0] == '{') { int len = 0; while ((name[len] != 0) && (name[len] != '}')) len++; if (name[len] == 0) { xsltTransformError(ctxt, style, NULL, "user param : malformed parameter name : %s\n", name); } else { href = xmlDictLookup(ctxt->dict, &name[1], len-1); name = xmlDictLookup(ctxt->dict, &name[len + 1], -1); } } else { name = xsltSplitQName(ctxt->dict, name, &prefix); if (prefix != NULL) { xmlNsPtr ns; ns = xmlSearchNs(style->doc, xmlDocGetRootElement(style->doc), prefix); if (ns == NULL) { xsltTransformError(ctxt, style, NULL, "user param : no namespace bound to prefix %s\n", prefix); href = NULL; } else { href = ns->href; } } } if (name == NULL) return (-1); res_ptr = xmlHashLookup2(ctxt->globalVars, name, href); if (res_ptr != 0) { xsltTransformError(ctxt, style, NULL, "Global parameter %s already defined\n", name); } if (ctxt->globalVars == NULL) ctxt->globalVars = xmlHashCreate(20); /* * do not overwrite variables with parameters from the command line */ while (style != NULL) { elem = ctxt->style->variables; while (elem != NULL) { if ((elem->comp != NULL) && (elem->comp->type == XSLT_FUNC_VARIABLE) && (xmlStrEqual(elem->name, name)) && (xmlStrEqual(elem->nameURI, href))) { return(0); } elem = elem->next; } style = xsltNextImport(style); } style = ctxt->style; elem = NULL; /* * Do the evaluation if @eval is non-zero. */ result = NULL; if (eval != 0) { xpExpr = xmlXPathCompile(value); if (xpExpr != NULL) { xmlDocPtr oldXPDoc; xmlNodePtr oldXPContextNode; int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; xmlNsPtr *oldXPNamespaces; xmlXPathContextPtr xpctxt = ctxt->xpathCtxt; /* * Save context states. */ oldXPDoc = xpctxt->doc; oldXPContextNode = xpctxt->node; oldXPProximityPosition = xpctxt->proximityPosition; oldXPContextSize = xpctxt->contextSize; oldXPNamespaces = xpctxt->namespaces; oldXPNsNr = xpctxt->nsNr; /* * SPEC XSLT 1.0: * "At top-level, the expression or template specifying the * variable value is evaluated with the same context as that used * to process the root node of the source document: the current * node is the root node of the source document and the current * node list is a list containing just the root node of the source * document." */ xpctxt->doc = ctxt->initialContextDoc; xpctxt->node = ctxt->initialContextNode; xpctxt->contextSize = 1; xpctxt->proximityPosition = 1; /* * There is really no in scope namespace for parameters on the * command line. */ xpctxt->namespaces = NULL; xpctxt->nsNr = 0; result = xmlXPathCompiledEval(xpExpr, xpctxt); /* * Restore Context states. */ xpctxt->doc = oldXPDoc; xpctxt->node = oldXPContextNode; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->namespaces = oldXPNamespaces; xpctxt->nsNr = oldXPNsNr; xmlXPathFreeCompExpr(xpExpr); } if (result == NULL) { xsltTransformError(ctxt, style, NULL, "Evaluating user parameter %s failed\n", name); ctxt->state = XSLT_STATE_STOPPED; return(-1); } } /* * If @eval is 0 then @value is to be taken literally and result is NULL * * If @eval is not 0, then @value is an XPath expression and has been * successfully evaluated and result contains the resulting value and * is not NULL. * * Now create an xsltStackElemPtr for insertion into the context's * global variable/parameter hash table. */ #ifdef WITH_XSLT_DEBUG_VARIABLE #ifdef LIBXML_DEBUG_ENABLED if ((xsltGenericDebugContext == stdout) || (xsltGenericDebugContext == stderr)) xmlXPathDebugDumpObject((FILE *)xsltGenericDebugContext, result, 0); #endif #endif elem = xsltNewStackElem(NULL); if (elem != NULL) { elem->name = name; elem->select = xmlDictLookup(ctxt->dict, value, -1); if (href != NULL) elem->nameURI = xmlDictLookup(ctxt->dict, href, -1); elem->tree = NULL; elem->computed = 1; if (eval == 0) { elem->value = xmlXPathNewString(value); } else { elem->value = result; } } /* * Global parameters are stored in the XPath context variables pool. */ res = xmlHashAddEntry2(ctxt->globalVars, name, href, elem); if (res != 0) { xsltFreeStackElem(elem); xsltTransformError(ctxt, style, NULL, "Global parameter %s already defined\n", name); } return(0); }
173,332
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 RenderViewTest::SetUp() { if (!GetContentClient()->renderer()) GetContentClient()->set_renderer(&mock_content_renderer_client_); if (!render_thread_.get()) render_thread_.reset(new MockRenderThread()); render_thread_->set_routing_id(kRouteId); render_thread_->set_surface_id(kSurfaceId); command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM)); params_.reset(new content::MainFunctionParams(*command_line_)); platform_.reset(new RendererMainPlatformDelegate(*params_)); platform_->PlatformInitialize(); webkit_glue::SetJavaScriptFlags(" --expose-gc"); WebKit::initialize(&webkit_platform_support_); mock_process_.reset(new MockRenderProcess); RenderViewImpl* view = RenderViewImpl::Create( 0, kOpenerId, content::RendererPreferences(), WebPreferences(), new SharedRenderViewCounter(0), kRouteId, kSurfaceId, kInvalidSessionStorageNamespaceId, string16(), 1, WebKit::WebScreenInfo()); view->AddRef(); view_ = view; mock_keyboard_.reset(new MockKeyboard()); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void RenderViewTest::SetUp() { if (!GetContentClient()->renderer()) GetContentClient()->set_renderer(&mock_content_renderer_client_); if (!render_thread_.get()) render_thread_.reset(new MockRenderThread()); render_thread_->set_routing_id(kRouteId); render_thread_->set_surface_id(kSurfaceId); render_thread_->set_new_window_routing_id(kNewWindowRouteId); command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM)); params_.reset(new content::MainFunctionParams(*command_line_)); platform_.reset(new RendererMainPlatformDelegate(*params_)); platform_->PlatformInitialize(); webkit_glue::SetJavaScriptFlags(" --expose-gc"); WebKit::initialize(&webkit_platform_support_); mock_process_.reset(new MockRenderProcess); RenderViewImpl* view = RenderViewImpl::Create( 0, kOpenerId, content::RendererPreferences(), WebPreferences(), new SharedRenderViewCounter(0), kRouteId, kSurfaceId, kInvalidSessionStorageNamespaceId, string16(), 1, WebKit::WebScreenInfo()); view->AddRef(); view_ = view; mock_keyboard_.reset(new MockKeyboard()); }
171,025
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 AppCacheDatabase::InsertEntry(const EntryRecord* record) { if (!LazyOpen(kCreateIfNeeded)) return false; static const char kSql[] = "INSERT INTO Entries (cache_id, url, flags, response_id, response_size)" " VALUES(?, ?, ?, ?, ?)"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, record->cache_id); statement.BindString(1, record->url.spec()); statement.BindInt(2, record->flags); statement.BindInt64(3, record->response_id); statement.BindInt64(4, record->response_size); return statement.Run(); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
bool AppCacheDatabase::InsertEntry(const EntryRecord* record) { if (!LazyOpen(kCreateIfNeeded)) return false; static const char kSql[] = "INSERT INTO Entries (cache_id, url, flags, response_id, response_size, " "padding_size)" " VALUES(?, ?, ?, ?, ?, ?)"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, record->cache_id); statement.BindString(1, record->url.spec()); statement.BindInt(2, record->flags); statement.BindInt64(3, record->response_id); DCHECK_GE(record->response_size, 0); statement.BindInt64(4, record->response_size); DCHECK_GE(record->padding_size, 0); statement.BindInt64(5, record->padding_size); return statement.Run(); }
172,980
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 php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } Commit Message: Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle Proper soltion would be to call serialize/unserialize and deal with the result, but this requires more work that should be done by wddx maintainer (not me). CWE ID: CWE-476
static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } if (pce != &PHP_IC_ENTRY && ((*pce)->serialize || (*pce)->unserialize)) { ent2->data = NULL; php_error_docref(NULL TSRMLS_CC, E_WARNING, "Class %s can not be unserialized", Z_STRVAL_P(ent1->data)); } else { /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; } /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } }
168,669
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 locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithException()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefThrows(cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithException()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefThrows(cppValue); }
171,688
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 Set(const std::string& addr, int value) { base::AutoLock lock(lock_); map_[addr] = value; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void Set(const std::string& addr, int value) { // Sets the |value| for |preview_id|. void Set(int32 preview_id, int value) { base::AutoLock lock(lock_); map_[preview_id] = value; }
170,842
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: get_pols_2_svc(gpols_arg *arg, struct svc_req *rqstp) { static gpols_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gpols_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->exp; if (prime_arg == NULL) prime_arg = "*"; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_LIST, NULL, NULL)) { ret.code = KADM5_AUTH_LIST; log_unauth("kadm5_get_policies", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_policies((void *)handle, arg->exp, &ret.pols, &ret.count); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_policies", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
get_pols_2_svc(gpols_arg *arg, struct svc_req *rqstp) { static gpols_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gpols_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->exp; if (prime_arg == NULL) prime_arg = "*"; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_LIST, NULL, NULL)) { ret.code = KADM5_AUTH_LIST; log_unauth("kadm5_get_policies", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_policies((void *)handle, arg->exp, &ret.pols, &ret.count); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_policies", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,514
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 upnp_event_prepare(struct upnp_event_notify * obj) { static const char notifymsg[] = "NOTIFY %s HTTP/1.1\r\n" "Host: %s%s\r\n" #if (UPNP_VERSION_MAJOR == 1) && (UPNP_VERSION_MINOR == 0) "Content-Type: text/xml\r\n" /* UDA v1.0 */ #else "Content-Type: text/xml; charset=\"utf-8\"\r\n" /* UDA v1.1 or later */ #endif "Content-Length: %d\r\n" "NT: upnp:event\r\n" "NTS: upnp:propchange\r\n" "SID: %s\r\n" "SEQ: %u\r\n" "Connection: close\r\n" "Cache-Control: no-cache\r\n" "\r\n" "%.*s\r\n"; char * xml; int l; if(obj->sub == NULL) { obj->state = EError; return; } switch(obj->sub->service) { case EWanCFG: xml = getVarsWANCfg(&l); break; case EWanIPC: xml = getVarsWANIPCn(&l); break; #ifdef ENABLE_L3F_SERVICE case EL3F: xml = getVarsL3F(&l); break; #endif #ifdef ENABLE_6FC_SERVICE case E6FC: xml = getVars6FC(&l); break; #endif #ifdef ENABLE_DP_SERVICE case EDP: xml = getVarsDP(&l); break; #endif default: xml = NULL; l = 0; } obj->buffersize = 1024; obj->buffer = malloc(obj->buffersize); if(!obj->buffer) { syslog(LOG_ERR, "%s: malloc returned NULL", "upnp_event_prepare"); if(xml) { free(xml); } obj->state = EError; return; } obj->tosend = snprintf(obj->buffer, obj->buffersize, notifymsg, obj->path, obj->addrstr, obj->portstr, l+2, obj->sub->uuid, obj->sub->seq, l, xml); if(xml) { free(xml); xml = NULL; } obj->state = ESending; } Commit Message: upnp_event_prepare(): check the return value of snprintf() CWE ID: CWE-200
static void upnp_event_prepare(struct upnp_event_notify * obj) { static const char notifymsg[] = "NOTIFY %s HTTP/1.1\r\n" "Host: %s%s\r\n" #if (UPNP_VERSION_MAJOR == 1) && (UPNP_VERSION_MINOR == 0) "Content-Type: text/xml\r\n" /* UDA v1.0 */ #else "Content-Type: text/xml; charset=\"utf-8\"\r\n" /* UDA v1.1 or later */ #endif "Content-Length: %d\r\n" "NT: upnp:event\r\n" "NTS: upnp:propchange\r\n" "SID: %s\r\n" "SEQ: %u\r\n" "Connection: close\r\n" "Cache-Control: no-cache\r\n" "\r\n" "%.*s\r\n"; char * xml; int l; if(obj->sub == NULL) { obj->state = EError; return; } switch(obj->sub->service) { case EWanCFG: xml = getVarsWANCfg(&l); break; case EWanIPC: xml = getVarsWANIPCn(&l); break; #ifdef ENABLE_L3F_SERVICE case EL3F: xml = getVarsL3F(&l); break; #endif #ifdef ENABLE_6FC_SERVICE case E6FC: xml = getVars6FC(&l); break; #endif #ifdef ENABLE_DP_SERVICE case EDP: xml = getVarsDP(&l); break; #endif default: xml = NULL; l = 0; } obj->buffersize = 1024; for (;;) { obj->buffer = malloc(obj->buffersize); if(!obj->buffer) { syslog(LOG_ERR, "%s: malloc returned NULL", "upnp_event_prepare"); if(xml) { free(xml); } obj->state = EError; return; } obj->tosend = snprintf(obj->buffer, obj->buffersize, notifymsg, obj->path, obj->addrstr, obj->portstr, l+2, obj->sub->uuid, obj->sub->seq, l, xml); if (obj->tosend < 0) { syslog(LOG_ERR, "%s: snprintf() failed", "upnp_event_prepare"); if(xml) { free(xml); } obj->state = EError; return; } else if (obj->tosend < obj->buffersize) { break; /* the buffer was large enough */ } /* Try again with a buffer big enough */ free(obj->buffer); obj->buffersize = obj->tosend + 1; /* reserve space for the final 0 */ } if(xml) { free(xml); xml = NULL; } obj->state = ESending; }
169,668
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 WallpaperManager::OnDefaultWallpaperDecoded( const base::FilePath& path, const wallpaper::WallpaperLayout layout, std::unique_ptr<user_manager::UserImage>* result_out, MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage> user_image) { if (user_image->image().isNull()) { LOG(ERROR) << "Failed to decode default wallpaper. "; return; } *result_out = std::move(user_image); WallpaperInfo info(path.value(), layout, wallpaper::DEFAULT, base::Time::Now().LocalMidnight()); SetWallpaper((*result_out)->image(), info); } Commit Message: [reland] Do not set default wallpaper unless it should do so. [email protected], [email protected] Bug: 751382 Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda Reviewed-on: https://chromium-review.googlesource.com/619754 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Alexander Alekseev <[email protected]> Reviewed-by: Biao She <[email protected]> Cr-Original-Commit-Position: refs/heads/master@{#498325} Reviewed-on: https://chromium-review.googlesource.com/646430 Cr-Commit-Position: refs/heads/master@{#498982} CWE ID: CWE-200
void WallpaperManager::OnDefaultWallpaperDecoded( const base::FilePath& path, const wallpaper::WallpaperLayout layout, bool update_wallpaper, std::unique_ptr<user_manager::UserImage>* result_out, MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage> user_image) { if (user_image->image().isNull()) { LOG(ERROR) << "Failed to decode default wallpaper. "; return; } *result_out = std::move(user_image); if (update_wallpaper) { WallpaperInfo info(path.value(), layout, wallpaper::DEFAULT, base::Time::Now().LocalMidnight()); SetWallpaper((*result_out)->image(), info); } }
171,967
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 ChromeContentBrowserClient::AppendExtraCommandLineSwitches( CommandLine* command_line, int child_process_id) { #if defined(USE_LINUX_BREAKPAD) if (IsCrashReporterEnabled()) { command_line->AppendSwitchASCII(switches::kEnableCrashReporter, child_process_logging::GetClientId() + "," + base::GetLinuxDistro()); } #elif defined(OS_MACOSX) if (IsCrashReporterEnabled()) { command_line->AppendSwitchASCII(switches::kEnableCrashReporter, child_process_logging::GetClientId()); } #endif // OS_MACOSX if (logging::DialogsAreSuppressed()) command_line->AppendSwitch(switches::kNoErrorDialogs); std::string process_type = command_line->GetSwitchValueASCII(switches::kProcessType); const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); if (process_type == switches::kExtensionProcess || process_type == switches::kRendererProcess) { FilePath user_data_dir = browser_command_line.GetSwitchValuePath(switches::kUserDataDir); if (!user_data_dir.empty()) command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir); #if defined(OS_CHROMEOS) const std::string& login_profile = browser_command_line.GetSwitchValueASCII(switches::kLoginProfile); if (!login_profile.empty()) command_line->AppendSwitchASCII(switches::kLoginProfile, login_profile); #endif RenderProcessHost* process = RenderProcessHost::FromID(child_process_id); PrefService* prefs = process->profile()->GetPrefs(); if (prefs->HasPrefPath(prefs::kDisable3DAPIs) && prefs->GetBoolean(prefs::kDisable3DAPIs)) { command_line->AppendSwitch(switches::kDisable3DAPIs); } if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) || !g_browser_process->safe_browsing_detection_service()) { command_line->AppendSwitch(switches::kDisableClientSidePhishingDetection); } static const char* const kSwitchNames[] = { switches::kAllowHTTPBackgroundPage, switches::kAllowScriptingGallery, switches::kAppsCheckoutURL, switches::kAppsGalleryURL, switches::kCloudPrintServiceURL, switches::kDebugPrint, #if defined(GOOGLE_CHROME_BUILD) && !defined(OS_CHROMEOS) && !defined(OS_MACOSX) switches::kDisablePrintPreview, #else switches::kEnablePrintPreview, #endif switches::kDomAutomationController, switches::kDumpHistogramsOnExit, switches::kEnableClickToPlay, switches::kEnableCrxlessWebApps, switches::kEnableExperimentalExtensionApis, switches::kEnableInBrowserThumbnailing, switches::kEnableIPCFuzzing, switches::kEnableNaCl, switches::kEnableRemoting, switches::kEnableResourceContentSettings, switches::kEnableSearchProviderApiV2, switches::kEnableWatchdog, switches::kExperimentalSpellcheckerFeatures, switches::kMemoryProfiling, switches::kMessageLoopHistogrammer, switches::kPpapiFlashArgs, switches::kPpapiFlashInProcess, switches::kPpapiFlashPath, switches::kPpapiFlashVersion, switches::kProfilingAtStart, switches::kProfilingFile, switches::kProfilingFlush, switches::kRemoteShellPort, switches::kSilentDumpOnDCHECK, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } else if (process_type == switches::kUtilityProcess) { if (browser_command_line.HasSwitch( switches::kEnableExperimentalExtensionApis)) { command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis); } } else if (process_type == switches::kPluginProcess) { static const char* const kSwitchNames[] = { #if defined(OS_CHROMEOS) switches::kLoginProfile, #endif switches::kMemoryProfiling, switches::kSilentDumpOnDCHECK, switches::kUserDataDir, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } else if (process_type == switches::kZygoteProcess) { static const char* const kSwitchNames[] = { switches::kEnableRemoting, switches::kUserDataDir, // Make logs go to the right file. switches::kPpapiFlashInProcess, switches::kPpapiFlashPath, switches::kPpapiFlashVersion, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ChromeContentBrowserClient::AppendExtraCommandLineSwitches( CommandLine* command_line, int child_process_id) { #if defined(USE_LINUX_BREAKPAD) if (IsCrashReporterEnabled()) { command_line->AppendSwitchASCII(switches::kEnableCrashReporter, child_process_logging::GetClientId() + "," + base::GetLinuxDistro()); } #elif defined(OS_MACOSX) if (IsCrashReporterEnabled()) { command_line->AppendSwitchASCII(switches::kEnableCrashReporter, child_process_logging::GetClientId()); } #endif // OS_MACOSX if (logging::DialogsAreSuppressed()) command_line->AppendSwitch(switches::kNoErrorDialogs); std::string process_type = command_line->GetSwitchValueASCII(switches::kProcessType); const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); if (process_type == switches::kExtensionProcess || process_type == switches::kRendererProcess) { FilePath user_data_dir = browser_command_line.GetSwitchValuePath(switches::kUserDataDir); if (!user_data_dir.empty()) command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir); #if defined(OS_CHROMEOS) const std::string& login_profile = browser_command_line.GetSwitchValueASCII(switches::kLoginProfile); if (!login_profile.empty()) command_line->AppendSwitchASCII(switches::kLoginProfile, login_profile); #endif RenderProcessHost* process = RenderProcessHost::FromID(child_process_id); PrefService* prefs = process->profile()->GetPrefs(); if (prefs->HasPrefPath(prefs::kDisable3DAPIs) && prefs->GetBoolean(prefs::kDisable3DAPIs)) { command_line->AppendSwitch(switches::kDisable3DAPIs); } if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) || !g_browser_process->safe_browsing_detection_service()) { command_line->AppendSwitch(switches::kDisableClientSidePhishingDetection); } static const char* const kSwitchNames[] = { switches::kAllowHTTPBackgroundPage, switches::kAllowScriptingGallery, switches::kAppsCheckoutURL, switches::kAppsGalleryURL, switches::kCloudPrintServiceURL, switches::kDebugPrint, #if defined(GOOGLE_CHROME_BUILD) && !defined(OS_CHROMEOS) && !defined(OS_MACOSX) switches::kDisablePrintPreview, #else switches::kEnablePrintPreview, #endif switches::kDomAutomationController, switches::kDumpHistogramsOnExit, switches::kEnableClickToPlay, switches::kEnableCrxlessWebApps, switches::kEnableExperimentalExtensionApis, switches::kEnableInBrowserThumbnailing, switches::kEnableIPCFuzzing, switches::kEnableNaCl, switches::kEnableRemoting, switches::kEnableResourceContentSettings, switches::kEnableSearchProviderApiV2, switches::kEnableWatchdog, switches::kExperimentalSpellcheckerFeatures, switches::kMemoryProfiling, switches::kMessageLoopHistogrammer, switches::kPpapiFlashArgs, switches::kPpapiFlashInProcess, switches::kPpapiFlashPath, switches::kPpapiFlashVersion, switches::kProfilingAtStart, switches::kProfilingFile, switches::kProfilingFlush, switches::kSilentDumpOnDCHECK, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } else if (process_type == switches::kUtilityProcess) { if (browser_command_line.HasSwitch( switches::kEnableExperimentalExtensionApis)) { command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis); } } else if (process_type == switches::kPluginProcess) { static const char* const kSwitchNames[] = { #if defined(OS_CHROMEOS) switches::kLoginProfile, #endif switches::kMemoryProfiling, switches::kSilentDumpOnDCHECK, switches::kUserDataDir, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } else if (process_type == switches::kZygoteProcess) { static const char* const kSwitchNames[] = { switches::kEnableRemoting, switches::kUserDataDir, // Make logs go to the right file. switches::kPpapiFlashInProcess, switches::kPpapiFlashPath, switches::kPpapiFlashVersion, }; command_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); } }
170,322
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_bh_enable(unsigned int cnt) { lockdep_assert_irqs_disabled(); if (softirq_count() == (cnt & SOFTIRQ_MASK)) trace_softirqs_on(_RET_IP_); preempt_count_sub(cnt); } Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters CWE ID: CWE-787
static void __local_bh_enable(unsigned int cnt) { lockdep_assert_irqs_disabled(); if (preempt_count() == cnt) trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip()); if (softirq_count() == (cnt & SOFTIRQ_MASK)) trace_softirqs_on(_RET_IP_); __preempt_count_sub(cnt); }
169,184
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: method_invocation_get_uid (GDBusMethodInvocation *context) { const gchar *sender; PolkitSubject *busname; PolkitSubject *process; uid_t uid; sender = g_dbus_method_invocation_get_sender (context); busname = polkit_system_bus_name_new (sender); process = polkit_system_bus_name_get_process_sync (POLKIT_SYSTEM_BUS_NAME (busname), NULL, NULL); uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (process)); g_object_unref (busname); g_object_unref (process); return uid; } Commit Message: CWE ID: CWE-362
method_invocation_get_uid (GDBusMethodInvocation *context)
165,010
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 NormalPageArena::coalesce() { if (m_promptlyFreedSize < 1024 * 1024) return false; if (getThreadState()->sweepForbidden()) return false; ASSERT(!hasCurrentAllocationArea()); TRACE_EVENT0("blink_gc", "BaseArena::coalesce"); m_freeList.clear(); size_t freedSize = 0; for (NormalPage* page = static_cast<NormalPage*>(m_firstPage); page; page = static_cast<NormalPage*>(page->next())) { Address startOfGap = page->payload(); for (Address headerAddress = startOfGap; headerAddress < page->payloadEnd();) { HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(headerAddress); size_t size = header->size(); ASSERT(size > 0); ASSERT(size < blinkPagePayloadSize()); if (header->isPromptlyFreed()) { ASSERT(size >= sizeof(HeapObjectHeader)); SET_MEMORY_INACCESSIBLE(headerAddress, sizeof(HeapObjectHeader)); CHECK_MEMORY_INACCESSIBLE(headerAddress, size); freedSize += size; headerAddress += size; continue; } if (header->isFree()) { SET_MEMORY_INACCESSIBLE(headerAddress, size < sizeof(FreeListEntry) ? size : sizeof(FreeListEntry)); CHECK_MEMORY_INACCESSIBLE(headerAddress, size); headerAddress += size; continue; } ASSERT(header->checkHeader()); if (startOfGap != headerAddress) addToFreeList(startOfGap, headerAddress - startOfGap); headerAddress += size; startOfGap = headerAddress; } if (startOfGap != page->payloadEnd()) addToFreeList(startOfGap, page->payloadEnd() - startOfGap); } getThreadState()->decreaseAllocatedObjectSize(freedSize); ASSERT(m_promptlyFreedSize == freedSize); m_promptlyFreedSize = 0; return true; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
bool NormalPageArena::coalesce() { if (m_promptlyFreedSize < 1024 * 1024) return false; if (getThreadState()->sweepForbidden()) return false; ASSERT(!hasCurrentAllocationArea()); TRACE_EVENT0("blink_gc", "BaseArena::coalesce"); m_freeList.clear(); size_t freedSize = 0; for (NormalPage* page = static_cast<NormalPage*>(m_firstPage); page; page = static_cast<NormalPage*>(page->next())) { Address startOfGap = page->payload(); for (Address headerAddress = startOfGap; headerAddress < page->payloadEnd();) { HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(headerAddress); size_t size = header->size(); ASSERT(size > 0); ASSERT(size < blinkPagePayloadSize()); if (header->isPromptlyFreed()) { ASSERT(size >= sizeof(HeapObjectHeader)); SET_MEMORY_INACCESSIBLE(headerAddress, sizeof(HeapObjectHeader)); CHECK_MEMORY_INACCESSIBLE(headerAddress, size); freedSize += size; headerAddress += size; continue; } if (header->isFree()) { SET_MEMORY_INACCESSIBLE(headerAddress, size < sizeof(FreeListEntry) ? size : sizeof(FreeListEntry)); CHECK_MEMORY_INACCESSIBLE(headerAddress, size); headerAddress += size; continue; } header->checkHeader(); if (startOfGap != headerAddress) addToFreeList(startOfGap, headerAddress - startOfGap); headerAddress += size; startOfGap = headerAddress; } if (startOfGap != page->payloadEnd()) addToFreeList(startOfGap, page->payloadEnd() - startOfGap); } getThreadState()->decreaseAllocatedObjectSize(freedSize); ASSERT(m_promptlyFreedSize == freedSize); m_promptlyFreedSize = 0; return true; }
172,708
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: uint64 Clipboard::GetSequenceNumber(Buffer buffer) { return 0; } Commit Message: Use XFixes to update the clipboard sequence number. BUG=73478 TEST=manual testing Review URL: http://codereview.chromium.org/8501002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109528 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
uint64 Clipboard::GetSequenceNumber(Buffer buffer) { if (buffer == BUFFER_STANDARD) return SelectionChangeObserver::GetInstance()->clipboard_sequence_number(); else return SelectionChangeObserver::GetInstance()->primary_sequence_number(); }
170,962
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: InspectorPageAgent::ResourceType InspectorPageAgent::CachedResourceType( const Resource& cached_resource) { switch (cached_resource.GetType()) { case Resource::kImage: return InspectorPageAgent::kImageResource; case Resource::kFont: return InspectorPageAgent::kFontResource; case Resource::kMedia: return InspectorPageAgent::kMediaResource; case Resource::kManifest: return InspectorPageAgent::kManifestResource; case Resource::kTextTrack: return InspectorPageAgent::kTextTrackResource; case Resource::kCSSStyleSheet: case Resource::kXSLStyleSheet: return InspectorPageAgent::kStylesheetResource; case Resource::kScript: return InspectorPageAgent::kScriptResource; case Resource::kImportResource: case Resource::kMainResource: return InspectorPageAgent::kDocumentResource; default: break; } return InspectorPageAgent::kOtherResource; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
InspectorPageAgent::ResourceType InspectorPageAgent::CachedResourceType( InspectorPageAgent::ResourceType InspectorPageAgent::ToResourceType( const Resource::Type resource_type) { switch (resource_type) { case Resource::kImage: return InspectorPageAgent::kImageResource; case Resource::kFont: return InspectorPageAgent::kFontResource; case Resource::kMedia: return InspectorPageAgent::kMediaResource; case Resource::kManifest: return InspectorPageAgent::kManifestResource; case Resource::kTextTrack: return InspectorPageAgent::kTextTrackResource; case Resource::kCSSStyleSheet: case Resource::kXSLStyleSheet: return InspectorPageAgent::kStylesheetResource; case Resource::kScript: return InspectorPageAgent::kScriptResource; case Resource::kImportResource: case Resource::kMainResource: return InspectorPageAgent::kDocumentResource; default: break; } return InspectorPageAgent::kOtherResource; }
172,469
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 DevToolsSession::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; host_ = frame_host; for (auto& pair : handlers_) pair.second->SetRenderer(process_, host_); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void DevToolsSession::SetRenderer(RenderProcessHost* process_host, void DevToolsSession::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { process_host_id_ = process_host_id; host_ = frame_host; for (auto& pair : handlers_) pair.second->SetRenderer(process_host_id_, host_); }
172,743
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: BaseShadow::log_except(const char *msg) { ShadowExceptionEvent event; bool exception_already_logged = false; if(!msg) msg = ""; sprintf(event.message, msg); if ( BaseShadow::myshadow_ptr ) { BaseShadow *shadow = BaseShadow::myshadow_ptr; event.recvd_bytes = shadow->bytesSent(); event.sent_bytes = shadow->bytesReceived(); exception_already_logged = shadow->exception_already_logged; if (shadow->began_execution) { event.began_execution = TRUE; } } else { event.recvd_bytes = 0.0; event.sent_bytes = 0.0; } if (!exception_already_logged && !uLog.writeEventNoFsync (&event,NULL)) { ::dprintf (D_ALWAYS, "Unable to log ULOG_SHADOW_EXCEPTION event\n"); } } Commit Message: CWE ID: CWE-134
BaseShadow::log_except(const char *msg) { ShadowExceptionEvent event; bool exception_already_logged = false; if(!msg) msg = ""; sprintf(event.message, "%s", msg); if ( BaseShadow::myshadow_ptr ) { BaseShadow *shadow = BaseShadow::myshadow_ptr; event.recvd_bytes = shadow->bytesSent(); event.sent_bytes = shadow->bytesReceived(); exception_already_logged = shadow->exception_already_logged; if (shadow->began_execution) { event.began_execution = TRUE; } } else { event.recvd_bytes = 0.0; event.sent_bytes = 0.0; } if (!exception_already_logged && !uLog.writeEventNoFsync (&event,NULL)) { ::dprintf (D_ALWAYS, "Unable to log ULOG_SHADOW_EXCEPTION event\n"); } }
165,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: my_object_many_return (MyObject *obj, guint32 *arg0, char **arg1, gint32 *arg2, guint32 *arg3, guint32 *arg4, const char **arg5, GError **error) { *arg0 = 42; *arg1 = g_strdup ("42"); *arg2 = -67; *arg3 = 2; *arg4 = 26; *arg5 = "hello world"; /* Annotation specifies as const */ return TRUE; } Commit Message: CWE ID: CWE-264
my_object_many_return (MyObject *obj, guint32 *arg0, char **arg1, gint32 *arg2, guint32 *arg3, guint32 *arg4, const char **arg5, GError **error)
165,111
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 v8::Local<v8::Value> compileAndRunPrivateScript(ScriptState* scriptState, String scriptClassName, const char* source, size_t size) { v8::Isolate* isolate = scriptState->isolate(); v8::TryCatch block(isolate); String sourceString(source, size); String fileName = scriptClassName + ".js"; v8::Local<v8::Context> context = scriptState->context(); v8::Local<v8::Object> global = context->Global(); v8::Local<v8::Value> privateScriptController = global->Get(context, v8String(isolate, "privateScriptController")) .ToLocalChecked(); RELEASE_ASSERT(privateScriptController->IsUndefined() || privateScriptController->IsObject()); if (privateScriptController->IsObject()) { v8::Local<v8::Object> privateScriptControllerObject = privateScriptController.As<v8::Object>(); v8::Local<v8::Value> importFunctionValue = privateScriptControllerObject->Get(context, v8String(isolate, "import")) .ToLocalChecked(); if (importFunctionValue->IsUndefined()) { v8::Local<v8::Function> function; if (!v8::FunctionTemplate::New(isolate, importFunction) ->GetFunction(context) .ToLocal(&function) || !v8CallBoolean(privateScriptControllerObject->Set( context, v8String(isolate, "import"), function))) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: Setting import function failed. (Class " "name = " << scriptClassName.utf8().data() << ")"; } } } v8::Local<v8::Script> script; if (!v8Call(V8ScriptRunner::compileScript( v8String(isolate, sourceString), fileName, String(), TextPosition::minimumPosition(), isolate, nullptr, nullptr, nullptr, NotSharableCrossOrigin), script, block)) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: Compile failed. (Class name = " << scriptClassName.utf8().data() << ")"; } v8::Local<v8::Value> result; if (!v8Call(V8ScriptRunner::runCompiledInternalScript(isolate, script), result, block)) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: installClass() failed. (Class name = " << scriptClassName.utf8().data() << ")"; } return result; } Commit Message: Don't touch the prototype chain to get the private script controller. Prior to this patch, private scripts attempted to get the "privateScriptController" property off the global object without verifying if the property actually exists on the global. If the property hasn't been set yet, this operation could descend into the prototype chain and potentially return a named property from the WindowProperties object, leading to release asserts and general confusion. BUG=668552 Review-Url: https://codereview.chromium.org/2529163002 Cr-Commit-Position: refs/heads/master@{#434627} CWE ID: CWE-79
static v8::Local<v8::Value> compileAndRunPrivateScript(ScriptState* scriptState, String scriptClassName, const char* source, size_t size) { v8::Isolate* isolate = scriptState->isolate(); v8::TryCatch block(isolate); String sourceString(source, size); String fileName = scriptClassName + ".js"; v8::Local<v8::Context> context = scriptState->context(); v8::Local<v8::Object> global = context->Global(); v8::Local<v8::String> key = v8String(isolate, "privateScriptController"); if (global->HasOwnProperty(context, key).ToChecked()) { v8::Local<v8::Value> privateScriptController = global->Get(context, key).ToLocalChecked(); CHECK(privateScriptController->IsObject()); v8::Local<v8::Object> privateScriptControllerObject = privateScriptController.As<v8::Object>(); v8::Local<v8::Value> importFunctionValue = privateScriptControllerObject->Get(context, v8String(isolate, "import")) .ToLocalChecked(); if (importFunctionValue->IsUndefined()) { v8::Local<v8::Function> function; if (!v8::FunctionTemplate::New(isolate, importFunction) ->GetFunction(context) .ToLocal(&function) || !v8CallBoolean(privateScriptControllerObject->Set( context, v8String(isolate, "import"), function))) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: Setting import function failed. (Class " "name = " << scriptClassName.utf8().data() << ")"; } } } v8::Local<v8::Script> script; if (!v8Call(V8ScriptRunner::compileScript( v8String(isolate, sourceString), fileName, String(), TextPosition::minimumPosition(), isolate, nullptr, nullptr, nullptr, NotSharableCrossOrigin), script, block)) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: Compile failed. (Class name = " << scriptClassName.utf8().data() << ")"; } v8::Local<v8::Value> result; if (!v8Call(V8ScriptRunner::runCompiledInternalScript(isolate, script), result, block)) { dumpV8Message(context, block.Message()); LOG(FATAL) << "Private script error: installClass() failed. (Class name = " << scriptClassName.utf8().data() << ")"; } return result; }
172,450
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 jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cmap_t *cmap = &box->data.cmap; jp2_cmapent_t *ent; unsigned int i; cmap->numchans = (box->datalen) / 4; if (!(cmap->ents = jas_alloc2(cmap->numchans, sizeof(jp2_cmapent_t)))) { return -1; } for (i = 0; i < cmap->numchans; ++i) { ent = &cmap->ents[i]; if (jp2_getuint16(in, &ent->cmptno) || jp2_getuint8(in, &ent->map) || jp2_getuint8(in, &ent->pcol)) { return -1; } } return 0; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476
static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cmap_t *cmap = &box->data.cmap; jp2_cmapent_t *ent; unsigned int i; cmap->ents = 0; cmap->numchans = (box->datalen) / 4; if (!(cmap->ents = jas_alloc2(cmap->numchans, sizeof(jp2_cmapent_t)))) { return -1; } for (i = 0; i < cmap->numchans; ++i) { ent = &cmap->ents[i]; if (jp2_getuint16(in, &ent->cmptno) || jp2_getuint8(in, &ent->map) || jp2_getuint8(in, &ent->pcol)) { return -1; } } return 0; }
168,322
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 ConvertLoopSlice(ModSample &src, ModSample &dest, SmpLength start, SmpLength len, bool loop) { if(!src.HasSampleData()) return; dest.FreeSample(); dest = src; dest.nLength = len; dest.pSample = nullptr; if(!dest.AllocateSample()) { return; } if(len != src.nLength) MemsetZero(dest.cues); std::memcpy(dest.pSample8, src.pSample8 + start, len); dest.uFlags.set(CHN_LOOP, loop); if(loop) { dest.nLoopStart = 0; dest.nLoopEnd = len; } else { dest.nLoopStart = 0; dest.nLoopEnd = 0; } } Commit Message: [Fix] STP: Possible out-of-bounds memory read with malformed STP files (caught with afl-fuzz). git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@9567 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-125
static void ConvertLoopSlice(ModSample &src, ModSample &dest, SmpLength start, SmpLength len, bool loop) { if(!src.HasSampleData() || start >= src.nLength || src.nLength - start < len) { return; } dest.FreeSample(); dest = src; dest.nLength = len; dest.pSample = nullptr; if(!dest.AllocateSample()) { return; } if(len != src.nLength) MemsetZero(dest.cues); std::memcpy(dest.pSample8, src.pSample8 + start, len); dest.uFlags.set(CHN_LOOP, loop); if(loop) { dest.nLoopStart = 0; dest.nLoopEnd = len; } else { dest.nLoopStart = 0; dest.nLoopEnd = 0; } }
169,338
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 decode_getacl(struct xdr_stream *xdr, struct rpc_rqst *req, size_t *acl_len) { __be32 *savep; uint32_t attrlen, bitmap[3] = {0}; struct kvec *iov = req->rq_rcv_buf.head; int status; *acl_len = 0; if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0) goto out; if ((status = decode_attr_bitmap(xdr, bitmap)) != 0) goto out; if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0) goto out; if (unlikely(bitmap[0] & (FATTR4_WORD0_ACL - 1U))) return -EIO; if (likely(bitmap[0] & FATTR4_WORD0_ACL)) { size_t hdrlen; u32 recvd; /* We ignore &savep and don't do consistency checks on * the attr length. Let userspace figure it out.... */ hdrlen = (u8 *)xdr->p - (u8 *)iov->iov_base; recvd = req->rq_rcv_buf.len - hdrlen; if (attrlen > recvd) { dprintk("NFS: server cheating in getattr" " acl reply: attrlen %u > recvd %u\n", attrlen, recvd); return -EINVAL; } xdr_read_pages(xdr, attrlen); *acl_len = attrlen; } else status = -EOPNOTSUPP; out: return status; } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: [email protected] Signed-off-by: Andy Adamson <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> CWE ID: CWE-189
static int decode_getacl(struct xdr_stream *xdr, struct rpc_rqst *req, struct nfs_getaclres *res) { __be32 *savep, *bm_p; uint32_t attrlen, bitmap[3] = {0}; struct kvec *iov = req->rq_rcv_buf.head; int status; res->acl_len = 0; if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0) goto out; bm_p = xdr->p; if ((status = decode_attr_bitmap(xdr, bitmap)) != 0) goto out; if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0) goto out; if (unlikely(bitmap[0] & (FATTR4_WORD0_ACL - 1U))) return -EIO; if (likely(bitmap[0] & FATTR4_WORD0_ACL)) { size_t hdrlen; u32 recvd; /* The bitmap (xdr len + bitmaps) and the attr xdr len words * are stored with the acl data to handle the problem of * variable length bitmaps.*/ xdr->p = bm_p; res->acl_data_offset = be32_to_cpup(bm_p) + 2; res->acl_data_offset <<= 2; /* We ignore &savep and don't do consistency checks on * the attr length. Let userspace figure it out.... */ hdrlen = (u8 *)xdr->p - (u8 *)iov->iov_base; attrlen += res->acl_data_offset; recvd = req->rq_rcv_buf.len - hdrlen; if (attrlen > recvd) { if (res->acl_flags & NFS4_ACL_LEN_REQUEST) { /* getxattr interface called with a NULL buf */ res->acl_len = attrlen; goto out; } dprintk("NFS: acl reply: attrlen %u > recvd %u\n", attrlen, recvd); return -EINVAL; } xdr_read_pages(xdr, attrlen); res->acl_len = attrlen; } else status = -EOPNOTSUPP; out: return status; }
165,719
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 char *create_output_name(unsigned char *fname, unsigned char *dir, int lower, int isunix, int utf8) { unsigned char *p, *name, c, *fe, sep, slash; unsigned int x; sep = (isunix) ? '/' : '\\'; /* the path-seperator */ slash = (isunix) ? '\\' : '/'; /* the other slash */ /* length of filename */ x = strlen((char *) fname); /* UTF8 worst case scenario: tolower() expands all chars from 1 to 3 bytes */ if (utf8) x *= 3; /* length of output directory */ if (dir) x += strlen((char *) dir); if (!(name = (unsigned char *) malloc(x + 2))) { fprintf(stderr, "out of memory!\n"); return NULL; } /* start with blank name */ *name = '\0'; /* add output directory if needed */ if (dir) { strcpy((char *) name, (char *) dir); strcat((char *) name, "/"); } /* remove leading slashes */ while (*fname == sep) fname++; /* copy from fi->filename to new name, converting MS-DOS slashes to UNIX * slashes as we go. Also lowercases characters if needed. */ p = &name[strlen((char *)name)]; fe = &fname[strlen((char *)fname)]; if (utf8) { /* UTF8 translates two-byte unicode characters into 1, 2 or 3 bytes. * %000000000xxxxxxx -> %0xxxxxxx * %00000xxxxxyyyyyy -> %110xxxxx %10yyyyyy * %xxxxyyyyyyzzzzzz -> %1110xxxx %10yyyyyy %10zzzzzz * * Therefore, the inverse is as follows: * First char: * 0x00 - 0x7F = one byte char * 0x80 - 0xBF = invalid * 0xC0 - 0xDF = 2 byte char (next char only 0x80-0xBF is valid) * 0xE0 - 0xEF = 3 byte char (next 2 chars only 0x80-0xBF is valid) * 0xF0 - 0xFF = invalid */ do { if (fname >= fe) { free(name); return NULL; } /* get next UTF8 char */ if ((c = *fname++) < 0x80) x = c; else { if ((c >= 0xC0) && (c < 0xE0)) { x = (c & 0x1F) << 6; x |= *fname++ & 0x3F; } else if ((c >= 0xE0) && (c < 0xF0)) { x = (c & 0xF) << 12; x |= (*fname++ & 0x3F) << 6; x |= *fname++ & 0x3F; } else x = '?'; } /* whatever is the path seperator -> '/' * whatever is the other slash -> '\\' * otherwise, if lower is set, the lowercase version */ if (x == sep) x = '/'; else if (x == slash) x = '\\'; else if (lower) x = (unsigned int) tolower((int) x); /* integer back to UTF8 */ if (x < 0x80) { *p++ = (unsigned char) x; } else if (x < 0x800) { *p++ = 0xC0 | (x >> 6); *p++ = 0x80 | (x & 0x3F); } else { *p++ = 0xE0 | (x >> 12); *p++ = 0x80 | ((x >> 6) & 0x3F); *p++ = 0x80 | (x & 0x3F); } } while (x); } else { /* regular non-utf8 version */ do { c = *fname++; if (c == sep) c = '/'; else if (c == slash) c = '\\'; else if (lower) c = (unsigned char) tolower((int) c); } while ((*p++ = c)); } return (char *) name; } Commit Message: add anti "../" and leading slash protection to chmextract CWE ID: CWE-22
static char *create_output_name(unsigned char *fname, unsigned char *dir, char *create_output_name(char *fname) { char *out, *p; if ((out = malloc(strlen(fname) + 1))) { /* remove leading slashes */ while (*fname == '/' || *fname == '\\') fname++; /* if that removes all characters, just call it "x" */ strcpy(out, (*fname) ? fname : "x"); /* change "../" to "xx/" */ for (p = out; *p; p++) { if (p[0] == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\\')) { p[0] = p[1] = 'x'; } } } return out; }
169,001
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: juniper_pppoe_atm_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; uint16_t extracted_ethertype; l2info.pictype = DLT_JUNIPER_PPPOE_ATM; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; extracted_ethertype = EXTRACT_16BITS(p); /* this DLT contains nothing but raw PPPoE frames, * prepended with a type field*/ if (ethertype_print(ndo, extracted_ethertype, p+ETHERTYPE_LEN, l2info.length-ETHERTYPE_LEN, l2info.caplen-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype)); return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
juniper_pppoe_atm_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; uint16_t extracted_ethertype; l2info.pictype = DLT_JUNIPER_PPPOE_ATM; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; ND_TCHECK2(p[0], 2); extracted_ethertype = EXTRACT_16BITS(p); /* this DLT contains nothing but raw PPPoE frames, * prepended with a type field*/ if (ethertype_print(ndo, extracted_ethertype, p+ETHERTYPE_LEN, l2info.length-ETHERTYPE_LEN, l2info.caplen-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype)); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_pppoe_atm]")); return l2info.header_len; }
167,920
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: xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { xmlParserInputPtr input; xmlBufferPtr buf; int l, c; int count = 0; if ((ctxt == NULL) || (entity == NULL) || ((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) || (entity->content != NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "Reading %s entity content input\n", entity->name); buf = xmlBufferCreate(); if (buf == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } input = xmlNewEntityInputStream(ctxt, entity); if (input == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent input error"); xmlBufferFree(buf); return(-1); } /* * Push the entity as the current input, read char by char * saving to the buffer until the end of the entity or an error */ if (xmlPushInput(ctxt, input) < 0) { xmlBufferFree(buf); return(-1); } GROW; c = CUR_CHAR(l); while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) && (IS_CHAR(c))) { xmlBufferAdd(buf, ctxt->input->cur, l); if (count++ > 100) { count = 0; GROW; } NEXTL(l); c = CUR_CHAR(l); } if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) { xmlPopInput(ctxt); } else if (!IS_CHAR(c)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlLoadEntityContent: invalid char value %d\n", c); xmlBufferFree(buf); return(-1); } entity->content = buf->content; buf->content = NULL; xmlBufferFree(buf); return(0); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { xmlParserInputPtr input; xmlBufferPtr buf; int l, c; int count = 0; if ((ctxt == NULL) || (entity == NULL) || ((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) || (entity->content != NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "Reading %s entity content input\n", entity->name); buf = xmlBufferCreate(); if (buf == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } input = xmlNewEntityInputStream(ctxt, entity); if (input == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent input error"); xmlBufferFree(buf); return(-1); } /* * Push the entity as the current input, read char by char * saving to the buffer until the end of the entity or an error */ if (xmlPushInput(ctxt, input) < 0) { xmlBufferFree(buf); return(-1); } GROW; c = CUR_CHAR(l); while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) && (IS_CHAR(c))) { xmlBufferAdd(buf, ctxt->input->cur, l); if (count++ > 100) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlBufferFree(buf); return(-1); } } NEXTL(l); c = CUR_CHAR(l); } if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) { xmlPopInput(ctxt); } else if (!IS_CHAR(c)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlLoadEntityContent: invalid char value %d\n", c); xmlBufferFree(buf); return(-1); } entity->content = buf->content; buf->content = NULL; xmlBufferFree(buf); return(0); }
171,269
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: GURL GetFileManagerBaseUrl() { return GetFileManagerUrl("/"); } Commit Message: Reland r286968: The CL borrows ShareDialog from Files.app and add it to Gallery. Previous Review URL: https://codereview.chromium.org/431293002 BUG=374667 TEST=manually [email protected], [email protected] Review URL: https://codereview.chromium.org/433733004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286975 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
GURL GetFileManagerBaseUrl() {
171,195
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 DownloadUIAdapterDelegate::OpenItem(const OfflineItem& item, int64_t offline_id) { JNIEnv* env = AttachCurrentThread(); Java_OfflinePageDownloadBridge_openItem( env, ConvertUTF8ToJavaString(env, item.page_url.spec()), offline_id); } Commit Message: Open Offline Pages in CCT from Downloads Home. When the respective feature flag is enabled, offline pages opened from the Downloads Home will use CCT instead of normal tabs. Bug: 824807 Change-Id: I6d968b8b0c51aaeb7f26332c7ada9f927e151a65 Reviewed-on: https://chromium-review.googlesource.com/977321 Commit-Queue: Carlos Knippschild <[email protected]> Reviewed-by: Ted Choc <[email protected]> Reviewed-by: Bernhard Bauer <[email protected]> Reviewed-by: Jian Li <[email protected]> Cr-Commit-Position: refs/heads/master@{#546545} CWE ID: CWE-264
void DownloadUIAdapterDelegate::OpenItem(const OfflineItem& item, int64_t offline_id) { JNIEnv* env = AttachCurrentThread(); Java_OfflinePageDownloadBridge_openItem( env, ConvertUTF8ToJavaString(env, item.page_url.spec()), offline_id, offline_pages::ShouldOfflinePagesInDownloadHomeOpenInCct()); }
171,751
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 tmx_check_pretran(sip_msg_t *msg) { unsigned int chid; unsigned int slotid; int dsize; struct via_param *vbr; str scallid; str scseqmet; str scseqnum; str sftag; str svbranch = {NULL, 0}; pretran_t *it; if(_tmx_ptran_table==NULL) { LM_ERR("pretran hash table not initialized yet\n"); return -1; } if(get_route_type()!=REQUEST_ROUTE) { LM_ERR("invalid usage - not in request route\n"); return -1; } if(msg->first_line.type!=SIP_REQUEST) { LM_ERR("invalid usage - not a sip request\n"); return -1; } if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) { LM_ERR("failed to parse required headers\n"); return -1; } if(msg->cseq==NULL || msg->cseq->parsed==NULL) { LM_ERR("failed to parse cseq headers\n"); return -1; } if(get_cseq(msg)->method_id==METHOD_ACK || get_cseq(msg)->method_id==METHOD_CANCEL) { LM_DBG("no pre-transaction management for ACK or CANCEL\n"); return -1; } if (msg->via1==0) { LM_ERR("failed to get Via header\n"); return -1; } if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) { LM_ERR("failed to get From header\n"); return -1; } if (msg->callid==NULL || msg->callid->body.s==NULL) { LM_ERR("failed to parse callid headers\n"); return -1; } vbr = msg->via1->branch; scallid = msg->callid->body; trim(&scallid); scseqmet = get_cseq(msg)->method; trim(&scseqmet); scseqnum = get_cseq(msg)->number; trim(&scseqnum); sftag = get_from(msg)->tag_value; trim(&sftag); chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len); slotid = chid & (_tmx_ptran_size-1); if(unlikely(_tmx_proc_ptran == NULL)) { _tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t)); if(_tmx_proc_ptran == NULL) { LM_ERR("not enough memory for pretran structure\n"); return -1; } memset(_tmx_proc_ptran, 0, sizeof(pretran_t)); _tmx_proc_ptran->pid = my_pid(); } dsize = scallid.len + scseqnum.len + scseqmet.len + sftag.len + 4; if(likely(vbr!=NULL)) { svbranch = vbr->value; trim(&svbranch); dsize += svbranch.len; } if(dsize<256) dsize = 256; tmx_pretran_unlink(); if(dsize > _tmx_proc_ptran->dbuf.len) { if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s); _tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize); if(_tmx_proc_ptran->dbuf.s==NULL) { LM_ERR("not enough memory for pretran data\n"); return -1; } _tmx_proc_ptran->dbuf.len = dsize; } _tmx_proc_ptran->hid = chid; _tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id; _tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s; memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len); _tmx_proc_ptran->callid.len = scallid.len; _tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0'; _tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s + _tmx_proc_ptran->callid.len + 1; memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len); _tmx_proc_ptran->ftag.len = sftag.len; _tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0'; _tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s + _tmx_proc_ptran->ftag.len + 1; memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len); _tmx_proc_ptran->cseqnum.len = scseqnum.len; _tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0'; _tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s + _tmx_proc_ptran->cseqnum.len + 1; memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len); _tmx_proc_ptran->cseqmet.len = scseqmet.len; _tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0'; if(likely(vbr!=NULL)) { _tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s + _tmx_proc_ptran->cseqmet.len + 1; memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len); _tmx_proc_ptran->vbranch.len = svbranch.len; _tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0'; } else { _tmx_proc_ptran->vbranch.s = NULL; _tmx_proc_ptran->vbranch.len = 0; } lock_get(&_tmx_ptran_table[slotid].lock); it = _tmx_ptran_table[slotid].plist; tmx_pretran_link_safe(slotid); for(; it!=NULL; it=it->next) { if(_tmx_proc_ptran->hid != it->hid || _tmx_proc_ptran->cseqmetid != it->cseqmetid || _tmx_proc_ptran->callid.len != it->callid.len || _tmx_proc_ptran->ftag.len != it->ftag.len || _tmx_proc_ptran->cseqmet.len != it->cseqmet.len || _tmx_proc_ptran->cseqnum.len != it->cseqnum.len) continue; if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) { if(_tmx_proc_ptran->vbranch.len != it->vbranch.len) continue; /* shortcut - check last char in Via branch * - kamailio/ser adds there branch index => in case of paralel * forking by previous hop, catch it here quickly */ if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1] != it->vbranch.s[it->vbranch.len-1]) continue; if(memcmp(_tmx_proc_ptran->vbranch.s, it->vbranch.s, it->vbranch.len)!=0) continue; /* shall stop by matching magic cookie? * if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN * && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) { * LM_DBG("rfc3261 cookie found in Via branch\n"); * } */ } if(memcmp(_tmx_proc_ptran->callid.s, it->callid.s, it->callid.len)!=0 || memcmp(_tmx_proc_ptran->ftag.s, it->ftag.s, it->ftag.len)!=0 || memcmp(_tmx_proc_ptran->cseqnum.s, it->cseqnum.s, it->cseqnum.len)!=0) continue; if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF) && memcmp(_tmx_proc_ptran->cseqmet.s, it->cseqmet.s, it->cseqmet.len)!=0) continue; LM_DBG("matched another pre-transaction by pid %d for [%.*s]\n", it->pid, it->callid.len, it->callid.s); lock_release(&_tmx_ptran_table[slotid].lock); return 1; } lock_release(&_tmx_ptran_table[slotid].lock); return 0; } Commit Message: tmx: allocate space to store ending 0 for branch value - reported by Alfred Farrugia and Sandro Gauci CWE ID: CWE-119
int tmx_check_pretran(sip_msg_t *msg) { unsigned int chid; unsigned int slotid; int dsize; struct via_param *vbr; str scallid; str scseqmet; str scseqnum; str sftag; str svbranch = {NULL, 0}; pretran_t *it; if(_tmx_ptran_table==NULL) { LM_ERR("pretran hash table not initialized yet\n"); return -1; } if(get_route_type()!=REQUEST_ROUTE) { LM_ERR("invalid usage - not in request route\n"); return -1; } if(msg->first_line.type!=SIP_REQUEST) { LM_ERR("invalid usage - not a sip request\n"); return -1; } if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) { LM_ERR("failed to parse required headers\n"); return -1; } if(msg->cseq==NULL || msg->cseq->parsed==NULL) { LM_ERR("failed to parse cseq headers\n"); return -1; } if(get_cseq(msg)->method_id==METHOD_ACK || get_cseq(msg)->method_id==METHOD_CANCEL) { LM_DBG("no pre-transaction management for ACK or CANCEL\n"); return -1; } if (msg->via1==0) { LM_ERR("failed to get Via header\n"); return -1; } if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) { LM_ERR("failed to get From header\n"); return -1; } if (msg->callid==NULL || msg->callid->body.s==NULL) { LM_ERR("failed to parse callid headers\n"); return -1; } vbr = msg->via1->branch; scallid = msg->callid->body; trim(&scallid); scseqmet = get_cseq(msg)->method; trim(&scseqmet); scseqnum = get_cseq(msg)->number; trim(&scseqnum); sftag = get_from(msg)->tag_value; trim(&sftag); chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len); slotid = chid & (_tmx_ptran_size-1); if(unlikely(_tmx_proc_ptran == NULL)) { _tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t)); if(_tmx_proc_ptran == NULL) { LM_ERR("not enough memory for pretran structure\n"); return -1; } memset(_tmx_proc_ptran, 0, sizeof(pretran_t)); _tmx_proc_ptran->pid = my_pid(); } dsize = scallid.len + scseqnum.len + scseqmet.len + sftag.len + 4; if(likely(vbr!=NULL)) { svbranch = vbr->value; trim(&svbranch); dsize += svbranch.len + 1; } if(dsize<256) dsize = 256; tmx_pretran_unlink(); if(dsize > _tmx_proc_ptran->dbuf.len) { if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s); _tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize); if(_tmx_proc_ptran->dbuf.s==NULL) { LM_ERR("not enough memory for pretran data\n"); return -1; } _tmx_proc_ptran->dbuf.len = dsize; } _tmx_proc_ptran->hid = chid; _tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id; _tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s; memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len); _tmx_proc_ptran->callid.len = scallid.len; _tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0'; _tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s + _tmx_proc_ptran->callid.len + 1; memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len); _tmx_proc_ptran->ftag.len = sftag.len; _tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0'; _tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s + _tmx_proc_ptran->ftag.len + 1; memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len); _tmx_proc_ptran->cseqnum.len = scseqnum.len; _tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0'; _tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s + _tmx_proc_ptran->cseqnum.len + 1; memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len); _tmx_proc_ptran->cseqmet.len = scseqmet.len; _tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0'; if(likely(vbr!=NULL)) { _tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s + _tmx_proc_ptran->cseqmet.len + 1; memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len); _tmx_proc_ptran->vbranch.len = svbranch.len; _tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0'; } else { _tmx_proc_ptran->vbranch.s = NULL; _tmx_proc_ptran->vbranch.len = 0; } lock_get(&_tmx_ptran_table[slotid].lock); it = _tmx_ptran_table[slotid].plist; tmx_pretran_link_safe(slotid); for(; it!=NULL; it=it->next) { if(_tmx_proc_ptran->hid != it->hid || _tmx_proc_ptran->cseqmetid != it->cseqmetid || _tmx_proc_ptran->callid.len != it->callid.len || _tmx_proc_ptran->ftag.len != it->ftag.len || _tmx_proc_ptran->cseqmet.len != it->cseqmet.len || _tmx_proc_ptran->cseqnum.len != it->cseqnum.len) continue; if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) { if(_tmx_proc_ptran->vbranch.len != it->vbranch.len) continue; /* shortcut - check last char in Via branch * - kamailio/ser adds there branch index => in case of paralel * forking by previous hop, catch it here quickly */ if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1] != it->vbranch.s[it->vbranch.len-1]) continue; if(memcmp(_tmx_proc_ptran->vbranch.s, it->vbranch.s, it->vbranch.len)!=0) continue; /* shall stop by matching magic cookie? * if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN * && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) { * LM_DBG("rfc3261 cookie found in Via branch\n"); * } */ } if(memcmp(_tmx_proc_ptran->callid.s, it->callid.s, it->callid.len)!=0 || memcmp(_tmx_proc_ptran->ftag.s, it->ftag.s, it->ftag.len)!=0 || memcmp(_tmx_proc_ptran->cseqnum.s, it->cseqnum.s, it->cseqnum.len)!=0) continue; if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF) && memcmp(_tmx_proc_ptran->cseqmet.s, it->cseqmet.s, it->cseqmet.len)!=0) continue; LM_DBG("matched another pre-transaction by pid %d for [%.*s]\n", it->pid, it->callid.len, it->callid.s); lock_release(&_tmx_ptran_table[slotid].lock); return 1; } lock_release(&_tmx_ptran_table[slotid].lock); return 0; }
169,271
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: process_demand_active(STREAM s) { uint8 type; uint16 len_src_descriptor, len_combined_caps; /* at this point we need to ensure that we have ui created */ rd_create_ui(); in_uint32_le(s, g_rdp_shareid); in_uint16_le(s, len_src_descriptor); in_uint16_le(s, len_combined_caps); in_uint8s(s, len_src_descriptor); logger(Protocol, Debug, "process_demand_active(), shareid=0x%x", g_rdp_shareid); rdp_process_server_caps(s, len_combined_caps); rdp_send_confirm_active(); rdp_send_synchronise(); rdp_send_control(RDP_CTL_COOPERATE); rdp_send_control(RDP_CTL_REQUEST_CONTROL); rdp_recv(&type); /* RDP_PDU_SYNCHRONIZE */ rdp_recv(&type); /* RDP_CTL_COOPERATE */ rdp_recv(&type); /* RDP_CTL_GRANT_CONTROL */ rdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0, g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0); if (g_rdp_version >= RDP_V5) { rdp_enum_bmpcache2(); rdp_send_fonts(3); } else { rdp_send_fonts(1); rdp_send_fonts(2); } rdp_recv(&type); /* RDP_PDU_UNKNOWN 0x28 (Fonts?) */ reset_order_state(); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
process_demand_active(STREAM s) { uint8 type; uint16 len_src_descriptor, len_combined_caps; struct stream packet = *s; /* at this point we need to ensure that we have ui created */ rd_create_ui(); in_uint32_le(s, g_rdp_shareid); in_uint16_le(s, len_src_descriptor); in_uint16_le(s, len_combined_caps); if (!s_check_rem(s, len_src_descriptor)) { rdp_protocol_error("rdp_demand_active(), consume of source descriptor from stream would overrun", &packet); } in_uint8s(s, len_src_descriptor); logger(Protocol, Debug, "process_demand_active(), shareid=0x%x", g_rdp_shareid); rdp_process_server_caps(s, len_combined_caps); rdp_send_confirm_active(); rdp_send_synchronise(); rdp_send_control(RDP_CTL_COOPERATE); rdp_send_control(RDP_CTL_REQUEST_CONTROL); rdp_recv(&type); /* RDP_PDU_SYNCHRONIZE */ rdp_recv(&type); /* RDP_CTL_COOPERATE */ rdp_recv(&type); /* RDP_CTL_GRANT_CONTROL */ rdp_send_input(0, RDP_INPUT_SYNCHRONIZE, 0, g_numlock_sync ? ui_get_numlock_state(read_keyboard_state()) : 0, 0); if (g_rdp_version >= RDP_V5) { rdp_enum_bmpcache2(); rdp_send_fonts(3); } else { rdp_send_fonts(1); rdp_send_fonts(2); } rdp_recv(&type); /* RDP_PDU_UNKNOWN 0x28 (Fonts?) */ reset_order_state(); }
169,803
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_translate_to_linux(uint8_t *newName, uint8_t *udfName, int udfLen, uint8_t *fidName, int fidNameLen) { int index, newIndex = 0, needsCRC = 0; int extIndex = 0, newExtIndex = 0, hasExt = 0; unsigned short valueCRC; uint8_t curr; if (udfName[0] == '.' && (udfLen == 1 || (udfLen == 2 && udfName[1] == '.'))) { needsCRC = 1; newIndex = udfLen; memcpy(newName, udfName, udfLen); } else { for (index = 0; index < udfLen; index++) { curr = udfName[index]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (index + 1 < udfLen && (udfName[index + 1] == '/' || udfName[index + 1] == 0)) index++; } if (curr == EXT_MARK && (udfLen - index - 1) <= EXT_SIZE) { if (udfLen == index + 1) hasExt = 0; else { hasExt = 1; extIndex = index; newExtIndex = newIndex; } } if (newIndex < 256) newName[newIndex++] = curr; else needsCRC = 1; } } if (needsCRC) { uint8_t ext[EXT_SIZE]; int localExtIndex = 0; if (hasExt) { int maxFilenameLen; for (index = 0; index < EXT_SIZE && extIndex + index + 1 < udfLen; index++) { curr = udfName[extIndex + index + 1]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (extIndex + index + 2 < udfLen && (index + 1 < EXT_SIZE && (udfName[extIndex + index + 2] == '/' || udfName[extIndex + index + 2] == 0))) index++; } ext[localExtIndex++] = curr; } maxFilenameLen = 250 - localExtIndex; if (newIndex > maxFilenameLen) newIndex = maxFilenameLen; else newIndex = newExtIndex; } else if (newIndex > 250) newIndex = 250; newName[newIndex++] = CRC_MARK; valueCRC = crc_itu_t(0, fidName, fidNameLen); newName[newIndex++] = hex_asc_upper_hi(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_lo(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_hi(valueCRC); newName[newIndex++] = hex_asc_upper_lo(valueCRC); if (hasExt) { newName[newIndex++] = EXT_MARK; for (index = 0; index < localExtIndex; index++) newName[newIndex++] = ext[index]; } } return newIndex; } 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: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-17
static int udf_translate_to_linux(uint8_t *newName, uint8_t *udfName, static int udf_translate_to_linux(uint8_t *newName, int newLen, uint8_t *udfName, int udfLen, uint8_t *fidName, int fidNameLen) { int index, newIndex = 0, needsCRC = 0; int extIndex = 0, newExtIndex = 0, hasExt = 0; unsigned short valueCRC; uint8_t curr; if (udfName[0] == '.' && (udfLen == 1 || (udfLen == 2 && udfName[1] == '.'))) { needsCRC = 1; newIndex = udfLen; memcpy(newName, udfName, udfLen); } else { for (index = 0; index < udfLen; index++) { curr = udfName[index]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (index + 1 < udfLen && (udfName[index + 1] == '/' || udfName[index + 1] == 0)) index++; } if (curr == EXT_MARK && (udfLen - index - 1) <= EXT_SIZE) { if (udfLen == index + 1) hasExt = 0; else { hasExt = 1; extIndex = index; newExtIndex = newIndex; } } if (newIndex < newLen) newName[newIndex++] = curr; else needsCRC = 1; } } if (needsCRC) { uint8_t ext[EXT_SIZE]; int localExtIndex = 0; if (hasExt) { int maxFilenameLen; for (index = 0; index < EXT_SIZE && extIndex + index + 1 < udfLen; index++) { curr = udfName[extIndex + index + 1]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (extIndex + index + 2 < udfLen && (index + 1 < EXT_SIZE && (udfName[extIndex + index + 2] == '/' || udfName[extIndex + index + 2] == 0))) index++; } ext[localExtIndex++] = curr; } maxFilenameLen = newLen - CRC_LEN - localExtIndex; if (newIndex > maxFilenameLen) newIndex = maxFilenameLen; else newIndex = newExtIndex; } else if (newIndex > newLen - CRC_LEN) newIndex = newLen - CRC_LEN; newName[newIndex++] = CRC_MARK; valueCRC = crc_itu_t(0, fidName, fidNameLen); newName[newIndex++] = hex_asc_upper_hi(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_lo(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_hi(valueCRC); newName[newIndex++] = hex_asc_upper_lo(valueCRC); if (hasExt) { newName[newIndex++] = EXT_MARK; for (index = 0; index < localExtIndex; index++) newName[newIndex++] = ext[index]; } } return newIndex; }
166,760
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: Block::Block(long long start, long long size_, long long discard_padding) : m_start(start), m_size(size_), m_track(0), m_timecode(-1), m_flags(0), m_frames(NULL), m_frame_count(-1), m_discard_padding(discard_padding) { } 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
Block::Block(long long start, long long size_, long long discard_padding) :
174,240
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 av_reallocp_array(void *ptr, size_t nmemb, size_t size) { void **ptrptr = ptr; *ptrptr = av_realloc_f(*ptrptr, nmemb, size); if (!*ptrptr && !(nmemb && size)) return AVERROR(ENOMEM); return 0; } Commit Message: avutil/mem: Fix flipped condition Fixes return code and later null pointer dereference Found-by: Laurent Butti <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID:
int av_reallocp_array(void *ptr, size_t nmemb, size_t size) { void **ptrptr = ptr; *ptrptr = av_realloc_f(*ptrptr, nmemb, size); if (!*ptrptr && nmemb && size) return AVERROR(ENOMEM); return 0; }
165,995
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: INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits) { stream_t *ps_stream = (stream_t *)pv_ctxt; if (ps_stream->u4_offset < ps_stream->u4_max_offset) { FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned) } return; } Commit Message: Fixed out of bound read in flush_bits Bug: 28168413 Change-Id: I3db5432a08daf665e160c0dab2d1928a576418b4 CWE ID: CWE-200
INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits) { stream_t *ps_stream = (stream_t *)pv_ctxt; if ((ps_stream->u4_offset + 64) < ps_stream->u4_max_offset) { FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned) } else { UWORD32 u4_temp; if (((ps_stream->u4_offset & 0x1f) + u4_no_of_bits) >= 32) { ps_stream->u4_buf = ps_stream->u4_buf_nxt; ps_stream->u4_buf_nxt = 0; } ps_stream->u4_offset += u4_no_of_bits; } return; }
173,549
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: KeyboardLibrary* CrosLibrary::GetKeyboardLibrary() { return keyboard_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
KeyboardLibrary* CrosLibrary::GetKeyboardLibrary() {
170,624
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 DownloadItemImpl::OnDownloadCompleting(DownloadFileManager* file_manager) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); VLOG(20) << __FUNCTION__ << "()" << " needs rename = " << NeedsRename() << " " << DebugString(true); DCHECK(!GetTargetName().empty()); DCHECK_NE(DANGEROUS, GetSafetyState()); DCHECK(file_manager); bool should_overwrite = (GetTargetDisposition() != DownloadItem::TARGET_DISPOSITION_UNIQUIFY); DownloadFileManager::RenameCompletionCallback callback = base::Bind(&DownloadItemImpl::OnDownloadRenamedToFinalName, weak_ptr_factory_.GetWeakPtr(), base::Unretained(file_manager)); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&DownloadFileManager::RenameCompletingDownloadFile, file_manager, GetGlobalId(), GetTargetFilePath(), should_overwrite, callback)); } else { Completed(); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&DownloadFileManager::CompleteDownload, file_manager, download_id_)); } } Commit Message: Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 [email protected] Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void DownloadItemImpl::OnDownloadCompleting(DownloadFileManager* file_manager) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); VLOG(20) << __FUNCTION__ << "()" << " needs rename = " << NeedsRename() << " " << DebugString(true); DCHECK(!GetTargetName().empty()); DCHECK_NE(DANGEROUS, GetSafetyState()); DCHECK(file_manager); // Rename the Download file and call back to OnDownloadRenamedToFinalName. bool should_overwrite = (GetTargetDisposition() != DownloadItem::TARGET_DISPOSITION_UNIQUIFY); DownloadFileManager::RenameCompletionCallback callback = base::Bind(&DownloadItemImpl::OnDownloadRenamedToFinalName, weak_ptr_factory_.GetWeakPtr(), base::Unretained(file_manager)); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&DownloadFileManager::RenameDownloadFile, file_manager, GetGlobalId(), GetTargetFilePath(), should_overwrite, callback)); } else { // Complete the download and release the DownloadFile. BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&DownloadFileManager::CompleteDownload, file_manager, GetGlobalId(), base::Bind(&DownloadItemImpl::OnDownloadFileReleased, weak_ptr_factory_.GetWeakPtr()))); } }
170,882
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: long Chapters::Edition::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) // Atom ID { status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Chapters::Edition::Parse( Segment* const pSegment = pChapters->m_pSegment; if (pSegment == NULL) // weird return -1; const SegmentInfo* const pInfo = pSegment->GetInfo(); if (pInfo == NULL) return -1; const long long timecode_scale = pInfo->GetTimeCodeScale(); if (timecode_scale < 1) // weird return -1; if (timecode < 0) return -1; const long long result = timecode_scale * timecode; return result; } long Chapters::Atom::ParseDisplay(IMkvReader* pReader, long long pos, long long size) { if (!ExpandDisplaysArray()) return -1; Display& d = m_displays[m_displays_count++]; d.Init(); return d.Parse(pReader, pos, size); } bool Chapters::Atom::ExpandDisplaysArray() { if (m_displays_size > m_displays_count) return true; // nothing else to do const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size; Display* const displays = new (std::nothrow) Display[size]; if (displays == NULL) return false; for (int idx = 0; idx < m_displays_count; ++idx) { m_displays[idx].ShallowCopy(displays[idx]); } delete[] m_displays; m_displays = displays; m_displays_size = size; return true; } Chapters::Display::Display() {} Chapters::Display::~Display() {} const char* Chapters::Display::GetString() const { return m_string; } const char* Chapters::Display::GetLanguage() const { return m_language; } const char* Chapters::Display::GetCountry() const { return m_country; } void Chapters::Display::Init() { m_string = NULL; m_language = NULL; m_country = NULL; } void Chapters::Display::ShallowCopy(Display& rhs) const { rhs.m_string = m_string; rhs.m_language = m_language; rhs.m_country = m_country; } void Chapters::Display::Clear() { delete[] m_string; m_string = NULL; delete[] m_language; m_language = NULL; delete[] m_country; m_country = NULL; } long Chapters::Display::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x05) { // ChapterString ID status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) { // ChapterLanguage ID status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) { // ChapterCountry ID status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; }
174,401
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 GpuDataManager::UpdateGpuInfo(const GPUInfo& gpu_info) { { base::AutoLock auto_lock(gpu_info_lock_); if (!gpu_info_.Merge(gpu_info)) return; RunGpuInfoUpdateCallbacks(); content::GetContentClient()->SetGpuInfo(gpu_info_); } UpdateGpuFeatureFlags(); } Commit Message: Fix a lock re-entry bug in GpuDataManager::UpdateGpuInfo. The issue is that the registered callbacks could request GPUInfo, so they could re-enter the lock. Therefore, we should release the lock before we run through callbacks. BUG=84805 TEST=the issue in 84805 is gone. Review URL: http://codereview.chromium.org/7054063 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87898 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GpuDataManager::UpdateGpuInfo(const GPUInfo& gpu_info) { { base::AutoLock auto_lock(gpu_info_lock_); if (!gpu_info_.Merge(gpu_info)) return; } RunGpuInfoUpdateCallbacks(); { base::AutoLock auto_lock(gpu_info_lock_); content::GetContentClient()->SetGpuInfo(gpu_info_); } UpdateGpuFeatureFlags(); }
170,410
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 RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = rnd.Rand8() - rnd.Rand8(); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[j]); } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED(16, int16_t, input_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]); for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = (rnd.Rand16() & mask_) - (rnd.Rand16() & mask_); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[j]); } }
174,520
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 mount *clone_mnt(struct mount *old, struct dentry *root, int flag) { struct super_block *sb = old->mnt.mnt_sb; struct mount *mnt; int err; mnt = alloc_vfsmnt(old->mnt_devname); if (!mnt) return ERR_PTR(-ENOMEM); if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE)) mnt->mnt_group_id = 0; /* not a peer of original */ else mnt->mnt_group_id = old->mnt_group_id; if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) { err = mnt_alloc_group_id(mnt); if (err) goto out_free; } mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~MNT_WRITE_HOLD; atomic_inc(&sb->s_active); mnt->mnt.mnt_sb = sb; mnt->mnt.mnt_root = dget(root); mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; br_write_lock(&vfsmount_lock); list_add_tail(&mnt->mnt_instance, &sb->s_mounts); br_write_unlock(&vfsmount_lock); if ((flag & CL_SLAVE) || ((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) { list_add(&mnt->mnt_slave, &old->mnt_slave_list); mnt->mnt_master = old; CLEAR_MNT_SHARED(mnt); } else if (!(flag & CL_PRIVATE)) { if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old)) list_add(&mnt->mnt_share, &old->mnt_share); if (IS_MNT_SLAVE(old)) list_add(&mnt->mnt_slave, &old->mnt_slave); mnt->mnt_master = old->mnt_master; } if (flag & CL_MAKE_SHARED) set_mnt_shared(mnt); /* stick the duplicate mount on the same expiry list * as the original if that was on one */ if (flag & CL_EXPIRE) { if (!list_empty(&old->mnt_expire)) list_add(&mnt->mnt_expire, &old->mnt_expire); } return mnt; out_free: free_vfsmnt(mnt); return ERR_PTR(err); } Commit Message: vfs: Carefully propogate mounts across user namespaces As a matter of policy MNT_READONLY should not be changable if the original mounter had more privileges than creator of the mount namespace. Add the flag CL_UNPRIVILEGED to note when we are copying a mount from a mount namespace that requires more privileges to a mount namespace that requires fewer privileges. When the CL_UNPRIVILEGED flag is set cause clone_mnt to set MNT_NO_REMOUNT if any of the mnt flags that should never be changed are set. This protects both mount propagation and the initial creation of a less privileged mount namespace. Cc: [email protected] Acked-by: Serge Hallyn <[email protected]> Reported-by: Andy Lutomirski <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-264
static struct mount *clone_mnt(struct mount *old, struct dentry *root, int flag) { struct super_block *sb = old->mnt.mnt_sb; struct mount *mnt; int err; mnt = alloc_vfsmnt(old->mnt_devname); if (!mnt) return ERR_PTR(-ENOMEM); if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE)) mnt->mnt_group_id = 0; /* not a peer of original */ else mnt->mnt_group_id = old->mnt_group_id; if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) { err = mnt_alloc_group_id(mnt); if (err) goto out_free; } mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~MNT_WRITE_HOLD; /* Don't allow unprivileged users to change mount flags */ if ((flag & CL_UNPRIVILEGED) && (mnt->mnt.mnt_flags & MNT_READONLY)) mnt->mnt.mnt_flags |= MNT_LOCK_READONLY; atomic_inc(&sb->s_active); mnt->mnt.mnt_sb = sb; mnt->mnt.mnt_root = dget(root); mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; br_write_lock(&vfsmount_lock); list_add_tail(&mnt->mnt_instance, &sb->s_mounts); br_write_unlock(&vfsmount_lock); if ((flag & CL_SLAVE) || ((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) { list_add(&mnt->mnt_slave, &old->mnt_slave_list); mnt->mnt_master = old; CLEAR_MNT_SHARED(mnt); } else if (!(flag & CL_PRIVATE)) { if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old)) list_add(&mnt->mnt_share, &old->mnt_share); if (IS_MNT_SLAVE(old)) list_add(&mnt->mnt_slave, &old->mnt_slave); mnt->mnt_master = old->mnt_master; } if (flag & CL_MAKE_SHARED) set_mnt_shared(mnt); /* stick the duplicate mount on the same expiry list * as the original if that was on one */ if (flag & CL_EXPIRE) { if (!list_empty(&old->mnt_expire)) list_add(&mnt->mnt_expire, &old->mnt_expire); } return mnt; out_free: free_vfsmnt(mnt); return ERR_PTR(err); }
166,094
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: NavigationPolicy EffectiveNavigationPolicy(NavigationPolicy policy, const WebInputEvent* current_event, const WebWindowFeatures& features) { if (policy == kNavigationPolicyIgnore) return GetNavigationPolicy(current_event, features); if (policy == kNavigationPolicyNewBackgroundTab && GetNavigationPolicy(current_event, features) != kNavigationPolicyNewBackgroundTab && !UIEventWithKeyState::NewTabModifierSetFromIsolatedWorld()) { return kNavigationPolicyNewForegroundTab; } return policy; } Commit Message: Only allow downloading in response to real keyboard modifiers BUG=848531 Change-Id: I97554c8d312243b55647f1376945aee32dbd95bf Reviewed-on: https://chromium-review.googlesource.com/1082216 Reviewed-by: Mike West <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#564051} CWE ID:
NavigationPolicy EffectiveNavigationPolicy(NavigationPolicy policy, if (policy == kNavigationPolicyNewBackgroundTab && user_policy != kNavigationPolicyNewBackgroundTab && !UIEventWithKeyState::NewTabModifierSetFromIsolatedWorld()) { // Don't allow background tabs to be opened via script setting the // event modifiers. return kNavigationPolicyNewForegroundTab; } if (policy == kNavigationPolicyDownload && user_policy != kNavigationPolicyDownload) { // Don't allow downloads to be triggered via script setting the event // modifiers. return kNavigationPolicyNewForegroundTab; } return policy; }
173,192
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: ScriptPromise Bluetooth::requestLEScan(ScriptState* script_state, const BluetoothLEScanOptions* options, ExceptionState& exception_state) { ExecutionContext* context = ExecutionContext::From(script_state); DCHECK(context); context->AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kInfo, "Web Bluetooth Scanning is experimental on this platform. See " "https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/" "implementation-status.md")); CHECK(context->IsSecureContext()); auto& doc = *To<Document>(context); auto* frame = doc.GetFrame(); if (!frame) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Document not active")); } if (!LocalFrame::HasTransientUserActivation(frame)) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Must be handling a user gesture to show a permission request.")); } if (!service_) { frame->GetInterfaceProvider().GetInterface(mojo::MakeRequest( &service_, context->GetTaskRunner(TaskType::kMiscPlatformAPI))); } auto scan_options = mojom::blink::WebBluetoothRequestLEScanOptions::New(); ConvertRequestLEScanOptions(options, scan_options, exception_state); if (exception_state.HadException()) return ScriptPromise(); Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url()); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); mojom::blink::WebBluetoothScanClientAssociatedPtrInfo client; mojo::BindingId id = client_bindings_.AddBinding( this, mojo::MakeRequest(&client), context->GetTaskRunner(TaskType::kMiscPlatformAPI)); service_->RequestScanningStart( std::move(client), std::move(scan_options), WTF::Bind(&Bluetooth::RequestScanningCallback, WrapPersistent(this), WrapPersistent(resolver), id)); return promise; } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
ScriptPromise Bluetooth::requestLEScan(ScriptState* script_state, const BluetoothLEScanOptions* options, ExceptionState& exception_state) { ExecutionContext* context = ExecutionContext::From(script_state); DCHECK(context); context->AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kInfo, "Web Bluetooth Scanning is experimental on this platform. See " "https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/" "implementation-status.md")); CHECK(context->IsSecureContext()); auto& doc = *To<Document>(context); auto* frame = doc.GetFrame(); if (!frame) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Document not active")); } if (!LocalFrame::HasTransientUserActivation(frame)) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Must be handling a user gesture to show a permission request.")); } EnsureServiceConnection(); auto scan_options = mojom::blink::WebBluetoothRequestLEScanOptions::New(); ConvertRequestLEScanOptions(options, scan_options, exception_state); if (exception_state.HadException()) return ScriptPromise(); Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url()); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); mojom::blink::WebBluetoothScanClientAssociatedPtrInfo client; mojo::BindingId id = client_bindings_.AddBinding( this, mojo::MakeRequest(&client), context->GetTaskRunner(TaskType::kMiscPlatformAPI)); service_->RequestScanningStart( std::move(client), std::move(scan_options), WTF::Bind(&Bluetooth::RequestScanningCallback, WrapPersistent(this), WrapPersistent(resolver), id)); return promise; }
172,449
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 const char *parse_string(cJSON *item,const char *str,const char **ep) { const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; if (*str!='\"') {*ep=str;return 0;} /* not a string! */ while (*end_ptr!='\"' && *end_ptr && ++len) if (*end_ptr++ == '\\') end_ptr++; /* Skip escaped quotes. */ out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ if (!out) return 0; item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */ item->type=cJSON_String; ptr=str+1;ptr2=out; while (ptr < end_ptr) { if (*ptr!='\\') *ptr2++=*ptr++; else { ptr++; switch (*ptr) { case 'b': *ptr2++='\b'; break; case 'f': *ptr2++='\f'; break; case 'n': *ptr2++='\n'; break; case 'r': *ptr2++='\r'; break; case 't': *ptr2++='\t'; break; case 'u': /* transcode utf16 to utf8. */ uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */ if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */ if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ { if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */ if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */ uc2=parse_hex4(ptr+3);ptr+=6; if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */ uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); } len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; switch (len) { case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 1: *--ptr2 =(uc | firstByteMark[len]); } ptr2+=len; break; default: *ptr2++=*ptr; break; } ptr++; } } *ptr2=0; if (*ptr=='\"') ptr++; return ptr; } Commit Message: fix buffer overflow (#30) CWE ID: CWE-125
static const char *parse_string(cJSON *item,const char *str,const char **ep) { const char *ptr=str+1,*end_ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; if (*str!='\"') {*ep=str;return 0;} /* not a string! */ while (*end_ptr!='\"' && *end_ptr && ++len) { if (*end_ptr++ == '\\') { if (*end_ptr == '\0') { /* prevent buffer overflow when last input character is a backslash */ return 0; } end_ptr++; /* Skip escaped quotes. */ } } out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ if (!out) return 0; item->valuestring=out; /* assign here so out will be deleted during cJSON_Delete() later */ item->type=cJSON_String; ptr=str+1;ptr2=out; while (ptr < end_ptr) { if (*ptr!='\\') *ptr2++=*ptr++; else { ptr++; switch (*ptr) { case 'b': *ptr2++='\b'; break; case 'f': *ptr2++='\f'; break; case 'n': *ptr2++='\n'; break; case 'r': *ptr2++='\r'; break; case 't': *ptr2++='\t'; break; case 'u': /* transcode utf16 to utf8. */ uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ if (ptr >= end_ptr) {*ep=str;return 0;} /* invalid */ if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) {*ep=str;return 0;} /* check for invalid. */ if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ { if (ptr+6 > end_ptr) {*ep=str;return 0;} /* invalid */ if (ptr[1]!='\\' || ptr[2]!='u') {*ep=str;return 0;} /* missing second-half of surrogate. */ uc2=parse_hex4(ptr+3);ptr+=6; if (uc2<0xDC00 || uc2>0xDFFF) {*ep=str;return 0;} /* invalid second-half of surrogate. */ uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); } len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; switch (len) { case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 1: *--ptr2 =(uc | firstByteMark[len]); } ptr2+=len; break; default: *ptr2++=*ptr; break; } ptr++; } } *ptr2=0; if (*ptr=='\"') ptr++; return ptr; }
169,862
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: resetLppTransposer (HANDLE_SBR_LPP_TRANS hLppTrans, /*!< Handle of lpp transposer */ UCHAR highBandStartSb, /*!< High band area: start subband */ UCHAR *v_k_master, /*!< Master table */ UCHAR numMaster, /*!< Valid entries in master table */ UCHAR *noiseBandTable, /*!< Mapping of SBR noise bands to QMF bands */ UCHAR noNoiseBands, /*!< Number of noise bands */ UCHAR usb, /*!< High band area: stop subband */ UINT fs /*!< SBR output sampling frequency */ ) { TRANSPOSER_SETTINGS *pSettings = hLppTrans->pSettings; PATCH_PARAM *patchParam = pSettings->patchParam; int i, patch; int targetStopBand; int sourceStartBand; int patchDistance; int numBandsInPatch; int lsb = v_k_master[0]; /* Start subband expressed in "non-critical" sampling terms*/ int xoverOffset = highBandStartSb - lsb; /* Calculate distance in QMF bands between k0 and kx */ int startFreqHz; int desiredBorder; usb = fixMin(usb, v_k_master[numMaster]); /* Avoid endless loops (compare with float code). */ /* * Plausibility check */ if ( lsb - SHIFT_START_SB < 4 ) { return SBRDEC_UNSUPPORTED_CONFIG; } /* * Initialize the patching parameter */ /* ISO/IEC 14496-3 (Figure 4.48): goalSb = round( 2.048e6 / fs ) */ desiredBorder = (((2048000*2) / fs) + 1) >> 1; desiredBorder = findClosestEntry(desiredBorder, v_k_master, numMaster, 1); /* Adapt region to master-table */ /* First patch */ sourceStartBand = SHIFT_START_SB + xoverOffset; targetStopBand = lsb + xoverOffset; /* upperBand */ /* Even (odd) numbered channel must be patched to even (odd) numbered channel */ patch = 0; while(targetStopBand < usb) { /* Too many patches? Allow MAX_NUM_PATCHES+1 patches here. we need to check later again, since patch might be the highest patch AND contain less than 3 bands => actual number of patches will be reduced by 1. */ if (patch > MAX_NUM_PATCHES) { return SBRDEC_UNSUPPORTED_CONFIG; } patchParam[patch].guardStartBand = targetStopBand; patchParam[patch].targetStartBand = targetStopBand; numBandsInPatch = desiredBorder - targetStopBand; /* Get the desired range of the patch */ if ( numBandsInPatch >= lsb - sourceStartBand ) { /* Desired number bands are not available -> patch whole source range */ patchDistance = targetStopBand - sourceStartBand; /* Get the targetOffset */ patchDistance = patchDistance & ~1; /* Rounding off odd numbers and make all even */ numBandsInPatch = lsb - (targetStopBand - patchDistance); /* Update number of bands to be patched */ numBandsInPatch = findClosestEntry(targetStopBand + numBandsInPatch, v_k_master, numMaster, 0) - targetStopBand; /* Adapt region to master-table */ } /* Desired number bands are available -> get the minimal even patching distance */ patchDistance = numBandsInPatch + targetStopBand - lsb; /* Get minimal distance */ patchDistance = (patchDistance + 1) & ~1; /* Rounding up odd numbers and make all even */ if (numBandsInPatch > 0) { patchParam[patch].sourceStartBand = targetStopBand - patchDistance; patchParam[patch].targetBandOffs = patchDistance; patchParam[patch].numBandsInPatch = numBandsInPatch; patchParam[patch].sourceStopBand = patchParam[patch].sourceStartBand + numBandsInPatch; targetStopBand += patchParam[patch].numBandsInPatch; patch++; } /* All patches but first */ sourceStartBand = SHIFT_START_SB; /* Check if we are close to desiredBorder */ if( desiredBorder - targetStopBand < 3) /* MPEG doc */ { desiredBorder = usb; } } patch--; /* If highest patch contains less than three subband: skip it */ if ( (patch>0) && (patchParam[patch].numBandsInPatch < 3) ) { patch--; targetStopBand = patchParam[patch].targetStartBand + patchParam[patch].numBandsInPatch; } /* now check if we don't have one too many */ if (patch >= MAX_NUM_PATCHES) { return SBRDEC_UNSUPPORTED_CONFIG; } pSettings->noOfPatches = patch + 1; /* Check lowest and highest source subband */ pSettings->lbStartPatching = targetStopBand; pSettings->lbStopPatching = 0; for ( patch = 0; patch < pSettings->noOfPatches; patch++ ) { pSettings->lbStartPatching = fixMin( pSettings->lbStartPatching, patchParam[patch].sourceStartBand ); pSettings->lbStopPatching = fixMax( pSettings->lbStopPatching, patchParam[patch].sourceStopBand ); } for(i = 0 ; i < noNoiseBands; i++){ pSettings->bwBorders[i] = noiseBandTable[i+1]; } /* * Choose whitening factors */ startFreqHz = ( (lsb + xoverOffset)*fs ) >> 7; /* Shift does a division by 2*(64) */ for( i = 1; i < NUM_WHFACTOR_TABLE_ENTRIES; i++ ) { if( startFreqHz < FDK_sbrDecoder_sbr_whFactorsIndex[i]) break; } i--; pSettings->whFactors.off = FDK_sbrDecoder_sbr_whFactorsTable[i][0]; pSettings->whFactors.transitionLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][1]; pSettings->whFactors.lowLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][2]; pSettings->whFactors.midLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][3]; pSettings->whFactors.highLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][4]; return SBRDEC_OK; } Commit Message: Fix out of bound memory access in lppTransposer In TRANSPOSER_SETTINGS, initialize the whole bwBorders array to a reasonable value to guarantee correct termination in while loop in lppTransposer function. This fixes the reported bug. For completeness: - clear the whole bwIndex array instead of noOfPatches entries only. - abort criterion in while loop to prevent potential infinite loop, and limit bwIndex[patch] to a valid range. Test: see bug for malicious content, decoded with "stagefright -s -a" Bug: 65280786 Change-Id: I16ed2e1c0f1601926239a652ca20a91284151843 (cherry picked from commit 6d3dd40e204bf550abcfa589bd9615df8778e118) CWE ID: CWE-200
resetLppTransposer (HANDLE_SBR_LPP_TRANS hLppTrans, /*!< Handle of lpp transposer */ UCHAR highBandStartSb, /*!< High band area: start subband */ UCHAR *v_k_master, /*!< Master table */ UCHAR numMaster, /*!< Valid entries in master table */ UCHAR *noiseBandTable, /*!< Mapping of SBR noise bands to QMF bands */ UCHAR noNoiseBands, /*!< Number of noise bands */ UCHAR usb, /*!< High band area: stop subband */ UINT fs /*!< SBR output sampling frequency */ ) { TRANSPOSER_SETTINGS *pSettings = hLppTrans->pSettings; PATCH_PARAM *patchParam = pSettings->patchParam; int i, patch; int targetStopBand; int sourceStartBand; int patchDistance; int numBandsInPatch; int lsb = v_k_master[0]; /* Start subband expressed in "non-critical" sampling terms*/ int xoverOffset = highBandStartSb - lsb; /* Calculate distance in QMF bands between k0 and kx */ int startFreqHz; int desiredBorder; usb = fixMin(usb, v_k_master[numMaster]); /* Avoid endless loops (compare with float code). */ /* * Plausibility check */ if ( lsb - SHIFT_START_SB < 4 ) { return SBRDEC_UNSUPPORTED_CONFIG; } /* * Initialize the patching parameter */ /* ISO/IEC 14496-3 (Figure 4.48): goalSb = round( 2.048e6 / fs ) */ desiredBorder = (((2048000*2) / fs) + 1) >> 1; desiredBorder = findClosestEntry(desiredBorder, v_k_master, numMaster, 1); /* Adapt region to master-table */ /* First patch */ sourceStartBand = SHIFT_START_SB + xoverOffset; targetStopBand = lsb + xoverOffset; /* upperBand */ /* Even (odd) numbered channel must be patched to even (odd) numbered channel */ patch = 0; while(targetStopBand < usb) { /* Too many patches? Allow MAX_NUM_PATCHES+1 patches here. we need to check later again, since patch might be the highest patch AND contain less than 3 bands => actual number of patches will be reduced by 1. */ if (patch > MAX_NUM_PATCHES) { return SBRDEC_UNSUPPORTED_CONFIG; } patchParam[patch].guardStartBand = targetStopBand; patchParam[patch].targetStartBand = targetStopBand; numBandsInPatch = desiredBorder - targetStopBand; /* Get the desired range of the patch */ if ( numBandsInPatch >= lsb - sourceStartBand ) { /* Desired number bands are not available -> patch whole source range */ patchDistance = targetStopBand - sourceStartBand; /* Get the targetOffset */ patchDistance = patchDistance & ~1; /* Rounding off odd numbers and make all even */ numBandsInPatch = lsb - (targetStopBand - patchDistance); /* Update number of bands to be patched */ numBandsInPatch = findClosestEntry(targetStopBand + numBandsInPatch, v_k_master, numMaster, 0) - targetStopBand; /* Adapt region to master-table */ } /* Desired number bands are available -> get the minimal even patching distance */ patchDistance = numBandsInPatch + targetStopBand - lsb; /* Get minimal distance */ patchDistance = (patchDistance + 1) & ~1; /* Rounding up odd numbers and make all even */ if (numBandsInPatch > 0) { patchParam[patch].sourceStartBand = targetStopBand - patchDistance; patchParam[patch].targetBandOffs = patchDistance; patchParam[patch].numBandsInPatch = numBandsInPatch; patchParam[patch].sourceStopBand = patchParam[patch].sourceStartBand + numBandsInPatch; targetStopBand += patchParam[patch].numBandsInPatch; patch++; } /* All patches but first */ sourceStartBand = SHIFT_START_SB; /* Check if we are close to desiredBorder */ if( desiredBorder - targetStopBand < 3) /* MPEG doc */ { desiredBorder = usb; } } patch--; /* If highest patch contains less than three subband: skip it */ if ( (patch>0) && (patchParam[patch].numBandsInPatch < 3) ) { patch--; targetStopBand = patchParam[patch].targetStartBand + patchParam[patch].numBandsInPatch; } /* now check if we don't have one too many */ if (patch >= MAX_NUM_PATCHES) { return SBRDEC_UNSUPPORTED_CONFIG; } pSettings->noOfPatches = patch + 1; /* Check lowest and highest source subband */ pSettings->lbStartPatching = targetStopBand; pSettings->lbStopPatching = 0; for ( patch = 0; patch < pSettings->noOfPatches; patch++ ) { pSettings->lbStartPatching = fixMin( pSettings->lbStartPatching, patchParam[patch].sourceStartBand ); pSettings->lbStopPatching = fixMax( pSettings->lbStopPatching, patchParam[patch].sourceStopBand ); } for(i = 0 ; i < noNoiseBands; i++){ pSettings->bwBorders[i] = noiseBandTable[i+1]; } for (;i < MAX_NUM_NOISE_VALUES; i++) { pSettings->bwBorders[i] = 255; } /* * Choose whitening factors */ startFreqHz = ( (lsb + xoverOffset)*fs ) >> 7; /* Shift does a division by 2*(64) */ for( i = 1; i < NUM_WHFACTOR_TABLE_ENTRIES; i++ ) { if( startFreqHz < FDK_sbrDecoder_sbr_whFactorsIndex[i]) break; } i--; pSettings->whFactors.off = FDK_sbrDecoder_sbr_whFactorsTable[i][0]; pSettings->whFactors.transitionLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][1]; pSettings->whFactors.lowLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][2]; pSettings->whFactors.midLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][3]; pSettings->whFactors.highLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][4]; return SBRDEC_OK; }
174,114
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: P2PQuicTransportImpl::P2PQuicTransportImpl( P2PQuicTransportConfig p2p_transport_config, std::unique_ptr<net::QuicChromiumConnectionHelper> helper, std::unique_ptr<quic::QuicConnection> connection, const quic::QuicConfig& quic_config, quic::QuicClock* clock) : quic::QuicSession(connection.get(), nullptr /* visitor */, quic_config, quic::CurrentSupportedVersions()), helper_(std::move(helper)), connection_(std::move(connection)), perspective_(p2p_transport_config.is_server ? quic::Perspective::IS_SERVER : quic::Perspective::IS_CLIENT), packet_transport_(p2p_transport_config.packet_transport), delegate_(p2p_transport_config.delegate), clock_(clock) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(delegate_); DCHECK(clock_); DCHECK(packet_transport_); DCHECK_GT(p2p_transport_config.certificates.size(), 0u); if (p2p_transport_config.can_respond_to_crypto_handshake) { InitializeCryptoStream(); } certificate_ = p2p_transport_config.certificates[0]; packet_transport_->SetReceiveDelegate(this); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
P2PQuicTransportImpl::P2PQuicTransportImpl( P2PQuicTransportConfig p2p_transport_config, std::unique_ptr<net::QuicChromiumConnectionHelper> helper, std::unique_ptr<quic::QuicConnection> connection, const quic::QuicConfig& quic_config, quic::QuicClock* clock) : quic::QuicSession(connection.get(), nullptr /* visitor */, quic_config, quic::CurrentSupportedVersions()), helper_(std::move(helper)), connection_(std::move(connection)), perspective_(p2p_transport_config.is_server ? quic::Perspective::IS_SERVER : quic::Perspective::IS_CLIENT), packet_transport_(p2p_transport_config.packet_transport), delegate_(p2p_transport_config.delegate), clock_(clock), stream_write_buffer_size_(p2p_transport_config.stream_write_buffer_size) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(delegate_); DCHECK(clock_); DCHECK(packet_transport_); DCHECK_GT(stream_write_buffer_size_, 0u); DCHECK_GT(p2p_transport_config.certificates.size(), 0u); if (p2p_transport_config.can_respond_to_crypto_handshake) { InitializeCryptoStream(); } certificate_ = p2p_transport_config.certificates[0]; packet_transport_->SetReceiveDelegate(this); }
172,266
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: decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; }
169,072
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: IndexedDBTransaction* IndexedDBConnection::CreateTransaction( int64_t id, const std::set<int64_t>& scope, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) { DCHECK_EQ(GetTransaction(id), nullptr) << "Duplicate transaction id." << id; std::unique_ptr<IndexedDBTransaction> transaction = IndexedDBClassFactory::Get()->CreateIndexedDBTransaction( id, this, scope, mode, backing_store_transaction); IndexedDBTransaction* transaction_ptr = transaction.get(); transactions_[id] = std::move(transaction); return transaction_ptr; } Commit Message: [IndexedDB] Fixed transaction use-after-free vuln Bug: 725032 Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa Reviewed-on: https://chromium-review.googlesource.com/518483 Reviewed-by: Joshua Bell <[email protected]> Commit-Queue: Daniel Murphy <[email protected]> Cr-Commit-Position: refs/heads/master@{#475952} CWE ID: CWE-416
IndexedDBTransaction* IndexedDBConnection::CreateTransaction( int64_t id, const std::set<int64_t>& scope, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) { CHECK_EQ(GetTransaction(id), nullptr) << "Duplicate transaction id." << id; std::unique_ptr<IndexedDBTransaction> transaction = IndexedDBClassFactory::Get()->CreateIndexedDBTransaction( id, this, scope, mode, backing_store_transaction); IndexedDBTransaction* transaction_ptr = transaction.get(); transactions_[id] = std::move(transaction); return transaction_ptr; }
172,352
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: DevToolsUIBindings::DevToolsUIBindings(content::WebContents* web_contents) : profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())), android_bridge_(DevToolsAndroidBridge::Factory::GetForProfile(profile_)), web_contents_(web_contents), delegate_(new DefaultBindingsDelegate(web_contents_)), devices_updates_enabled_(false), frontend_loaded_(false), reloading_(false), weak_factory_(this) { g_instances.Get().push_back(this); frontend_contents_observer_.reset(new FrontendWebContentsObserver(this)); web_contents_->GetMutableRendererPrefs()->can_accept_load_drops = false; file_helper_.reset(new DevToolsFileHelper(web_contents_, profile_, this)); file_system_indexer_ = new DevToolsFileSystemIndexer(); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents_); embedder_message_dispatcher_.reset( DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this)); frontend_host_.reset(content::DevToolsFrontendHost::Create( web_contents_->GetMainFrame(), base::Bind(&DevToolsUIBindings::HandleMessageFromDevToolsFrontend, base::Unretained(this)))); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
DevToolsUIBindings::DevToolsUIBindings(content::WebContents* web_contents) : profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())), android_bridge_(DevToolsAndroidBridge::Factory::GetForProfile(profile_)), web_contents_(web_contents), delegate_(new DefaultBindingsDelegate(web_contents_)), devices_updates_enabled_(false), frontend_loaded_(false), reloading_(false), weak_factory_(this) { g_instances.Get().push_back(this); frontend_contents_observer_.reset(new FrontendWebContentsObserver(this)); web_contents_->GetMutableRendererPrefs()->can_accept_load_drops = false; file_helper_.reset(new DevToolsFileHelper(web_contents_, profile_, this)); file_system_indexer_ = new DevToolsFileSystemIndexer(); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents_); embedder_message_dispatcher_.reset( DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this)); UpdateFrontendHost(); }
172,452
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: header_put_marker (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4) { psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_marker */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_marker (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_marker */
170,059
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: header_gets (SF_PRIVATE *psf, char *ptr, int bufsize) { int k ; for (k = 0 ; k < bufsize - 1 ; k++) { if (psf->headindex < psf->headend) { ptr [k] = psf->header [psf->headindex] ; psf->headindex ++ ; } else { psf->headend += psf_fread (psf->header + psf->headend, 1, 1, psf) ; ptr [k] = psf->header [psf->headindex] ; psf->headindex = psf->headend ; } ; if (ptr [k] == '\n') break ; } ; ptr [k] = 0 ; return k ; } /* header_gets */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_gets (SF_PRIVATE *psf, char *ptr, int bufsize) { int k ; if (psf->header.indx + bufsize >= psf->header.len && psf_bump_header_allocation (psf, bufsize)) return 0 ; for (k = 0 ; k < bufsize - 1 ; k++) { if (psf->header.indx < psf->header.end) { ptr [k] = psf->header.ptr [psf->header.indx] ; psf->header.indx ++ ; } else { psf->header.end += psf_fread (psf->header.ptr + psf->header.end, 1, 1, psf) ; ptr [k] = psf->header.ptr [psf->header.indx] ; psf->header.indx = psf->header.end ; } ; if (ptr [k] == '\n') break ; } ; ptr [k] = 0 ; return k ; } /* header_gets */
170,047
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 TabletModeWindowManager::Init() { { ScopedObserveWindowAnimation scoped_observe(GetTopWindow(), this, /*exiting_tablet_mode=*/false); ArrangeWindowsForTabletMode(); } AddWindowCreationObservers(); display::Screen::GetScreen()->AddObserver(this); Shell::Get()->AddShellObserver(this); Shell::Get()->session_controller()->AddObserver(this); Shell::Get()->overview_controller()->AddObserver(this); accounts_since_entering_tablet_.insert( Shell::Get()->session_controller()->GetActiveAccountId()); event_handler_ = std::make_unique<wm::TabletModeEventHandler>(); } Commit Message: Fix the crash after clamshell -> tablet transition in overview mode. This CL just reverted some changes that were made in https://chromium-review.googlesource.com/c/chromium/src/+/1658955. In that CL, we changed the clamshell <-> tablet transition when clamshell split view mode is enabled, however, we should keep the old behavior unchanged if the feature is not enabled, i.e., overview should be ended if it's active before the transition. Otherwise, it will cause a nullptr dereference crash since |split_view_drag_indicators_| is not created in clamshell overview and will be used in tablet overview. Bug: 982507 Change-Id: I238fe9472648a446cff4ab992150658c228714dd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1705474 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Mitsuru Oshima (Slow - on/off site) <[email protected]> Cr-Commit-Position: refs/heads/master@{#679306} CWE ID: CWE-362
void TabletModeWindowManager::Init() { // If clamshell split view mode is not enabled, still keep the old behavior: // end overview if it's active. And carry over snapped windows to splitscreen // if possible. if (!IsClamshellSplitViewModeEnabled()) Shell::Get()->overview_controller()->EndOverview(); // If clamshell splitview mode is enabled, there are 3 cases when entering // tablet mode: { ScopedObserveWindowAnimation scoped_observe(GetTopWindow(), this, /*exiting_tablet_mode=*/false); ArrangeWindowsForTabletMode(); } AddWindowCreationObservers(); display::Screen::GetScreen()->AddObserver(this); Shell::Get()->AddShellObserver(this); Shell::Get()->session_controller()->AddObserver(this); Shell::Get()->overview_controller()->AddObserver(this); accounts_since_entering_tablet_.insert( Shell::Get()->session_controller()->GetActiveAccountId()); event_handler_ = std::make_unique<wm::TabletModeEventHandler>(); }
172,401
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 yr_object_copy( YR_OBJECT* object, YR_OBJECT** object_copy) { YR_OBJECT* copy; YR_OBJECT* o; YR_STRUCTURE_MEMBER* structure_member; YR_OBJECT_FUNCTION* func; YR_OBJECT_FUNCTION* func_copy; int i; *object_copy = NULL; FAIL_ON_ERROR(yr_object_create( object->type, object->identifier, NULL, &copy)); switch(object->type) { case OBJECT_TYPE_INTEGER: ((YR_OBJECT_INTEGER*) copy)->value = UNDEFINED; break; case OBJECT_TYPE_STRING: ((YR_OBJECT_STRING*) copy)->value = NULL; break; case OBJECT_TYPE_FUNCTION: func = (YR_OBJECT_FUNCTION*) object; func_copy = (YR_OBJECT_FUNCTION*) copy; FAIL_ON_ERROR_WITH_CLEANUP( yr_object_copy(func->return_obj, &func_copy->return_obj), yr_object_destroy(copy)); for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) func_copy->prototypes[i] = func->prototypes[i]; break; case OBJECT_TYPE_STRUCTURE: structure_member = ((YR_OBJECT_STRUCTURE*) object)->members; while (structure_member != NULL) { FAIL_ON_ERROR_WITH_CLEANUP( yr_object_copy(structure_member->object, &o), yr_object_destroy(copy)); FAIL_ON_ERROR_WITH_CLEANUP( yr_object_structure_set_member(copy, o), yr_free(o); yr_object_destroy(copy)); structure_member = structure_member->next; } break; case OBJECT_TYPE_ARRAY: yr_object_copy( ((YR_OBJECT_ARRAY *) object)->prototype_item, &o); ((YR_OBJECT_ARRAY *)copy)->prototype_item = o; break; case OBJECT_TYPE_DICTIONARY: yr_object_copy( ((YR_OBJECT_DICTIONARY *) object)->prototype_item, &o); ((YR_OBJECT_DICTIONARY *)copy)->prototype_item = o; break; default: assert(FALSE); } *object_copy = copy; return ERROR_SUCCESS; } Commit Message: Fix issue #658 CWE ID: CWE-416
int yr_object_copy( YR_OBJECT* object, YR_OBJECT** object_copy) { YR_OBJECT* copy; YR_OBJECT* o; YR_STRUCTURE_MEMBER* structure_member; YR_OBJECT_FUNCTION* func; YR_OBJECT_FUNCTION* func_copy; int i; *object_copy = NULL; FAIL_ON_ERROR(yr_object_create( object->type, object->identifier, NULL, &copy)); switch(object->type) { case OBJECT_TYPE_INTEGER: ((YR_OBJECT_INTEGER*) copy)->value = ((YR_OBJECT_INTEGER*) object)->value; break; case OBJECT_TYPE_STRING: if (((YR_OBJECT_STRING*) object)->value != NULL) { ((YR_OBJECT_STRING*) copy)->value = sized_string_dup( ((YR_OBJECT_STRING*) object)->value); } else { ((YR_OBJECT_STRING*) copy)->value = NULL; } break; case OBJECT_TYPE_FLOAT: ((YR_OBJECT_DOUBLE*) copy)->value = ((YR_OBJECT_DOUBLE*) object)->value; break; case OBJECT_TYPE_FUNCTION: func = (YR_OBJECT_FUNCTION*) object; func_copy = (YR_OBJECT_FUNCTION*) copy; FAIL_ON_ERROR_WITH_CLEANUP( yr_object_copy(func->return_obj, &func_copy->return_obj), yr_object_destroy(copy)); for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) func_copy->prototypes[i] = func->prototypes[i]; break; case OBJECT_TYPE_STRUCTURE: structure_member = ((YR_OBJECT_STRUCTURE*) object)->members; while (structure_member != NULL) { FAIL_ON_ERROR_WITH_CLEANUP( yr_object_copy(structure_member->object, &o), yr_object_destroy(copy)); FAIL_ON_ERROR_WITH_CLEANUP( yr_object_structure_set_member(copy, o), yr_free(o); yr_object_destroy(copy)); structure_member = structure_member->next; } break; case OBJECT_TYPE_ARRAY: yr_object_copy( ((YR_OBJECT_ARRAY *) object)->prototype_item, &o); ((YR_OBJECT_ARRAY *)copy)->prototype_item = o; break; case OBJECT_TYPE_DICTIONARY: yr_object_copy( ((YR_OBJECT_DICTIONARY *) object)->prototype_item, &o); ((YR_OBJECT_DICTIONARY *)copy)->prototype_item = o; break; default: assert(FALSE); } *object_copy = copy; return ERROR_SUCCESS; }
168,187
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 __init init_ext2_fs(void) { int err = init_ext2_xattr(); if (err) return err; err = init_inodecache(); if (err) goto out1; err = register_filesystem(&ext2_fs_type); if (err) goto out; return 0; out: destroy_inodecache(); out1: exit_ext2_xattr(); return err; } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19
static int __init init_ext2_fs(void) { int err; err = init_inodecache(); if (err) return err; err = register_filesystem(&ext2_fs_type); if (err) goto out; return 0; out: destroy_inodecache(); return err; }
169,975
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 logi_dj_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct dj_receiver_dev *djrcv_dev = hid_get_drvdata(hdev); struct dj_report *dj_report = (struct dj_report *) data; unsigned long flags; bool report_processed = false; dbg_hid("%s, size:%d\n", __func__, size); /* Here we receive all data coming from iface 2, there are 4 cases: * * 1) Data should continue its normal processing i.e. data does not * come from the DJ collection, in which case we do nothing and * return 0, so hid-core can continue normal processing (will forward * to associated hidraw device) * * 2) Data is from DJ collection, and is intended for this driver i. e. * data contains arrival, departure, etc notifications, in which case * we queue them for delayed processing by the work queue. We return 1 * to hid-core as no further processing is required from it. * * 3) Data is from DJ collection, and informs a connection change, * if the change means rf link loss, then we must send a null report * to the upper layer to discard potentially pressed keys that may be * repeated forever by the input layer. Return 1 to hid-core as no * further processing is required. * * 4) Data is from DJ collection and is an actual input event from * a paired DJ device in which case we forward it to the correct hid * device (via hid_input_report() ) and return 1 so hid-core does not do * anything else with it. */ spin_lock_irqsave(&djrcv_dev->lock, flags); if (dj_report->report_id == REPORT_ID_DJ_SHORT) { switch (dj_report->report_type) { case REPORT_TYPE_NOTIF_DEVICE_PAIRED: case REPORT_TYPE_NOTIF_DEVICE_UNPAIRED: logi_dj_recv_queue_notification(djrcv_dev, dj_report); break; case REPORT_TYPE_NOTIF_CONNECTION_STATUS: if (dj_report->report_params[CONNECTION_STATUS_PARAM_STATUS] == STATUS_LINKLOSS) { logi_dj_recv_forward_null_report(djrcv_dev, dj_report); } break; default: logi_dj_recv_forward_report(djrcv_dev, dj_report); } report_processed = true; } spin_unlock_irqrestore(&djrcv_dev->lock, flags); return report_processed; } Commit Message: HID: logitech: perform bounds checking on device_id early enough device_index is a char type and the size of paired_dj_deivces is 7 elements, therefore proper bounds checking has to be applied to device_index before it is used. We are currently performing the bounds checking in logi_dj_recv_add_djhid_device(), which is too late, as malicious device could send REPORT_TYPE_NOTIF_DEVICE_UNPAIRED early enough and trigger the problem in one of the report forwarding functions called from logi_dj_raw_event(). Fix this by performing the check at the earliest possible ocasion in logi_dj_raw_event(). Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119
static int logi_dj_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct dj_receiver_dev *djrcv_dev = hid_get_drvdata(hdev); struct dj_report *dj_report = (struct dj_report *) data; unsigned long flags; bool report_processed = false; dbg_hid("%s, size:%d\n", __func__, size); /* Here we receive all data coming from iface 2, there are 4 cases: * * 1) Data should continue its normal processing i.e. data does not * come from the DJ collection, in which case we do nothing and * return 0, so hid-core can continue normal processing (will forward * to associated hidraw device) * * 2) Data is from DJ collection, and is intended for this driver i. e. * data contains arrival, departure, etc notifications, in which case * we queue them for delayed processing by the work queue. We return 1 * to hid-core as no further processing is required from it. * * 3) Data is from DJ collection, and informs a connection change, * if the change means rf link loss, then we must send a null report * to the upper layer to discard potentially pressed keys that may be * repeated forever by the input layer. Return 1 to hid-core as no * further processing is required. * * 4) Data is from DJ collection and is an actual input event from * a paired DJ device in which case we forward it to the correct hid * device (via hid_input_report() ) and return 1 so hid-core does not do * anything else with it. */ if ((dj_report->device_index < DJ_DEVICE_INDEX_MIN) || (dj_report->device_index > DJ_DEVICE_INDEX_MAX)) { dev_err(&hdev->dev, "%s: invalid device index:%d\n", __func__, dj_report->device_index); return false; } spin_lock_irqsave(&djrcv_dev->lock, flags); if (dj_report->report_id == REPORT_ID_DJ_SHORT) { switch (dj_report->report_type) { case REPORT_TYPE_NOTIF_DEVICE_PAIRED: case REPORT_TYPE_NOTIF_DEVICE_UNPAIRED: logi_dj_recv_queue_notification(djrcv_dev, dj_report); break; case REPORT_TYPE_NOTIF_CONNECTION_STATUS: if (dj_report->report_params[CONNECTION_STATUS_PARAM_STATUS] == STATUS_LINKLOSS) { logi_dj_recv_forward_null_report(djrcv_dev, dj_report); } break; default: logi_dj_recv_forward_report(djrcv_dev, dj_report); } report_processed = true; } spin_unlock_irqrestore(&djrcv_dev->lock, flags); return report_processed; }
166,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: NORET_TYPE void do_exit(long code) { struct task_struct *tsk = current; int group_dead; profile_task_exit(tsk); WARN_ON(atomic_read(&tsk->fs_excl)); if (unlikely(in_interrupt())) panic("Aiee, killing interrupt handler!"); if (unlikely(!tsk->pid)) panic("Attempted to kill the idle task!"); tracehook_report_exit(&code); /* * We're taking recursive faults here in do_exit. Safest is to just * leave this task alone and wait for reboot. */ if (unlikely(tsk->flags & PF_EXITING)) { printk(KERN_ALERT "Fixing recursive fault but reboot is needed!\n"); /* * We can do this unlocked here. The futex code uses * this flag just to verify whether the pi state * cleanup has been done or not. In the worst case it * loops once more. We pretend that the cleanup was * done as there is no way to return. Either the * OWNER_DIED bit is set by now or we push the blocked * task into the wait for ever nirwana as well. */ tsk->flags |= PF_EXITPIDONE; if (tsk->io_context) exit_io_context(); set_current_state(TASK_UNINTERRUPTIBLE); schedule(); } exit_signals(tsk); /* sets PF_EXITING */ /* * tsk->flags are checked in the futex code to protect against * an exiting task cleaning up the robust pi futexes. */ smp_mb(); spin_unlock_wait(&tsk->pi_lock); if (unlikely(in_atomic())) printk(KERN_INFO "note: %s[%d] exited with preempt_count %d\n", current->comm, task_pid_nr(current), preempt_count()); acct_update_integrals(tsk); if (tsk->mm) { update_hiwater_rss(tsk->mm); update_hiwater_vm(tsk->mm); } group_dead = atomic_dec_and_test(&tsk->signal->live); if (group_dead) { hrtimer_cancel(&tsk->signal->real_timer); exit_itimers(tsk->signal); } acct_collect(code, group_dead); #ifdef CONFIG_FUTEX if (unlikely(tsk->robust_list)) exit_robust_list(tsk); #ifdef CONFIG_COMPAT if (unlikely(tsk->compat_robust_list)) compat_exit_robust_list(tsk); #endif #endif if (group_dead) tty_audit_exit(); if (unlikely(tsk->audit_context)) audit_free(tsk); tsk->exit_code = code; taskstats_exit(tsk, group_dead); exit_mm(tsk); if (group_dead) acct_process(); trace_sched_process_exit(tsk); exit_sem(tsk); exit_files(tsk); exit_fs(tsk); check_stack_usage(); exit_thread(); cgroup_exit(tsk, 1); exit_keys(tsk); if (group_dead && tsk->signal->leader) disassociate_ctty(1); module_put(task_thread_info(tsk)->exec_domain->module); if (tsk->binfmt) module_put(tsk->binfmt->module); proc_exit_connector(tsk); exit_notify(tsk, group_dead); #ifdef CONFIG_NUMA mpol_put(tsk->mempolicy); tsk->mempolicy = NULL; #endif #ifdef CONFIG_FUTEX /* * This must happen late, after the PID is not * hashed anymore: */ if (unlikely(!list_empty(&tsk->pi_state_list))) exit_pi_state_list(tsk); if (unlikely(current->pi_state_cache)) kfree(current->pi_state_cache); #endif /* * Make sure we are holding no locks: */ debug_check_no_locks_held(tsk); /* * We can do this unlocked here. The futex code uses this flag * just to verify whether the pi state cleanup has been done * or not. In the worst case it loops once more. */ tsk->flags |= PF_EXITPIDONE; if (tsk->io_context) exit_io_context(); if (tsk->splice_pipe) __free_pipe_info(tsk->splice_pipe); preempt_disable(); /* causes final put_task_struct in finish_task_switch(). */ tsk->state = TASK_DEAD; schedule(); BUG(); /* Avoid "noreturn function does return". */ for (;;) cpu_relax(); /* For when BUG is null */ } Commit Message: Move "exit_robust_list" into mm_release() We don't want to get rid of the futexes just at exit() time, we want to drop them when doing an execve() too, since that gets rid of the previous VM image too. Doing it at mm_release() time means that we automatically always do it when we disassociate a VM map from the task. Reported-by: [email protected] Cc: Andrew Morton <[email protected]> Cc: Nick Piggin <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Brad Spengler <[email protected]> Cc: Alex Efros <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Oleg Nesterov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
NORET_TYPE void do_exit(long code) { struct task_struct *tsk = current; int group_dead; profile_task_exit(tsk); WARN_ON(atomic_read(&tsk->fs_excl)); if (unlikely(in_interrupt())) panic("Aiee, killing interrupt handler!"); if (unlikely(!tsk->pid)) panic("Attempted to kill the idle task!"); tracehook_report_exit(&code); /* * We're taking recursive faults here in do_exit. Safest is to just * leave this task alone and wait for reboot. */ if (unlikely(tsk->flags & PF_EXITING)) { printk(KERN_ALERT "Fixing recursive fault but reboot is needed!\n"); /* * We can do this unlocked here. The futex code uses * this flag just to verify whether the pi state * cleanup has been done or not. In the worst case it * loops once more. We pretend that the cleanup was * done as there is no way to return. Either the * OWNER_DIED bit is set by now or we push the blocked * task into the wait for ever nirwana as well. */ tsk->flags |= PF_EXITPIDONE; if (tsk->io_context) exit_io_context(); set_current_state(TASK_UNINTERRUPTIBLE); schedule(); } exit_signals(tsk); /* sets PF_EXITING */ /* * tsk->flags are checked in the futex code to protect against * an exiting task cleaning up the robust pi futexes. */ smp_mb(); spin_unlock_wait(&tsk->pi_lock); if (unlikely(in_atomic())) printk(KERN_INFO "note: %s[%d] exited with preempt_count %d\n", current->comm, task_pid_nr(current), preempt_count()); acct_update_integrals(tsk); if (tsk->mm) { update_hiwater_rss(tsk->mm); update_hiwater_vm(tsk->mm); } group_dead = atomic_dec_and_test(&tsk->signal->live); if (group_dead) { hrtimer_cancel(&tsk->signal->real_timer); exit_itimers(tsk->signal); } acct_collect(code, group_dead); if (group_dead) tty_audit_exit(); if (unlikely(tsk->audit_context)) audit_free(tsk); tsk->exit_code = code; taskstats_exit(tsk, group_dead); exit_mm(tsk); if (group_dead) acct_process(); trace_sched_process_exit(tsk); exit_sem(tsk); exit_files(tsk); exit_fs(tsk); check_stack_usage(); exit_thread(); cgroup_exit(tsk, 1); exit_keys(tsk); if (group_dead && tsk->signal->leader) disassociate_ctty(1); module_put(task_thread_info(tsk)->exec_domain->module); if (tsk->binfmt) module_put(tsk->binfmt->module); proc_exit_connector(tsk); exit_notify(tsk, group_dead); #ifdef CONFIG_NUMA mpol_put(tsk->mempolicy); tsk->mempolicy = NULL; #endif #ifdef CONFIG_FUTEX /* * This must happen late, after the PID is not * hashed anymore: */ if (unlikely(!list_empty(&tsk->pi_state_list))) exit_pi_state_list(tsk); if (unlikely(current->pi_state_cache)) kfree(current->pi_state_cache); #endif /* * Make sure we are holding no locks: */ debug_check_no_locks_held(tsk); /* * We can do this unlocked here. The futex code uses this flag * just to verify whether the pi state cleanup has been done * or not. In the worst case it loops once more. */ tsk->flags |= PF_EXITPIDONE; if (tsk->io_context) exit_io_context(); if (tsk->splice_pipe) __free_pipe_info(tsk->splice_pipe); preempt_disable(); /* causes final put_task_struct in finish_task_switch(). */ tsk->state = TASK_DEAD; schedule(); BUG(); /* Avoid "noreturn function does return". */ for (;;) cpu_relax(); /* For when BUG is null */ }
165,667
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 BOOLEAN flush_incoming_que_on_wr_signal_l(l2cap_socket *sock) { uint8_t *buf; uint32_t len; while (packet_get_head_l(sock, &buf, &len)) { int sent = send(sock->our_fd, buf, len, MSG_DONTWAIT); if (sent == (signed)len) osi_free(buf); else if (sent >= 0) { packet_put_head_l(sock, buf + sent, len - sent); osi_free(buf); if (!sent) /* special case if other end not keeping up */ return TRUE; } else { packet_put_head_l(sock, buf, len); osi_free(buf); return errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN; } } return FALSE; } 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
static BOOLEAN flush_incoming_que_on_wr_signal_l(l2cap_socket *sock) { uint8_t *buf; uint32_t len; while (packet_get_head_l(sock, &buf, &len)) { int sent = TEMP_FAILURE_RETRY(send(sock->our_fd, buf, len, MSG_DONTWAIT)); if (sent == (signed)len) osi_free(buf); else if (sent >= 0) { packet_put_head_l(sock, buf + sent, len - sent); osi_free(buf); if (!sent) /* special case if other end not keeping up */ return TRUE; } else { packet_put_head_l(sock, buf, len); osi_free(buf); return errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN; } } return FALSE; }
173,454
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 prefetch_dec(void) { prefetch_table((const void *)&dec_tables, sizeof(dec_tables)); } Commit Message: AES: move look-up tables to .data section and unshare between processes * cipher/rijndael-internal.h (ATTR_ALIGNED_64): New. * cipher/rijndael-tables.h (encT): Move to 'enc_tables' structure. (enc_tables): New structure for encryption table with counters before and after. (encT): New macro. (dec_tables): Add counters before and after encryption table; Move from .rodata to .data section. (do_encrypt): Change 'encT' to 'enc_tables.T'. (do_decrypt): Change '&dec_tables' to 'dec_tables.T'. * cipher/cipher-gcm.c (prefetch_table): Make inline; Handle input with length not multiple of 256. (prefetch_enc, prefetch_dec): Modify pre- and post-table counters to unshare look-up table pages between processes. -- GnuPG-bug-id: 4541 Signed-off-by: Jussi Kivilinna <[email protected]> CWE ID: CWE-310
static void prefetch_dec(void) { /* Modify counters to trigger copy-on-write and unsharing if physical pages * of look-up table are shared between processes. Modifying counters also * causes checksums for pages to change and hint same-page merging algorithm * that these pages are frequently changing. */ dec_tables.counter_head++; dec_tables.counter_tail++; /* Prefetch look-up tables to cache. */ prefetch_table((const void *)&dec_tables, sizeof(dec_tables)); }
170,213
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 sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp) { struct sctp_association *asoc = sctp_id2assoc(sk, id); struct sctp_sock *sp = sctp_sk(sk); struct socket *sock; int err = 0; if (!asoc) return -EINVAL; /* If there is a thread waiting on more sndbuf space for * sending on this asoc, it cannot be peeled. */ if (waitqueue_active(&asoc->wait)) return -EBUSY; /* An association cannot be branched off from an already peeled-off * socket, nor is this supported for tcp style sockets. */ if (!sctp_style(sk, UDP)) return -EINVAL; /* Create a new socket. */ err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock); if (err < 0) return err; sctp_copy_sock(sock->sk, sk, asoc); /* Make peeled-off sockets more like 1-1 accepted sockets. * Set the daddr and initialize id to something more random */ sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk); /* Populate the fields of the newsk from the oldsk and migrate the * asoc to the newsk. */ sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH); *sockp = sock; return err; } Commit Message: sctp: do not peel off an assoc from one netns to another one Now when peeling off an association to the sock in another netns, all transports in this assoc are not to be rehashed and keep use the old key in hashtable. As a transport uses sk->net as the hash key to insert into hashtable, it would miss removing these transports from hashtable due to the new netns when closing the sock and all transports are being freeed, then later an use-after-free issue could be caused when looking up an asoc and dereferencing those transports. This is a very old issue since very beginning, ChunYu found it with syzkaller fuzz testing with this series: socket$inet6_sctp() bind$inet6() sendto$inet6() unshare(0x40000000) getsockopt$inet_sctp6_SCTP_GET_ASSOC_ID_LIST() getsockopt$inet_sctp6_SCTP_SOCKOPT_PEELOFF() This patch is to block this call when peeling one assoc off from one netns to another one, so that the netns of all transport would not go out-sync with the key in hashtable. Note that this patch didn't fix it by rehashing transports, as it's difficult to handle the situation when the tuple is already in use in the new netns. Besides, no one would like to peel off one assoc to another netns, considering ipaddrs, ifaces, etc. are usually different. Reported-by: ChunYu Wang <[email protected]> Signed-off-by: Xin Long <[email protected]> Acked-by: Marcelo Ricardo Leitner <[email protected]> Acked-by: Neil Horman <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp) { struct sctp_association *asoc = sctp_id2assoc(sk, id); struct sctp_sock *sp = sctp_sk(sk); struct socket *sock; int err = 0; /* Do not peel off from one netns to another one. */ if (!net_eq(current->nsproxy->net_ns, sock_net(sk))) return -EINVAL; if (!asoc) return -EINVAL; /* If there is a thread waiting on more sndbuf space for * sending on this asoc, it cannot be peeled. */ if (waitqueue_active(&asoc->wait)) return -EBUSY; /* An association cannot be branched off from an already peeled-off * socket, nor is this supported for tcp style sockets. */ if (!sctp_style(sk, UDP)) return -EINVAL; /* Create a new socket. */ err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock); if (err < 0) return err; sctp_copy_sock(sock->sk, sk, asoc); /* Make peeled-off sockets more like 1-1 accepted sockets. * Set the daddr and initialize id to something more random */ sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk); /* Populate the fields of the newsk from the oldsk and migrate the * asoc to the newsk. */ sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH); *sockp = sock; return err; }
167,736
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 SocketStream::DoLoop(int result) { if (!context_.get()) next_state_ = STATE_CLOSE; if (next_state_ == STATE_NONE) return; do { State state = next_state_; next_state_ = STATE_NONE; switch (state) { case STATE_BEFORE_CONNECT: DCHECK_EQ(OK, result); result = DoBeforeConnect(); break; case STATE_BEFORE_CONNECT_COMPLETE: result = DoBeforeConnectComplete(result); break; case STATE_RESOLVE_PROXY: DCHECK_EQ(OK, result); result = DoResolveProxy(); break; case STATE_RESOLVE_PROXY_COMPLETE: result = DoResolveProxyComplete(result); break; case STATE_RESOLVE_HOST: DCHECK_EQ(OK, result); result = DoResolveHost(); break; case STATE_RESOLVE_HOST_COMPLETE: result = DoResolveHostComplete(result); break; case STATE_RESOLVE_PROTOCOL: result = DoResolveProtocol(result); break; case STATE_RESOLVE_PROTOCOL_COMPLETE: result = DoResolveProtocolComplete(result); break; case STATE_TCP_CONNECT: result = DoTcpConnect(result); break; case STATE_TCP_CONNECT_COMPLETE: result = DoTcpConnectComplete(result); break; case STATE_GENERATE_PROXY_AUTH_TOKEN: result = DoGenerateProxyAuthToken(); break; case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE: result = DoGenerateProxyAuthTokenComplete(result); break; case STATE_WRITE_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoWriteTunnelHeaders(); break; case STATE_WRITE_TUNNEL_HEADERS_COMPLETE: result = DoWriteTunnelHeadersComplete(result); break; case STATE_READ_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoReadTunnelHeaders(); break; case STATE_READ_TUNNEL_HEADERS_COMPLETE: result = DoReadTunnelHeadersComplete(result); break; case STATE_SOCKS_CONNECT: DCHECK_EQ(OK, result); result = DoSOCKSConnect(); break; case STATE_SOCKS_CONNECT_COMPLETE: result = DoSOCKSConnectComplete(result); break; case STATE_SECURE_PROXY_CONNECT: DCHECK_EQ(OK, result); result = DoSecureProxyConnect(); break; case STATE_SECURE_PROXY_CONNECT_COMPLETE: result = DoSecureProxyConnectComplete(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR: result = DoSecureProxyHandleCertError(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE: result = DoSecureProxyHandleCertErrorComplete(result); break; case STATE_SSL_CONNECT: DCHECK_EQ(OK, result); result = DoSSLConnect(); break; case STATE_SSL_CONNECT_COMPLETE: result = DoSSLConnectComplete(result); break; case STATE_SSL_HANDLE_CERT_ERROR: result = DoSSLHandleCertError(result); break; case STATE_SSL_HANDLE_CERT_ERROR_COMPLETE: result = DoSSLHandleCertErrorComplete(result); break; case STATE_READ_WRITE: result = DoReadWrite(result); break; case STATE_AUTH_REQUIRED: Finish(result); return; case STATE_CLOSE: DCHECK_LE(result, OK); Finish(result); return; default: NOTREACHED() << "bad state " << state; Finish(result); return; } if (state == STATE_RESOLVE_PROTOCOL && result == ERR_PROTOCOL_SWITCHED) continue; if (state != STATE_READ_WRITE && result < ERR_IO_PENDING) { net_log_.EndEventWithNetErrorCode( NetLog::TYPE_SOCKET_STREAM_CONNECT, result); } } while (result != ERR_IO_PENDING); } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void SocketStream::DoLoop(int result) { if (!context_) next_state_ = STATE_CLOSE; if (next_state_ == STATE_NONE) return; do { State state = next_state_; next_state_ = STATE_NONE; switch (state) { case STATE_BEFORE_CONNECT: DCHECK_EQ(OK, result); result = DoBeforeConnect(); break; case STATE_BEFORE_CONNECT_COMPLETE: result = DoBeforeConnectComplete(result); break; case STATE_RESOLVE_PROXY: DCHECK_EQ(OK, result); result = DoResolveProxy(); break; case STATE_RESOLVE_PROXY_COMPLETE: result = DoResolveProxyComplete(result); break; case STATE_RESOLVE_HOST: DCHECK_EQ(OK, result); result = DoResolveHost(); break; case STATE_RESOLVE_HOST_COMPLETE: result = DoResolveHostComplete(result); break; case STATE_RESOLVE_PROTOCOL: result = DoResolveProtocol(result); break; case STATE_RESOLVE_PROTOCOL_COMPLETE: result = DoResolveProtocolComplete(result); break; case STATE_TCP_CONNECT: result = DoTcpConnect(result); break; case STATE_TCP_CONNECT_COMPLETE: result = DoTcpConnectComplete(result); break; case STATE_GENERATE_PROXY_AUTH_TOKEN: result = DoGenerateProxyAuthToken(); break; case STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE: result = DoGenerateProxyAuthTokenComplete(result); break; case STATE_WRITE_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoWriteTunnelHeaders(); break; case STATE_WRITE_TUNNEL_HEADERS_COMPLETE: result = DoWriteTunnelHeadersComplete(result); break; case STATE_READ_TUNNEL_HEADERS: DCHECK_EQ(OK, result); result = DoReadTunnelHeaders(); break; case STATE_READ_TUNNEL_HEADERS_COMPLETE: result = DoReadTunnelHeadersComplete(result); break; case STATE_SOCKS_CONNECT: DCHECK_EQ(OK, result); result = DoSOCKSConnect(); break; case STATE_SOCKS_CONNECT_COMPLETE: result = DoSOCKSConnectComplete(result); break; case STATE_SECURE_PROXY_CONNECT: DCHECK_EQ(OK, result); result = DoSecureProxyConnect(); break; case STATE_SECURE_PROXY_CONNECT_COMPLETE: result = DoSecureProxyConnectComplete(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR: result = DoSecureProxyHandleCertError(result); break; case STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE: result = DoSecureProxyHandleCertErrorComplete(result); break; case STATE_SSL_CONNECT: DCHECK_EQ(OK, result); result = DoSSLConnect(); break; case STATE_SSL_CONNECT_COMPLETE: result = DoSSLConnectComplete(result); break; case STATE_SSL_HANDLE_CERT_ERROR: result = DoSSLHandleCertError(result); break; case STATE_SSL_HANDLE_CERT_ERROR_COMPLETE: result = DoSSLHandleCertErrorComplete(result); break; case STATE_READ_WRITE: result = DoReadWrite(result); break; case STATE_AUTH_REQUIRED: Finish(result); return; case STATE_CLOSE: DCHECK_LE(result, OK); Finish(result); return; default: NOTREACHED() << "bad state " << state; Finish(result); return; } if (state == STATE_RESOLVE_PROTOCOL && result == ERR_PROTOCOL_SWITCHED) continue; if (state != STATE_READ_WRITE && result < ERR_IO_PENDING) { net_log_.EndEventWithNetErrorCode( NetLog::TYPE_SOCKET_STREAM_CONNECT, result); } } while (result != ERR_IO_PENDING); }
171,254
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<bool> IncludesValueImpl(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); bool search_for_hole = value->IsUndefined(isolate); for (uint32_t k = start_from; k < length; ++k) { uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k, ALL_PROPERTIES); if (entry == kMaxUInt32) { if (search_for_hole) return Just(true); 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<bool>()); if (value->SameValueZero(*element_k)) return Just(true); if (object->map() != *original_map) { return IncludesValueSlowPath(isolate, object, value, k + 1, length); } } else if (value->SameValueZero(*element_k)) { return Just(true); } } return Just(false); } 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<bool> IncludesValueImpl(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); bool search_for_hole = value->IsUndefined(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) { if (search_for_hole) return Just(true); 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<bool>()); if (value->SameValueZero(*element_k)) return Just(true); if (object->map() != *original_map) { return IncludesValueSlowPath(isolate, object, value, k + 1, length); } } else if (value->SameValueZero(*element_k)) { return Just(true); } } return Just(false); }
174,097
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 AudioRendererAlgorithm::OutputSlowerPlayback(uint8* dest) { DCHECK_LT(index_into_window_, window_size_); DCHECK_LT(playback_rate_, 1.0); DCHECK_NE(playback_rate_, 0.0); if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; int input_step = ceil(window_size_ * playback_rate_); AlignToFrameBoundary(&input_step); int output_step = window_size_; DCHECK_LT(input_step, output_step); int bytes_to_crossfade = bytes_in_crossfade_; if (muted_ || bytes_to_crossfade > input_step) bytes_to_crossfade = 0; int intro_crossfade_begin = input_step - bytes_to_crossfade; int intro_crossfade_end = input_step; int outtro_crossfade_begin = output_step - bytes_to_crossfade; if (index_into_window_ < intro_crossfade_begin) { CopyWithAdvance(dest); index_into_window_ += bytes_per_frame_; return true; } if (index_into_window_ < intro_crossfade_end) { int offset = index_into_window_ - intro_crossfade_begin; uint8* place_to_copy = crossfade_buffer_.get() + offset; CopyWithoutAdvance(place_to_copy); CopyWithAdvance(dest); index_into_window_ += bytes_per_frame_; return true; } int audio_buffer_offset = index_into_window_ - intro_crossfade_end; if (audio_buffer_.forward_bytes() < audio_buffer_offset + bytes_per_frame_) return false; DCHECK_GE(index_into_window_, intro_crossfade_end); CopyWithoutAdvance(dest, audio_buffer_offset); if (index_into_window_ >= outtro_crossfade_begin) { int offset_into_crossfade_buffer = index_into_window_ - outtro_crossfade_begin; uint8* intro_frame_ptr = crossfade_buffer_.get() + offset_into_crossfade_buffer; OutputCrossfadedFrame(dest, intro_frame_ptr); } index_into_window_ += bytes_per_frame_; return true; } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool AudioRendererAlgorithm::OutputSlowerPlayback(uint8* dest) { bool AudioRendererAlgorithm::OutputSlowerPlayback(uint8* dest, int input_step, int output_step) { // Ensure we don't run into OOB read/write situation. CHECK_LT(input_step, output_step); DCHECK_LT(index_into_window_, window_size_); DCHECK_LT(playback_rate_, 1.0); DCHECK_NE(playback_rate_, 0.0); if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; int bytes_to_crossfade = bytes_in_crossfade_; if (muted_ || bytes_to_crossfade > input_step) bytes_to_crossfade = 0; int intro_crossfade_begin = input_step - bytes_to_crossfade; int intro_crossfade_end = input_step; int outtro_crossfade_begin = output_step - bytes_to_crossfade; if (index_into_window_ < intro_crossfade_begin) { CopyWithAdvance(dest); index_into_window_ += bytes_per_frame_; return true; } if (index_into_window_ < intro_crossfade_end) { int offset = index_into_window_ - intro_crossfade_begin; uint8* place_to_copy = crossfade_buffer_.get() + offset; CopyWithoutAdvance(place_to_copy); CopyWithAdvance(dest); index_into_window_ += bytes_per_frame_; return true; } int audio_buffer_offset = index_into_window_ - intro_crossfade_end; if (audio_buffer_.forward_bytes() < audio_buffer_offset + bytes_per_frame_) return false; DCHECK_GE(index_into_window_, intro_crossfade_end); CopyWithoutAdvance(dest, audio_buffer_offset); if (index_into_window_ >= outtro_crossfade_begin) { int offset_into_crossfade_buffer = index_into_window_ - outtro_crossfade_begin; uint8* intro_frame_ptr = crossfade_buffer_.get() + offset_into_crossfade_buffer; OutputCrossfadedFrame(dest, intro_frame_ptr); } index_into_window_ += bytes_per_frame_; return true; }
171,529
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: mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy) { mrb_value orig; mrb_value buf; struct mrb_io *fptr_copy; struct mrb_io *fptr_orig; mrb_bool failed = TRUE; mrb_get_args(mrb, "o", &orig); fptr_copy = (struct mrb_io *)DATA_PTR(copy); if (fptr_copy != NULL) { fptr_finalize(mrb, fptr_copy, FALSE); mrb_free(mrb, fptr_copy); } fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb); fptr_orig = io_get_open_fptr(mrb, orig); DATA_TYPE(copy) = &mrb_io_type; DATA_PTR(copy) = fptr_copy; buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, "@buf")); mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, "@buf"), buf); fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed); if (failed) { mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd); if (fptr_orig->fd2 != -1) { fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed); if (failed) { close(fptr_copy->fd); mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd2); } fptr_copy->pid = fptr_orig->pid; fptr_copy->readable = fptr_orig->readable; fptr_copy->writable = fptr_orig->writable; fptr_copy->sync = fptr_orig->sync; fptr_copy->is_socket = fptr_orig->is_socket; return copy; } Commit Message: Fix `use after free in File#initilialize_copy`; fix #4001 The bug and the fix were reported by https://hackerone.com/pnoltof CWE ID: CWE-416
mrb_io_initialize_copy(mrb_state *mrb, mrb_value copy) { mrb_value orig; mrb_value buf; struct mrb_io *fptr_copy; struct mrb_io *fptr_orig; mrb_bool failed = TRUE; mrb_get_args(mrb, "o", &orig); fptr_orig = io_get_open_fptr(mrb, orig); fptr_copy = (struct mrb_io *)DATA_PTR(copy); if (fptr_copy != NULL) { fptr_finalize(mrb, fptr_copy, FALSE); mrb_free(mrb, fptr_copy); } fptr_copy = (struct mrb_io *)mrb_io_alloc(mrb); DATA_TYPE(copy) = &mrb_io_type; DATA_PTR(copy) = fptr_copy; buf = mrb_iv_get(mrb, orig, mrb_intern_cstr(mrb, "@buf")); mrb_iv_set(mrb, copy, mrb_intern_cstr(mrb, "@buf"), buf); fptr_copy->fd = mrb_dup(mrb, fptr_orig->fd, &failed); if (failed) { mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd); if (fptr_orig->fd2 != -1) { fptr_copy->fd2 = mrb_dup(mrb, fptr_orig->fd2, &failed); if (failed) { close(fptr_copy->fd); mrb_sys_fail(mrb, 0); } mrb_fd_cloexec(mrb, fptr_copy->fd2); } fptr_copy->pid = fptr_orig->pid; fptr_copy->readable = fptr_orig->readable; fptr_copy->writable = fptr_orig->writable; fptr_copy->sync = fptr_orig->sync; fptr_copy->is_socket = fptr_orig->is_socket; return copy; }
169,255
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 fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction) { FDrive *cur_drv = get_cur_drv(fdctrl); if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x80) { /* Command parameters done */ if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x40) { fdctrl->fifo[0] = fdctrl->fifo[1]; fdctrl->fifo[2] = 0; fdctrl->fifo[3] = 0; } } else if (fdctrl->data_len > 7) { /* ERROR */ fdctrl->fifo[0] = 0x80 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl); fdctrl_set_fifo(fdctrl, 1); } } Commit Message: CWE ID: CWE-119
static void fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction) { FDrive *cur_drv = get_cur_drv(fdctrl); uint32_t pos; pos = fdctrl->data_pos - 1; pos %= FD_SECTOR_LEN; if (fdctrl->fifo[pos] & 0x80) { /* Command parameters done */ if (fdctrl->fifo[pos] & 0x40) { fdctrl->fifo[0] = fdctrl->fifo[1]; fdctrl->fifo[2] = 0; fdctrl->fifo[3] = 0; } } else if (fdctrl->data_len > 7) { /* ERROR */ fdctrl->fifo[0] = 0x80 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl); fdctrl_set_fifo(fdctrl, 1); } }
164,706
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: nfsd4_set_nfs4_acl(struct svc_rqst *rqstp, struct svc_fh *fhp, struct nfs4_acl *acl) { __be32 error; int host_error; struct dentry *dentry; struct inode *inode; struct posix_acl *pacl = NULL, *dpacl = NULL; unsigned int flags = 0; /* Get inode */ error = fh_verify(rqstp, fhp, 0, NFSD_MAY_SATTR); if (error) return error; dentry = fhp->fh_dentry; inode = d_inode(dentry); if (!inode->i_op->set_acl || !IS_POSIXACL(inode)) return nfserr_attrnotsupp; if (S_ISDIR(inode->i_mode)) flags = NFS4_ACL_DIR; host_error = nfs4_acl_nfsv4_to_posix(acl, &pacl, &dpacl, flags); if (host_error == -EINVAL) return nfserr_attrnotsupp; if (host_error < 0) goto out_nfserr; host_error = inode->i_op->set_acl(inode, pacl, ACL_TYPE_ACCESS); if (host_error < 0) goto out_release; if (S_ISDIR(inode->i_mode)) { host_error = inode->i_op->set_acl(inode, dpacl, ACL_TYPE_DEFAULT); } out_release: posix_acl_release(pacl); posix_acl_release(dpacl); out_nfserr: if (host_error == -EOPNOTSUPP) return nfserr_attrnotsupp; else return nfserrno(host_error); } Commit Message: nfsd: check permissions when setting ACLs Use set_posix_acl, which includes proper permission checks, instead of calling ->set_acl directly. Without this anyone may be able to grant themselves permissions to a file by setting the ACL. Lock the inode to make the new checks atomic with respect to set_acl. (Also, nfsd was the only caller of set_acl not locking the inode, so I suspect this may fix other races.) This also simplifies the code, and ensures our ACLs are checked by posix_acl_valid. The permission checks and the inode locking were lost with commit 4ac7249e, which changed nfsd to use the set_acl inode operation directly instead of going through xattr handlers. Reported-by: David Sinquin <[email protected]> [[email protected]: use set_posix_acl] Fixes: 4ac7249e Cc: Christoph Hellwig <[email protected]> Cc: Al Viro <[email protected]> Cc: [email protected] Signed-off-by: J. Bruce Fields <[email protected]> CWE ID: CWE-284
nfsd4_set_nfs4_acl(struct svc_rqst *rqstp, struct svc_fh *fhp, struct nfs4_acl *acl) { __be32 error; int host_error; struct dentry *dentry; struct inode *inode; struct posix_acl *pacl = NULL, *dpacl = NULL; unsigned int flags = 0; /* Get inode */ error = fh_verify(rqstp, fhp, 0, NFSD_MAY_SATTR); if (error) return error; dentry = fhp->fh_dentry; inode = d_inode(dentry); if (S_ISDIR(inode->i_mode)) flags = NFS4_ACL_DIR; host_error = nfs4_acl_nfsv4_to_posix(acl, &pacl, &dpacl, flags); if (host_error == -EINVAL) return nfserr_attrnotsupp; if (host_error < 0) goto out_nfserr; fh_lock(fhp); host_error = set_posix_acl(inode, ACL_TYPE_ACCESS, pacl); if (host_error < 0) goto out_drop_lock; if (S_ISDIR(inode->i_mode)) { host_error = set_posix_acl(inode, ACL_TYPE_DEFAULT, dpacl); } out_drop_lock: fh_unlock(fhp); posix_acl_release(pacl); posix_acl_release(dpacl); out_nfserr: if (host_error == -EOPNOTSUPP) return nfserr_attrnotsupp; else return nfserrno(host_error); }
167,449
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: ssize_t MPEG4DataSource::readAt(off64_t offset, void *data, size_t size) { Mutex::Autolock autoLock(mLock); if (offset >= mCachedOffset && offset + size <= mCachedOffset + mCachedSize) { memcpy(data, &mCache[offset - mCachedOffset], size); return size; } return mSource->readAt(offset, data, size); } Commit Message: Add AUtils::isInRange, and use it to detect malformed MPEG4 nal sizes Bug: 19641538 Change-Id: I5aae3f100846c125decc61eec7cd6563e3f33777 CWE ID: CWE-119
ssize_t MPEG4DataSource::readAt(off64_t offset, void *data, size_t size) { Mutex::Autolock autoLock(mLock); if (isInRange(mCachedOffset, mCachedSize, offset, size)) { memcpy(data, &mCache[offset - mCachedOffset], size); return size; } return mSource->readAt(offset, data, size); }
173,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: image_transform_png_set_strip_16_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth > 8; } 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_strip_16_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth > 8; }
173,648
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: virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual bool SetImeConfig(const std::string& section, const std::string& config_name, const input_method::ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && value.type == input_method::ImeConfigValue::kValueTypeStringList) { active_input_method_ids_ = value.string_list_value; } MaybeStartInputMethodDaemon(section, config_name, value); const ConfigKeyType key = std::make_pair(section, config_name); current_config_values_[key] = value; if (ime_connected_) { pending_config_requests_[key] = value; FlushImeConfig(); } MaybeStopInputMethodDaemon(section, config_name, value); MaybeChangeCurrentKeyboardLayout(section, config_name, value); return pending_config_requests_.empty(); }
170,505
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 get_refcount(BlockDriverState *bs, int64_t cluster_index) { BDRVQcowState *s = bs->opaque; int refcount_table_index, block_index; int64_t refcount_block_offset; int ret; uint16_t *refcount_block; uint16_t refcount; refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT); if (refcount_table_index >= s->refcount_table_size) return 0; refcount_block_offset = s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK; if (!refcount_block_offset) return 0; ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset, (void**) &refcount_block); if (ret < 0) { return ret; } block_index = cluster_index & ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1); refcount = be16_to_cpu(refcount_block[block_index]); ret = qcow2_cache_put(bs, s->refcount_block_cache, (void**) &refcount_block); if (ret < 0) { return ret; } return refcount; } Commit Message: CWE ID: CWE-190
static int get_refcount(BlockDriverState *bs, int64_t cluster_index) { BDRVQcowState *s = bs->opaque; uint64_t refcount_table_index, block_index; int64_t refcount_block_offset; int ret; uint16_t *refcount_block; uint16_t refcount; refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT); if (refcount_table_index >= s->refcount_table_size) return 0; refcount_block_offset = s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK; if (!refcount_block_offset) return 0; ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset, (void**) &refcount_block); if (ret < 0) { return ret; } block_index = cluster_index & ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1); refcount = be16_to_cpu(refcount_block[block_index]); ret = qcow2_cache_put(bs, s->refcount_block_cache, (void**) &refcount_block); if (ret < 0) { return ret; } return refcount; }
165,405
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: mobility_opt_print(netdissect_options *ndo, const u_char *bp, const unsigned len) { unsigned i, optlen; for (i = 0; i < len; i += optlen) { ND_TCHECK(bp[i]); if (bp[i] == IP6MOPT_PAD1) optlen = 1; else { if (i + 1 < len) { ND_TCHECK(bp[i + 1]); optlen = bp[i + 1] + 2; } else goto trunc; } if (i + optlen > len) goto trunc; ND_TCHECK(bp[i + optlen]); switch (bp[i]) { case IP6MOPT_PAD1: ND_PRINT((ndo, "(pad1)")); break; case IP6MOPT_PADN: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(padn: trunc)")); goto trunc; } ND_PRINT((ndo, "(padn)")); break; case IP6MOPT_REFRESH: if (len - i < IP6MOPT_REFRESH_MINLEN) { ND_PRINT((ndo, "(refresh: trunc)")); goto trunc; } /* units of 4 secs */ ND_PRINT((ndo, "(refresh: %u)", EXTRACT_16BITS(&bp[i+2]) << 2)); break; case IP6MOPT_ALTCOA: if (len - i < IP6MOPT_ALTCOA_MINLEN) { ND_PRINT((ndo, "(altcoa: trunc)")); goto trunc; } ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2]))); break; case IP6MOPT_NONCEID: if (len - i < IP6MOPT_NONCEID_MINLEN) { ND_PRINT((ndo, "(ni: trunc)")); goto trunc; } ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)", EXTRACT_16BITS(&bp[i+2]), EXTRACT_16BITS(&bp[i+4]))); break; case IP6MOPT_AUTH: if (len - i < IP6MOPT_AUTH_MINLEN) { ND_PRINT((ndo, "(auth: trunc)")); goto trunc; } ND_PRINT((ndo, "(auth)")); break; default: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i])); goto trunc; } ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1])); break; } } return 0; trunc: return 1; } Commit Message: CVE-2017-13023/IPv6 mobility: Add a bounds check before fetching data This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't cause 'tcpdump: pcap_loop: truncated dump file' CWE ID: CWE-125
mobility_opt_print(netdissect_options *ndo, const u_char *bp, const unsigned len) { unsigned i, optlen; for (i = 0; i < len; i += optlen) { ND_TCHECK(bp[i]); if (bp[i] == IP6MOPT_PAD1) optlen = 1; else { if (i + 1 < len) { ND_TCHECK(bp[i + 1]); optlen = bp[i + 1] + 2; } else goto trunc; } if (i + optlen > len) goto trunc; ND_TCHECK(bp[i + optlen]); switch (bp[i]) { case IP6MOPT_PAD1: ND_PRINT((ndo, "(pad1)")); break; case IP6MOPT_PADN: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(padn: trunc)")); goto trunc; } ND_PRINT((ndo, "(padn)")); break; case IP6MOPT_REFRESH: if (len - i < IP6MOPT_REFRESH_MINLEN) { ND_PRINT((ndo, "(refresh: trunc)")); goto trunc; } /* units of 4 secs */ ND_TCHECK_16BITS(&bp[i+2]); ND_PRINT((ndo, "(refresh: %u)", EXTRACT_16BITS(&bp[i+2]) << 2)); break; case IP6MOPT_ALTCOA: if (len - i < IP6MOPT_ALTCOA_MINLEN) { ND_PRINT((ndo, "(altcoa: trunc)")); goto trunc; } ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2]))); break; case IP6MOPT_NONCEID: if (len - i < IP6MOPT_NONCEID_MINLEN) { ND_PRINT((ndo, "(ni: trunc)")); goto trunc; } ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)", EXTRACT_16BITS(&bp[i+2]), EXTRACT_16BITS(&bp[i+4]))); break; case IP6MOPT_AUTH: if (len - i < IP6MOPT_AUTH_MINLEN) { ND_PRINT((ndo, "(auth: trunc)")); goto trunc; } ND_PRINT((ndo, "(auth)")); break; default: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i])); goto trunc; } ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1])); break; } } return 0; trunc: return 1; }
167,868
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: std::string ExtensionTtsPlatformImpl::error() { return error_; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
std::string ExtensionTtsPlatformImpl::error() {
170,394
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: isofs_export_encode_fh(struct inode *inode, __u32 *fh32, int *max_len, struct inode *parent) { struct iso_inode_info * ei = ISOFS_I(inode); int len = *max_len; int type = 1; __u16 *fh16 = (__u16*)fh32; /* * WARNING: max_len is 5 for NFSv2. Because of this * limitation, we use the lower 16 bits of fh32[1] to hold the * offset of the inode and the upper 16 bits of fh32[1] to * hold the offset of the parent. */ if (parent && (len < 5)) { *max_len = 5; return 255; } else if (len < 3) { *max_len = 3; return 255; } len = 3; fh32[0] = ei->i_iget5_block; fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */ fh32[2] = inode->i_generation; if (parent) { struct iso_inode_info *eparent; eparent = ISOFS_I(parent); fh32[3] = eparent->i_iget5_block; fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */ fh32[4] = parent->i_generation; len = 5; type = 2; } *max_len = len; return type; } Commit Message: isofs: avoid info leak on export For type 1 the parent_offset member in struct isofs_fid gets copied uninitialized to userland. Fix this by initializing it to 0. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-200
isofs_export_encode_fh(struct inode *inode, __u32 *fh32, int *max_len, struct inode *parent) { struct iso_inode_info * ei = ISOFS_I(inode); int len = *max_len; int type = 1; __u16 *fh16 = (__u16*)fh32; /* * WARNING: max_len is 5 for NFSv2. Because of this * limitation, we use the lower 16 bits of fh32[1] to hold the * offset of the inode and the upper 16 bits of fh32[1] to * hold the offset of the parent. */ if (parent && (len < 5)) { *max_len = 5; return 255; } else if (len < 3) { *max_len = 3; return 255; } len = 3; fh32[0] = ei->i_iget5_block; fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */ fh16[3] = 0; /* avoid leaking uninitialized data */ fh32[2] = inode->i_generation; if (parent) { struct iso_inode_info *eparent; eparent = ISOFS_I(parent); fh32[3] = eparent->i_iget5_block; fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */ fh32[4] = parent->i_generation; len = 5; type = 2; } *max_len = len; return type; }
166,177
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: grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf, struct grub_ext4_extent_header *ext_block, grub_uint32_t fileblock) { struct grub_ext4_extent_idx *index; while (1) { int i; grub_disk_addr_t block; index = (struct grub_ext4_extent_idx *) (ext_block + 1); if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC) return 0; if (ext_block->depth == 0) return ext_block; for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++) { if (fileblock < grub_le_to_cpu32(index[i].block)) break; } if (--i < 0) return 0; block = grub_le_to_cpu16 (index[i].leaf_hi); block = (block << 32) + grub_le_to_cpu32 (index[i].leaf); if (grub_disk_read (data->disk, block << LOG2_EXT2_BLOCK_SIZE (data), 0, EXT2_BLOCK_SIZE(data), buf)) return 0; ext_block = (struct grub_ext4_extent_header *) buf; } } Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack CWE ID: CWE-119
grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf, struct grub_ext4_extent_header *ext_block, grub_uint32_t fileblock) { struct grub_ext4_extent_idx *index; while (1) { int i; grub_disk_addr_t block; index = (struct grub_ext4_extent_idx *) (ext_block + 1); if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC) return 0; if (ext_block->depth == 0) return ext_block; for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++) { if (fileblock < grub_le_to_cpu32(index[i].block)) break; } if (--i < 0) return 0; block = grub_le_to_cpu16 (index[i].leaf_hi); block = (block << 32) + grub_le_to_cpu32 (index[i].leaf); if (grub_disk_read (data->disk, block << LOG2_EXT2_BLOCK_SIZE (data), 0, EXT2_BLOCK_SIZE(data), buf)) { return 0; } ext_block = (struct grub_ext4_extent_header *) buf; } }
168,088
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: PageGroupLoadDeferrer::PageGroupLoadDeferrer(Page* page, bool deferSelf) { const HashSet<Page*>& pages = page->group().pages(); HashSet<Page*>::const_iterator end = pages.end(); for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) { Page* otherPage = *it; if ((deferSelf || otherPage != page)) { if (!otherPage->defersLoading()) { m_deferredFrames.append(otherPage->mainFrame()); for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) frame->document()->suspendScheduledTasks(ActiveDOMObject::WillDeferLoading); } } } size_t count = m_deferredFrames.size(); for (size_t i = 0; i < count; ++i) if (Page* page = m_deferredFrames[i]->page()) page->setDefersLoading(true); } Commit Message: Don't wait to notify client of spoof attempt if a modal dialog is created. BUG=281256 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23620020 git-svn-id: svn://svn.chromium.org/blink/trunk@157196 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
PageGroupLoadDeferrer::PageGroupLoadDeferrer(Page* page, bool deferSelf) { const HashSet<Page*>& pages = page->group().pages(); HashSet<Page*>::const_iterator end = pages.end(); for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) { Page* otherPage = *it; if ((deferSelf || otherPage != page)) { if (!otherPage->defersLoading()) { m_deferredFrames.append(otherPage->mainFrame()); // Ensure that we notify the client if the initial empty document is accessed before showing anything // modal, to prevent spoofs while the modal window or sheet is visible. otherPage->mainFrame()->loader()->notifyIfInitialDocumentAccessed(); for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) frame->document()->suspendScheduledTasks(ActiveDOMObject::WillDeferLoading); } } } size_t count = m_deferredFrames.size(); for (size_t i = 0; i < count; ++i) if (Page* page = m_deferredFrames[i]->page()) page->setDefersLoading(true); }
171,190
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 do_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { pgoff_t pgoff = (((address & PAGE_MASK) - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; pte_unmap(page_table); if (!(flags & FAULT_FLAG_WRITE)) return do_read_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); if (!(vma->vm_flags & VM_SHARED)) return do_cow_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); return do_shared_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); } Commit Message: mm: avoid setting up anonymous pages into file mapping Reading page fault handler code I've noticed that under right circumstances kernel would map anonymous pages into file mappings: if the VMA doesn't have vm_ops->fault() and the VMA wasn't fully populated on ->mmap(), kernel would handle page fault to not populated pte with do_anonymous_page(). Let's change page fault handler to use do_anonymous_page() only on anonymous VMA (->vm_ops == NULL) and make sure that the VMA is not shared. For file mappings without vm_ops->fault() or shred VMA without vm_ops, page fault on pte_none() entry would lead to SIGBUS. Signed-off-by: Kirill A. Shutemov <[email protected]> Acked-by: Oleg Nesterov <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20
static int do_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags, pte_t orig_pte) { pgoff_t pgoff = (((address & PAGE_MASK) - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; pte_unmap(page_table); /* The VMA was not fully populated on mmap() or missing VM_DONTEXPAND */ if (!vma->vm_ops->fault) return VM_FAULT_SIGBUS; if (!(flags & FAULT_FLAG_WRITE)) return do_read_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); if (!(vma->vm_flags & VM_SHARED)) return do_cow_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); return do_shared_fault(mm, vma, address, pmd, pgoff, flags, orig_pte); }
167,568
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_FUNCTION(move_uploaded_file) { char *path, *new_path; int path_len, new_path_len; zend_bool successful = 0; #ifndef PHP_WIN32 int oldmask; int ret; #endif if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &new_path, &new_path_len) == FAILURE) { return; } if (!zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_FALSE; } if (php_check_open_basedir(new_path TSRMLS_CC)) { RETURN_FALSE; } if (VCWD_RENAME(path, new_path) == 0) { successful = 1; #ifndef PHP_WIN32 oldmask = umask(077); umask(oldmask); ret = VCWD_CHMOD(new_path, 0666 & ~oldmask); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } #endif } else if (php_copy_file_ex(path, new_path, STREAM_DISABLE_OPEN_BASEDIR TSRMLS_CC) == SUCCESS) { VCWD_UNLINK(path); successful = 1; } if (successful) { zend_hash_del(SG(rfc1867_uploaded_files), path, path_len + 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to move '%s' to '%s'", path, new_path); } RETURN_BOOL(successful); } Commit Message: CWE ID: CWE-264
PHP_FUNCTION(move_uploaded_file) { char *path, *new_path; int path_len, new_path_len; zend_bool successful = 0; #ifndef PHP_WIN32 int oldmask; int ret; #endif if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp", &path, &path_len, &new_path, &new_path_len) == FAILURE) { return; } if (!zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_FALSE; } if (php_check_open_basedir(new_path TSRMLS_CC)) { RETURN_FALSE; } if (VCWD_RENAME(path, new_path) == 0) { successful = 1; #ifndef PHP_WIN32 oldmask = umask(077); umask(oldmask); ret = VCWD_CHMOD(new_path, 0666 & ~oldmask); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } #endif } else if (php_copy_file_ex(path, new_path, STREAM_DISABLE_OPEN_BASEDIR TSRMLS_CC) == SUCCESS) { VCWD_UNLINK(path); successful = 1; } if (successful) { zend_hash_del(SG(rfc1867_uploaded_files), path, path_len + 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to move '%s' to '%s'", path, new_path); } RETURN_BOOL(successful); }
164,751
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 ThreadableBlobRegistry::unregisterBlobURL(const KURL& url) { if (BlobURL::getOrigin(url) == "null") originMap()->remove(url.string()); if (isMainThread()) blobRegistry().unregisterBlobURL(url); else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url)); callOnMainThread(&unregisterBlobURLTask, context.leakPtr()); } } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void ThreadableBlobRegistry::unregisterBlobURL(const KURL& url) void BlobRegistry::unregisterBlobURL(const KURL& url) { if (BlobURL::getOrigin(url) == "null") originMap()->remove(url.string()); if (isMainThread()) { if (WebBlobRegistry* registry = blobRegistry()) registry->unregisterBlobURL(url); } else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url)); callOnMainThread(&unregisterBlobURLTask, context.leakPtr()); } }
170,690
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 ExtensionServiceBackend::LoadSingleExtension(const FilePath& path_in) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath extension_path = path_in; file_util::AbsolutePath(&extension_path); int flags = Extension::ShouldAlwaysAllowFileAccess(Extension::LOAD) ? Extension::ALLOW_FILE_ACCESS : Extension::NO_FLAGS; if (Extension::ShouldDoStrictErrorChecking(Extension::LOAD)) flags |= Extension::STRICT_ERROR_CHECKS; std::string error; scoped_refptr<const Extension> extension(extension_file_util::LoadExtension( extension_path, Extension::LOAD, flags, &error)); if (!extension) { if (!BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionServiceBackend::ReportExtensionLoadError, extension_path, error))) NOTREACHED() << error; return; } if (!BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionServiceBackend::OnExtensionInstalled, extension))) NOTREACHED(); } Commit Message: Unrevert: Show the install dialog for the initial load of an unpacked extension with plugins. First landing broke some browser tests. BUG=83273 TEST=in the extensions managmenet page, with developer mode enabled, Load an unpacked extension on an extension with NPAPI plugins. You should get an install dialog. TBR=mihaip git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87738 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionServiceBackend::LoadSingleExtension(const FilePath& path_in) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath extension_path = path_in; file_util::AbsolutePath(&extension_path); int flags = Extension::ShouldAlwaysAllowFileAccess(Extension::LOAD) ? Extension::ALLOW_FILE_ACCESS : Extension::NO_FLAGS; if (Extension::ShouldDoStrictErrorChecking(Extension::LOAD)) flags |= Extension::STRICT_ERROR_CHECKS; std::string error; scoped_refptr<const Extension> extension(extension_file_util::LoadExtension( extension_path, Extension::LOAD, flags, &error)); if (!extension) { if (!BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionServiceBackend::ReportExtensionLoadError, extension_path, error))) NOTREACHED() << error; return; } if (!BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionServiceBackend::OnLoadSingleExtension, extension))) NOTREACHED(); }
170,407
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: chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto; const u_char *bp = p; if (length < CHDLC_HDRLEN) goto trunc; ND_TCHECK2(*p, CHDLC_HDRLEN); proto = EXTRACT_16BITS(&p[2]); if (ndo->ndo_eflag) { ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ", tok2str(chdlc_cast_values, "0x%02x", p[0]), tok2str(ethertype_values, "Unknown", proto), proto, length)); } length -= CHDLC_HDRLEN; p += CHDLC_HDRLEN; switch (proto) { case ETHERTYPE_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: ip6_print(ndo, p, length); break; case CHDLC_TYPE_SLARP: chdlc_slarp_print(ndo, p, length); break; #if 0 case CHDLC_TYPE_CDP: chdlc_cdp_print(p, length); break; #endif case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); break; case ETHERTYPE_ISO: /* is the fudge byte set ? lets verify by spotting ISO headers */ if (length < 2) goto trunc; ND_TCHECK_16BITS(p); if (*(p+1) == 0x81 || *(p+1) == 0x82 || *(p+1) == 0x83) isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1); else isoclns_print(ndo, p, length, ndo->ndo_snapend - p); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto)); break; } return (CHDLC_HDRLEN); trunc: ND_PRINT((ndo, "[|chdlc]")); return ndo->ndo_snapend - bp; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto; const u_char *bp = p; if (length < CHDLC_HDRLEN) goto trunc; ND_TCHECK2(*p, CHDLC_HDRLEN); proto = EXTRACT_16BITS(&p[2]); if (ndo->ndo_eflag) { ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ", tok2str(chdlc_cast_values, "0x%02x", p[0]), tok2str(ethertype_values, "Unknown", proto), proto, length)); } length -= CHDLC_HDRLEN; p += CHDLC_HDRLEN; switch (proto) { case ETHERTYPE_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: ip6_print(ndo, p, length); break; case CHDLC_TYPE_SLARP: chdlc_slarp_print(ndo, p, length); break; #if 0 case CHDLC_TYPE_CDP: chdlc_cdp_print(p, length); break; #endif case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); break; case ETHERTYPE_ISO: /* is the fudge byte set ? lets verify by spotting ISO headers */ if (length < 2) goto trunc; ND_TCHECK_16BITS(p); if (*(p+1) == 0x81 || *(p+1) == 0x82 || *(p+1) == 0x83) isoclns_print(ndo, p + 1, length - 1); else isoclns_print(ndo, p, length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto)); break; } return (CHDLC_HDRLEN); trunc: ND_PRINT((ndo, "[|chdlc]")); return ndo->ndo_snapend - bp; }
167,943
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: gplotRead(const char *filename) { char buf[L_BUF_SIZE]; char *rootname, *title, *xlabel, *ylabel, *ignores; l_int32 outformat, ret, version, ignore; FILE *fp; GPLOT *gplot; PROCNAME("gplotRead"); if (!filename) return (GPLOT *)ERROR_PTR("filename not defined", procName, NULL); if ((fp = fopenReadStream(filename)) == NULL) return (GPLOT *)ERROR_PTR("stream not opened", procName, NULL); ret = fscanf(fp, "Gplot Version %d\n", &version); if (ret != 1) { fclose(fp); return (GPLOT *)ERROR_PTR("not a gplot file", procName, NULL); } if (version != GPLOT_VERSION_NUMBER) { fclose(fp); return (GPLOT *)ERROR_PTR("invalid gplot version", procName, NULL); } ignore = fscanf(fp, "Rootname: %s\n", buf); rootname = stringNew(buf); ignore = fscanf(fp, "Output format: %d\n", &outformat); ignores = fgets(buf, L_BUF_SIZE, fp); /* Title: ... */ title = stringNew(buf + 7); title[strlen(title) - 1] = '\0'; ignores = fgets(buf, L_BUF_SIZE, fp); /* X axis label: ... */ xlabel = stringNew(buf + 14); xlabel[strlen(xlabel) - 1] = '\0'; ignores = fgets(buf, L_BUF_SIZE, fp); /* Y axis label: ... */ ylabel = stringNew(buf + 14); ylabel[strlen(ylabel) - 1] = '\0'; gplot = gplotCreate(rootname, outformat, title, xlabel, ylabel); LEPT_FREE(rootname); LEPT_FREE(title); LEPT_FREE(xlabel); LEPT_FREE(ylabel); if (!gplot) { fclose(fp); return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL); } sarrayDestroy(&gplot->cmddata); sarrayDestroy(&gplot->datanames); sarrayDestroy(&gplot->plotdata); sarrayDestroy(&gplot->plottitles); numaDestroy(&gplot->plotstyles); ignore = fscanf(fp, "Commandfile name: %s\n", buf); stringReplace(&gplot->cmdname, buf); ignore = fscanf(fp, "\nCommandfile data:"); gplot->cmddata = sarrayReadStream(fp); ignore = fscanf(fp, "\nDatafile names:"); gplot->datanames = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot data:"); gplot->plotdata = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot titles:"); gplot->plottitles = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot styles:"); gplot->plotstyles = numaReadStream(fp); ignore = fscanf(fp, "Number of plots: %d\n", &gplot->nplots); ignore = fscanf(fp, "Output file name: %s\n", buf); stringReplace(&gplot->outname, buf); ignore = fscanf(fp, "Axis scaling: %d\n", &gplot->scaling); fclose(fp); return gplot; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
gplotRead(const char *filename) { char buf[L_BUFSIZE]; char *rootname, *title, *xlabel, *ylabel, *ignores; l_int32 outformat, ret, version, ignore; FILE *fp; GPLOT *gplot; PROCNAME("gplotRead"); if (!filename) return (GPLOT *)ERROR_PTR("filename not defined", procName, NULL); if ((fp = fopenReadStream(filename)) == NULL) return (GPLOT *)ERROR_PTR("stream not opened", procName, NULL); ret = fscanf(fp, "Gplot Version %d\n", &version); if (ret != 1) { fclose(fp); return (GPLOT *)ERROR_PTR("not a gplot file", procName, NULL); } if (version != GPLOT_VERSION_NUMBER) { fclose(fp); return (GPLOT *)ERROR_PTR("invalid gplot version", procName, NULL); } ignore = fscanf(fp, "Rootname: %511s\n", buf); /* L_BUFSIZE - 1 */ rootname = stringNew(buf); ignore = fscanf(fp, "Output format: %d\n", &outformat); ignores = fgets(buf, L_BUFSIZE, fp); /* Title: ... */ title = stringNew(buf + 7); title[strlen(title) - 1] = '\0'; ignores = fgets(buf, L_BUFSIZE, fp); /* X axis label: ... */ xlabel = stringNew(buf + 14); xlabel[strlen(xlabel) - 1] = '\0'; ignores = fgets(buf, L_BUFSIZE, fp); /* Y axis label: ... */ ylabel = stringNew(buf + 14); ylabel[strlen(ylabel) - 1] = '\0'; gplot = gplotCreate(rootname, outformat, title, xlabel, ylabel); LEPT_FREE(rootname); LEPT_FREE(title); LEPT_FREE(xlabel); LEPT_FREE(ylabel); if (!gplot) { fclose(fp); return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL); } sarrayDestroy(&gplot->cmddata); sarrayDestroy(&gplot->datanames); sarrayDestroy(&gplot->plotdata); sarrayDestroy(&gplot->plottitles); numaDestroy(&gplot->plotstyles); ignore = fscanf(fp, "Commandfile name: %511s\n", buf); /* L_BUFSIZE - 1 */ stringReplace(&gplot->cmdname, buf); ignore = fscanf(fp, "\nCommandfile data:"); gplot->cmddata = sarrayReadStream(fp); ignore = fscanf(fp, "\nDatafile names:"); gplot->datanames = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot data:"); gplot->plotdata = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot titles:"); gplot->plottitles = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot styles:"); gplot->plotstyles = numaReadStream(fp); ignore = fscanf(fp, "Number of plots: %d\n", &gplot->nplots); ignore = fscanf(fp, "Output file name: %511s\n", buf); stringReplace(&gplot->outname, buf); ignore = fscanf(fp, "Axis scaling: %d\n", &gplot->scaling); fclose(fp); return gplot; }
169,327
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: iakerb_gss_delete_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token) { OM_uint32 major_status = GSS_S_COMPLETE; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } *minor_status = 0; if (*context_handle != GSS_C_NO_CONTEXT) { iakerb_ctx_id_t iakerb_ctx = (iakerb_ctx_id_t)*context_handle; if (iakerb_ctx->magic == KG_IAKERB_CONTEXT) { iakerb_release_context(iakerb_ctx); *context_handle = GSS_C_NO_CONTEXT; } else { assert(iakerb_ctx->magic == KG_CONTEXT); major_status = krb5_gss_delete_sec_context(minor_status, context_handle, output_token); } } return major_status; } Commit Message: Fix IAKERB context aliasing bugs [CVE-2015-2696] The IAKERB mechanism currently replaces its context handle with the krb5 mechanism handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the IAKERB context structure after context establishment and add new IAKERB entry points to refer to it with that type. Add initiate and established flags to the IAKERB context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2696: In MIT krb5 1.9 and later, applications which call gss_inquire_context() on a partially-established IAKERB context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted IAKERB packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
iakerb_gss_delete_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t output_token) { iakerb_ctx_id_t iakerb_ctx = (iakerb_ctx_id_t)*context_handle; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } *minor_status = 0; *context_handle = GSS_C_NO_CONTEXT; iakerb_release_context(iakerb_ctx); return GSS_S_COMPLETE; }
166,645
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: SPL_METHOD(SplFileObject, setCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = ',', enclosure = '"', escape='\\'; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } intern->u.file.delimiter = delimiter; intern->u.file.enclosure = enclosure; intern->u.file.escape = escape; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, setCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = ',', enclosure = '"', escape='\\'; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } intern->u.file.delimiter = delimiter; intern->u.file.enclosure = enclosure; intern->u.file.escape = escape; } }
167,063
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 char *rfc2047_decode_word(const char *s, size_t len, enum ContentEncoding enc) { const char *it = s; const char *end = s + len; if (enc == ENCQUOTEDPRINTABLE) { struct Buffer buf = { 0 }; for (; it < end; ++it) { if (*it == '_') { mutt_buffer_addch(&buf, ' '); } else if ((*it == '=') && (!(it[1] & ~127) && hexval(it[1]) != -1) && (!(it[2] & ~127) && hexval(it[2]) != -1)) { mutt_buffer_addch(&buf, (hexval(it[1]) << 4) | hexval(it[2])); it += 2; } else { mutt_buffer_addch(&buf, *it); } } mutt_buffer_addch(&buf, '\0'); return buf.data; } else if (enc == ENCBASE64) { char *out = mutt_mem_malloc(3 * len / 4 + 1); int dlen = mutt_b64_decode(out, it); if (dlen == -1) { FREE(&out); return NULL; } out[dlen] = '\0'; return out; } assert(0); /* The enc parameter has an invalid value */ return NULL; } Commit Message: Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report. CWE ID: CWE-119
static char *rfc2047_decode_word(const char *s, size_t len, enum ContentEncoding enc) { const char *it = s; const char *end = s + len; if (enc == ENCQUOTEDPRINTABLE) { struct Buffer buf = { 0 }; for (; it < end; ++it) { if (*it == '_') { mutt_buffer_addch(&buf, ' '); } else if ((*it == '=') && (!(it[1] & ~127) && hexval(it[1]) != -1) && (!(it[2] & ~127) && hexval(it[2]) != -1)) { mutt_buffer_addch(&buf, (hexval(it[1]) << 4) | hexval(it[2])); it += 2; } else { mutt_buffer_addch(&buf, *it); } } mutt_buffer_addch(&buf, '\0'); return buf.data; } else if (enc == ENCBASE64) { const int olen = 3 * len / 4 + 1; char *out = mutt_mem_malloc(olen); int dlen = mutt_b64_decode(out, it, olen); if (dlen == -1) { FREE(&out); return NULL; } out[dlen] = '\0'; return out; } assert(0); /* The enc parameter has an invalid value */ return NULL; }
169,129
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: cJSON *cJSON_CreateFalse( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_False; return item; } 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 <[email protected]> CWE ID: CWE-119
cJSON *cJSON_CreateFalse( void )
167,271
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 mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_mpi r, s; ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); ECDSA_VALIDATE_RET( slen != NULL ); mbedtls_mpi_init( &r ); mbedtls_mpi_init( &s ); #if defined(MBEDTLS_ECDSA_DETERMINISTIC) (void) f_rng; (void) p_rng; MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d, hash, hlen, md_alg, rs_ctx ) ); #else (void) md_alg; #if defined(MBEDTLS_ECDSA_SIGN_ALT) MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng ) ); #else MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng, rs_ctx ) ); #endif /* MBEDTLS_ECDSA_SIGN_ALT */ #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) ); cleanup: mbedtls_mpi_free( &r ); mbedtls_mpi_free( &s ); return( ret ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted CWE ID: CWE-200
int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_mpi r, s; ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); ECDSA_VALIDATE_RET( slen != NULL ); mbedtls_mpi_init( &r ); mbedtls_mpi_init( &s ); #if defined(MBEDTLS_ECDSA_DETERMINISTIC) MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d, hash, hlen, md_alg, f_rng, p_rng, rs_ctx ) ); #else (void) md_alg; #if defined(MBEDTLS_ECDSA_SIGN_ALT) MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng ) ); #else /* Use the same RNG for both blinding and ephemeral key generation */ MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng, f_rng, p_rng, rs_ctx ) ); #endif /* MBEDTLS_ECDSA_SIGN_ALT */ #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) ); cleanup: mbedtls_mpi_free( &r ); mbedtls_mpi_free( &s ); return( ret ); }
169,509
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 ssize_t generic_perform_write(struct file *file, struct iov_iter *i, loff_t pos) { struct address_space *mapping = file->f_mapping; const struct address_space_operations *a_ops = mapping->a_ops; long status = 0; ssize_t written = 0; unsigned int flags = 0; /* * Copies from kernel address space cannot fail (NFSD is a big user). */ if (segment_eq(get_fs(), KERNEL_DS)) flags |= AOP_FLAG_UNINTERRUPTIBLE; do { struct page *page; pgoff_t index; /* Pagecache index for current page */ unsigned long offset; /* Offset into pagecache page */ unsigned long bytes; /* Bytes to write to page */ size_t copied; /* Bytes copied from user */ void *fsdata; offset = (pos & (PAGE_CACHE_SIZE - 1)); index = pos >> PAGE_CACHE_SHIFT; bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_count(i)); again: /* * Bring in the user page that we will copy from _first_. * Otherwise there's a nasty deadlock on copying from the * same page as we're writing to, without it being marked * up-to-date. * * Not only is this an optimisation, but it is also required * to check that the address is actually valid, when atomic * usercopies are used, below. */ if (unlikely(iov_iter_fault_in_readable(i, bytes))) { status = -EFAULT; break; } status = a_ops->write_begin(file, mapping, pos, bytes, flags, &page, &fsdata); if (unlikely(status)) break; pagefault_disable(); copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes); pagefault_enable(); flush_dcache_page(page); status = a_ops->write_end(file, mapping, pos, bytes, copied, page, fsdata); if (unlikely(status < 0)) break; copied = status; cond_resched(); if (unlikely(copied == 0)) { /* * If we were unable to copy any data at all, we must * fall back to a single segment length write. * * If we didn't fallback here, we could livelock * because not all segments in the iov can be copied at * once without a pagefault. */ bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_single_seg_count(i)); goto again; } iov_iter_advance(i, copied); pos += copied; written += copied; balance_dirty_pages_ratelimited(mapping); } while (iov_iter_count(i)); return written ? written : status; } Commit Message: fix writev regression: pan hanging unkillable and un-straceable Frederik Himpe reported an unkillable and un-straceable pan process. Zero length iovecs can go into an infinite loop in writev, because the iovec iterator does not always advance over them. The sequence required to trigger this is not trivial. I think it requires that a zero-length iovec be followed by a non-zero-length iovec which causes a pagefault in the atomic usercopy. This causes the writev code to drop back into single-segment copy mode, which then tries to copy the 0 bytes of the zero-length iovec; a zero length copy looks like a failure though, so it loops. Put a test into iov_iter_advance to catch zero-length iovecs. We could just put the test in the fallback path, but I feel it is more robust to skip over zero-length iovecs throughout the code (iovec iterator may be used in filesystems too, so it should be robust). Signed-off-by: Nick Piggin <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20
static ssize_t generic_perform_write(struct file *file, struct iov_iter *i, loff_t pos) { struct address_space *mapping = file->f_mapping; const struct address_space_operations *a_ops = mapping->a_ops; long status = 0; ssize_t written = 0; unsigned int flags = 0; /* * Copies from kernel address space cannot fail (NFSD is a big user). */ if (segment_eq(get_fs(), KERNEL_DS)) flags |= AOP_FLAG_UNINTERRUPTIBLE; do { struct page *page; pgoff_t index; /* Pagecache index for current page */ unsigned long offset; /* Offset into pagecache page */ unsigned long bytes; /* Bytes to write to page */ size_t copied; /* Bytes copied from user */ void *fsdata; offset = (pos & (PAGE_CACHE_SIZE - 1)); index = pos >> PAGE_CACHE_SHIFT; bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_count(i)); again: /* * Bring in the user page that we will copy from _first_. * Otherwise there's a nasty deadlock on copying from the * same page as we're writing to, without it being marked * up-to-date. * * Not only is this an optimisation, but it is also required * to check that the address is actually valid, when atomic * usercopies are used, below. */ if (unlikely(iov_iter_fault_in_readable(i, bytes))) { status = -EFAULT; break; } status = a_ops->write_begin(file, mapping, pos, bytes, flags, &page, &fsdata); if (unlikely(status)) break; pagefault_disable(); copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes); pagefault_enable(); flush_dcache_page(page); status = a_ops->write_end(file, mapping, pos, bytes, copied, page, fsdata); if (unlikely(status < 0)) break; copied = status; cond_resched(); iov_iter_advance(i, copied); if (unlikely(copied == 0)) { /* * If we were unable to copy any data at all, we must * fall back to a single segment length write. * * If we didn't fallback here, we could livelock * because not all segments in the iov can be copied at * once without a pagefault. */ bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_single_seg_count(i)); goto again; } pos += copied; written += copied; balance_dirty_pages_ratelimited(mapping); } while (iov_iter_count(i)); return written ? written : status; }
167,618
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 cloop_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVCloopState *s = bs->opaque; uint32_t offsets_size, max_compressed_block_size = 1, i; int ret; bs->read_only = 1; /* read header */ ret = bdrv_pread(bs->file, 128, &s->block_size, 4); if (ret < 0) { return ret; } s->block_size = be32_to_cpu(s->block_size); if (s->block_size % 512) { error_setg(errp, "block_size %u must be a multiple of 512", s->block_size); return -EINVAL; } if (s->block_size == 0) { error_setg(errp, "block_size cannot be zero"); return -EINVAL; } /* cloop's create_compressed_fs.c warns about block sizes beyond 256 KB but * we can accept more. Prevent ridiculous values like 4 GB - 1 since we * need a buffer this big. */ if (s->block_size > MAX_BLOCK_SIZE) { error_setg(errp, "block_size %u must be %u MB or less", s->block_size, MAX_BLOCK_SIZE / (1024 * 1024)); return -EINVAL; } ret = bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4); if (ret < 0) { return ret; } s->n_blocks = be32_to_cpu(s->n_blocks); /* read offsets */ offsets_size = s->n_blocks * sizeof(uint64_t); s->offsets = g_malloc(offsets_size); if (i > 0) { uint32_t size = s->offsets[i] - s->offsets[i - 1]; if (size > max_compressed_block_size) { max_compressed_block_size = size; } } } Commit Message: CWE ID: CWE-190
static int cloop_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVCloopState *s = bs->opaque; uint32_t offsets_size, max_compressed_block_size = 1, i; int ret; bs->read_only = 1; /* read header */ ret = bdrv_pread(bs->file, 128, &s->block_size, 4); if (ret < 0) { return ret; } s->block_size = be32_to_cpu(s->block_size); if (s->block_size % 512) { error_setg(errp, "block_size %u must be a multiple of 512", s->block_size); return -EINVAL; } if (s->block_size == 0) { error_setg(errp, "block_size cannot be zero"); return -EINVAL; } /* cloop's create_compressed_fs.c warns about block sizes beyond 256 KB but * we can accept more. Prevent ridiculous values like 4 GB - 1 since we * need a buffer this big. */ if (s->block_size > MAX_BLOCK_SIZE) { error_setg(errp, "block_size %u must be %u MB or less", s->block_size, MAX_BLOCK_SIZE / (1024 * 1024)); return -EINVAL; } ret = bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4); if (ret < 0) { return ret; } s->n_blocks = be32_to_cpu(s->n_blocks); /* read offsets */ if (s->n_blocks > UINT32_MAX / sizeof(uint64_t)) { /* Prevent integer overflow */ error_setg(errp, "n_blocks %u must be %zu or less", s->n_blocks, UINT32_MAX / sizeof(uint64_t)); return -EINVAL; } offsets_size = s->n_blocks * sizeof(uint64_t); s->offsets = g_malloc(offsets_size); if (i > 0) { uint32_t size = s->offsets[i] - s->offsets[i - 1]; if (size > max_compressed_block_size) { max_compressed_block_size = size; } } }
165,403
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: ecryptfs_decode_from_filename(unsigned char *dst, size_t *dst_size, const unsigned char *src, size_t src_size) { u8 current_bit_offset = 0; size_t src_byte_offset = 0; size_t dst_byte_offset = 0; if (dst == NULL) { (*dst_size) = ecryptfs_max_decoded_size(src_size); goto out; } while (src_byte_offset < src_size) { unsigned char src_byte = filename_rev_map[(int)src[src_byte_offset]]; switch (current_bit_offset) { case 0: dst[dst_byte_offset] = (src_byte << 2); current_bit_offset = 6; break; case 6: dst[dst_byte_offset++] |= (src_byte >> 4); dst[dst_byte_offset] = ((src_byte & 0xF) << 4); current_bit_offset = 4; break; case 4: dst[dst_byte_offset++] |= (src_byte >> 2); dst[dst_byte_offset] = (src_byte << 6); current_bit_offset = 2; break; case 2: dst[dst_byte_offset++] |= (src_byte); dst[dst_byte_offset] = 0; current_bit_offset = 0; break; } src_byte_offset++; } (*dst_size) = dst_byte_offset; out: return; } Commit Message: eCryptfs: Remove buggy and unnecessary write in file name decode routine Dmitry Chernenkov used KASAN to discover that eCryptfs writes past the end of the allocated buffer during encrypted filename decoding. This fix corrects the issue by getting rid of the unnecessary 0 write when the current bit offset is 2. Signed-off-by: Michael Halcrow <[email protected]> Reported-by: Dmitry Chernenkov <[email protected]> Suggested-by: Kees Cook <[email protected]> Cc: [email protected] # v2.6.29+: 51ca58d eCryptfs: Filename Encryption: Encoding and encryption functions Signed-off-by: Tyler Hicks <[email protected]> CWE ID: CWE-189
ecryptfs_decode_from_filename(unsigned char *dst, size_t *dst_size, const unsigned char *src, size_t src_size) { u8 current_bit_offset = 0; size_t src_byte_offset = 0; size_t dst_byte_offset = 0; if (dst == NULL) { (*dst_size) = ecryptfs_max_decoded_size(src_size); goto out; } while (src_byte_offset < src_size) { unsigned char src_byte = filename_rev_map[(int)src[src_byte_offset]]; switch (current_bit_offset) { case 0: dst[dst_byte_offset] = (src_byte << 2); current_bit_offset = 6; break; case 6: dst[dst_byte_offset++] |= (src_byte >> 4); dst[dst_byte_offset] = ((src_byte & 0xF) << 4); current_bit_offset = 4; break; case 4: dst[dst_byte_offset++] |= (src_byte >> 2); dst[dst_byte_offset] = (src_byte << 6); current_bit_offset = 2; break; case 2: dst[dst_byte_offset++] |= (src_byte); current_bit_offset = 0; break; } src_byte_offset++; } (*dst_size) = dst_byte_offset; out: return; }
166,766
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: SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); }
167,027
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 int LocaleLowercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); } Commit Message: ... CWE ID: CWE-125
MagickExport int LocaleLowercase(const int c) { if (c < 0) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); }
169,711
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 mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, NULL ) ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted CWE ID: CWE-200
int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, NULL, NULL, NULL ) ); } int mbedtls_ecdsa_sign_det_ext( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); ECDSA_VALIDATE_RET( f_rng_blind != NULL ); return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, f_rng_blind, p_rng_blind, NULL ) ); }
169,508
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: dtls1_process_record(SSL *s) { int i,al; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* For DTLS we simply ignore bad packets. */ rr->length = 0; s->packet_length = 0; goto err; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) enc_err = -1; } if (enc_err < 0) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /*- * So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */ return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); } Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a malloc failure, whilst the latter will fail if attempting to add a duplicate record to the queue. This should never happen because duplicate records should be detected and dropped before any attempt to add them to the queue. Unfortunately records that arrive that are for the next epoch are not being recorded correctly, and therefore replays are not being detected. Additionally, these "should not happen" failures that can occur in dtls1_buffer_record are not being treated as fatal and therefore an attacker could exploit this by sending repeated replay records for the next epoch, eventually causing a DoS through memory exhaustion. Thanks to Chris Mueller for reporting this issue and providing initial analysis and a patch. Further analysis and the final patch was performed by Matt Caswell from the OpenSSL development team. CVE-2015-0206 Reviewed-by: Dr Stephen Henson <[email protected]> CWE ID: CWE-119
dtls1_process_record(SSL *s) { int i,al; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* For DTLS we simply ignore bad packets. */ rr->length = 0; s->packet_length = 0; goto err; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) enc_err = -1; } if (enc_err < 0) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /*- * So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); }
166,748
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 StopInputMethodDaemon() { if (!initialized_successfully_) return; should_launch_ime_ = false; if (ibus_daemon_process_handle_ != base::kNullProcessHandle) { const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_); if (!chromeos::StopInputMethodProcess(input_method_status_connection_)) { LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to " << "PID " << pid; base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */); } VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated"; ibus_daemon_process_handle_ = base::kNullProcessHandle; } } 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 StopInputMethodDaemon() { if (!initialized_successfully_) return; should_launch_ime_ = false; if (ibus_daemon_process_handle_ != base::kNullProcessHandle) { const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_); if (!ibus_controller_->StopInputMethodProcess()) { LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to " << "PID " << pid; base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */); } VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated"; ibus_daemon_process_handle_ = base::kNullProcessHandle; } }
170,508
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 mk_request_free(struct session_request *sr) { if (sr->fd_file > 0) { mk_vhost_close(sr); } if (sr->headers.location) { mk_mem_free(sr->headers.location); } if (sr->uri_processed.data != sr->uri.data) { mk_ptr_free(&sr->uri_processed); } if (sr->real_path.data != sr->real_path_static) { mk_ptr_free(&sr->real_path); } } Commit Message: Request: new request session flag to mark those files opened by FDT This patch aims to fix a potential DDoS problem that can be caused in the server quering repetitive non-existent resources. When serving a static file, the core use Vhost FDT mechanism, but if it sends a static error page it does a direct open(2). When closing the resources for the same request it was just calling mk_vhost_close() which did not clear properly the file descriptor. This patch adds a new field on the struct session_request called 'fd_is_fdt', which contains MK_TRUE or MK_FALSE depending of how fd_file was opened. Thanks to Matthew Daley <[email protected]> for report and troubleshoot this problem. Signed-off-by: Eduardo Silva <[email protected]> CWE ID: CWE-20
void mk_request_free(struct session_request *sr) { if (sr->fd_file > 0) { if (sr->fd_is_fdt == MK_TRUE) { mk_vhost_close(sr); } else { close(sr->fd_file); } } if (sr->headers.location) { mk_mem_free(sr->headers.location); } if (sr->uri_processed.data != sr->uri.data) { mk_ptr_free(&sr->uri_processed); } if (sr->real_path.data != sr->real_path_static) { mk_ptr_free(&sr->real_path); } }
166,277