instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { xmlElementContentPtr ret = NULL, cur = NULL, n; const xmlChar *elem = NULL; GROW; if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { SKIP(7); SKIP_BLANKS; SHRINK; if (RAW == ')') { if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } NEXT; ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); if (RAW == '*') { ret->ocur = XML_ELEMENT_CONTENT_MULT; NEXT; } return(ret); } if ((RAW == '(') || (RAW == '|')) { ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); } while (RAW == '|') { NEXT; if (elem == NULL) { ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (ret == NULL) return(NULL); ret->c1 = cur; if (cur != NULL) cur->parent = ret; cur = ret; } else { n = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (n == NULL) return(NULL); n->c1 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (n->c1 != NULL) n->c1->parent = n; cur->c2 = n; if (n != NULL) n->parent = cur; cur = n; } SKIP_BLANKS; elem = xmlParseName(ctxt); if (elem == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseElementMixedContentDecl : Name expected\n"); xmlFreeDocElementContent(ctxt->myDoc, cur); return(NULL); } SKIP_BLANKS; GROW; } if ((RAW == ')') && (NXT(1) == '*')) { if (elem != NULL) { cur->c2 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (cur->c2 != NULL) cur->c2->parent = cur; } if (ret != NULL) ret->ocur = XML_ELEMENT_CONTENT_MULT; if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } SKIP(2); } else { xmlFreeDocElementContent(ctxt->myDoc, ret); xmlFatalErr(ctxt, XML_ERR_MIXED_NOT_STARTED, NULL); return(NULL); } } else { xmlFatalErr(ctxt, XML_ERR_PCDATA_REQUIRED, NULL); } return(ret); } 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
xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { xmlElementContentPtr ret = NULL, cur = NULL, n; const xmlChar *elem = NULL; GROW; if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { SKIP(7); SKIP_BLANKS; SHRINK; if (RAW == ')') { if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } NEXT; ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); if (RAW == '*') { ret->ocur = XML_ELEMENT_CONTENT_MULT; NEXT; } return(ret); } if ((RAW == '(') || (RAW == '|')) { ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); if (ret == NULL) return(NULL); } while ((RAW == '|') && (ctxt->instate != XML_PARSER_EOF)) { NEXT; if (elem == NULL) { ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (ret == NULL) return(NULL); ret->c1 = cur; if (cur != NULL) cur->parent = ret; cur = ret; } else { n = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); if (n == NULL) return(NULL); n->c1 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (n->c1 != NULL) n->c1->parent = n; cur->c2 = n; if (n != NULL) n->parent = cur; cur = n; } SKIP_BLANKS; elem = xmlParseName(ctxt); if (elem == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseElementMixedContentDecl : Name expected\n"); xmlFreeDocElementContent(ctxt->myDoc, cur); return(NULL); } SKIP_BLANKS; GROW; } if ((RAW == ')') && (NXT(1) == '*')) { if (elem != NULL) { cur->c2 = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT); if (cur->c2 != NULL) cur->c2->parent = cur; } if (ret != NULL) ret->ocur = XML_ELEMENT_CONTENT_MULT; if ((ctxt->validate) && (ctxt->input->id != inputchk)) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "Element content declaration doesn't start and stop in the same entity\n", NULL, NULL); } SKIP(2); } else { xmlFreeDocElementContent(ctxt->myDoc, ret); xmlFatalErr(ctxt, XML_ERR_MIXED_NOT_STARTED, NULL); return(NULL); } } else { xmlFatalErr(ctxt, XML_ERR_PCDATA_REQUIRED, NULL); } return(ret); }
171,286
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void TearDown() { vp9_worker_end(&worker_); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void TearDown() { vpx_get_worker_interface()->end(&worker_); }
174,600
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(linkinfo) { char *link; size_t link_len; zend_stat_t sb; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) { return; } ret = VCWD_STAT(link, &sb); if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); RETURN_LONG(Z_L(-1)); } RETURN_LONG((zend_long) sb.st_dev); } Commit Message: Fixed bug #76459 windows linkinfo lacks openbasedir check CWE ID: CWE-200
PHP_FUNCTION(linkinfo) { char *link; char *dirname; size_t link_len; zend_stat_t sb; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) { return; } dirname = estrndup(link, link_len); php_dirname(dirname, link_len); if (php_check_open_basedir(dirname)) { efree(dirname); RETURN_FALSE; } ret = VCWD_STAT(link, &sb); if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); efree(dirname); RETURN_LONG(Z_L(-1)); } efree(dirname); RETURN_LONG((zend_long) sb.st_dev); }
169,107
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 Cluster::GetFirst(const BlockEntry*& pFirst) const { if (m_entries_count <= 0) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) //error { pFirst = NULL; return status; } if (m_entries_count <= 0) //empty cluster { pFirst = NULL; return 0; } } assert(m_entries); pFirst = m_entries[0]; assert(pFirst); return 0; //success } 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 Cluster::GetFirst(const BlockEntry*& pFirst) const
174,320
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: JsVar *jswrap_graphics_createArrayBuffer(int width, int height, int bpp, JsVar *options) { if (width<=0 || height<=0 || width>32767 || height>32767) { jsExceptionHere(JSET_ERROR, "Invalid Size"); return 0; } if (!isValidBPP(bpp)) { jsExceptionHere(JSET_ERROR, "Invalid BPP"); return 0; } JsVar *parent = jspNewObject(0, "Graphics"); if (!parent) return 0; // low memory JsGraphics gfx; graphicsStructInit(&gfx); gfx.data.type = JSGRAPHICSTYPE_ARRAYBUFFER; gfx.data.flags = JSGRAPHICSFLAGS_NONE; gfx.graphicsVar = parent; gfx.data.width = (unsigned short)width; gfx.data.height = (unsigned short)height; gfx.data.bpp = (unsigned char)bpp; if (jsvIsObject(options)) { if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "zigzag", 0))) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_ZIGZAG); if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "msb", 0))) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_MSB); if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "vertical_byte", 0))) { if (gfx.data.bpp==1) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE); else jsWarn("vertical_byte only works for 1bpp ArrayBuffers\n"); } JsVar *colorv = jsvObjectGetChild(options, "color_order", 0); if (colorv) { if (jsvIsStringEqual(colorv, "rgb")) ; // The default else if (!jsvIsStringEqual(colorv, "brg")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_BRG); else if (!jsvIsStringEqual(colorv, "bgr")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_BGR); else if (!jsvIsStringEqual(colorv, "gbr")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_GBR); else if (!jsvIsStringEqual(colorv, "grb")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_GRB); else if (!jsvIsStringEqual(colorv, "rbg")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_RBG); else jsWarn("color_order must be 3 characters"); jsvUnLock(colorv); } } lcdInit_ArrayBuffer(&gfx); graphicsSetVar(&gfx); return parent; } Commit Message: Add height check for Graphics.createArrayBuffer(...vertical_byte:true) (fix #1421) CWE ID: CWE-125
JsVar *jswrap_graphics_createArrayBuffer(int width, int height, int bpp, JsVar *options) { if (width<=0 || height<=0 || width>32767 || height>32767) { jsExceptionHere(JSET_ERROR, "Invalid Size"); return 0; } if (!isValidBPP(bpp)) { jsExceptionHere(JSET_ERROR, "Invalid BPP"); return 0; } JsVar *parent = jspNewObject(0, "Graphics"); if (!parent) return 0; // low memory JsGraphics gfx; graphicsStructInit(&gfx); gfx.data.type = JSGRAPHICSTYPE_ARRAYBUFFER; gfx.data.flags = JSGRAPHICSFLAGS_NONE; gfx.graphicsVar = parent; gfx.data.width = (unsigned short)width; gfx.data.height = (unsigned short)height; gfx.data.bpp = (unsigned char)bpp; if (jsvIsObject(options)) { if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "zigzag", 0))) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_ZIGZAG); if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "msb", 0))) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_MSB); if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "vertical_byte", 0))) { if (gfx.data.bpp==1) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE); else { jsExceptionHere(JSET_ERROR, "vertical_byte only works for 1bpp ArrayBuffers\n"); return 0; } if (gfx.data.height&7) { jsExceptionHere(JSET_ERROR, "height must be a multiple of 8 when using vertical_byte\n"); return 0; } } JsVar *colorv = jsvObjectGetChild(options, "color_order", 0); if (colorv) { if (jsvIsStringEqual(colorv, "rgb")) ; // The default else if (!jsvIsStringEqual(colorv, "brg")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_BRG); else if (!jsvIsStringEqual(colorv, "bgr")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_BGR); else if (!jsvIsStringEqual(colorv, "gbr")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_GBR); else if (!jsvIsStringEqual(colorv, "grb")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_GRB); else if (!jsvIsStringEqual(colorv, "rbg")) gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_RBG); else jsWarn("color_order must be 3 characters"); jsvUnLock(colorv); } } lcdInit_ArrayBuffer(&gfx); graphicsSetVar(&gfx); return parent; }
169,216
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: GF_Err tenc_dump(GF_Box *a, FILE * trace) { GF_TrackEncryptionBox *ptr = (GF_TrackEncryptionBox*) a; if (!a) return GF_BAD_PARAM; gf_isom_box_dump_start(a, "TrackEncryptionBox", trace); fprintf(trace, "isEncrypted=\"%d\"", ptr->isProtected); if (ptr->Per_Sample_IV_Size) fprintf(trace, " IV_size=\"%d\" KID=\"", ptr->Per_Sample_IV_Size); else { fprintf(trace, " constant_IV_size=\"%d\" constant_IV=\"", ptr->constant_IV_size); dump_data_hex(trace, (char *) ptr->constant_IV, ptr->constant_IV_size); fprintf(trace, "\" KID=\""); } dump_data_hex(trace, (char *) ptr->KID, 16); if (ptr->version) fprintf(trace, "\" crypt_byte_block=\"%d\" skip_byte_block=\"%d", ptr->crypt_byte_block, ptr->skip_byte_block); fprintf(trace, "\">\n"); gf_isom_box_dump_done("TrackEncryptionBox", a, trace); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125
GF_Err tenc_dump(GF_Box *a, FILE * trace) { GF_TrackEncryptionBox *ptr = (GF_TrackEncryptionBox*) a; if (!a) return GF_BAD_PARAM; gf_isom_box_dump_start(a, "TrackEncryptionBox", trace); fprintf(trace, "isEncrypted=\"%d\"", ptr->isProtected); if (ptr->Per_Sample_IV_Size) fprintf(trace, " IV_size=\"%d\" KID=\"", ptr->Per_Sample_IV_Size); else { fprintf(trace, " constant_IV_size=\"%d\" constant_IV=\"", ptr->constant_IV_size); dump_data_hex(trace, (char *) ptr->constant_IV, ptr->constant_IV_size); fprintf(trace, "\" KID=\""); } dump_data_hex(trace, (char *) ptr->KID, 16); if (ptr->version) fprintf(trace, "\" crypt_byte_block=\"%d\" skip_byte_block=\"%d", ptr->crypt_byte_block, ptr->skip_byte_block); fprintf(trace, "\">\n"); gf_isom_box_dump_done("TrackEncryptionBox", a, trace); return GF_OK; }
169,172
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 vorbis_book_decodev_add(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); int i,j; if (!v) return -1; for(i=0;i<n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim;j++) a[i++]+=v[j]; } } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
long vorbis_book_decodev_add(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); int i,j; if (!v) return -1; for(i=0;i<n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim && i < n;j++) a[i++]+=v[j]; } } return 0; }
173,986
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: PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */ { const char *p; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); for (p = val; p < endptr; ) { zval **tmp; namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF); if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } has_value = *p & PS_BIN_UNDEF ? 0 : 1; name = estrndup(p + 1, namelen); p += namelen + 1; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { efree(name); continue; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } else { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } PS_ADD_VARL(name, namelen); efree(name); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */ Commit Message: Fix bug #72681 - consume data even if we're not storing them CWE ID: CWE-74
PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */ { const char *p; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; int skip = 0; PHP_VAR_UNSERIALIZE_INIT(var_hash); for (p = val; p < endptr; ) { zval **tmp; skip = 0; namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF); if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } has_value = *p & PS_BIN_UNDEF ? 0 : 1; name = estrndup(p + 1, namelen); p += namelen + 1; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { skip = 1; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { if (!skip) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } } else { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } if (!skip) { PS_ADD_VARL(name, namelen); } efree(name); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */
166,958
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 isNodeAriaVisible(Node* node) { if (!node) return false; if (!node->isElementNode()) return false; return equalIgnoringCase(toElement(node)->getAttribute(aria_hiddenAttr), "false"); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool isNodeAriaVisible(Node* node) { if (!node) return false; if (!node->isElementNode()) return false; return equalIgnoringASCIICase(toElement(node)->getAttribute(aria_hiddenAttr), "false"); }
171,929
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 Document::InitSecurityContext(const DocumentInit& initializer) { DCHECK(!GetSecurityOrigin()); if (!initializer.HasSecurityContext()) { cookie_url_ = KURL(g_empty_string); SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()); InitContentSecurityPolicy(); ApplyFeaturePolicy({}); return; } SandboxFlags sandbox_flags = initializer.GetSandboxFlags(); if (fetcher_->Archive()) { sandbox_flags |= kSandboxAll & ~(kSandboxPopups | kSandboxPropagatesToAuxiliaryBrowsingContexts); } EnforceSandboxFlags(sandbox_flags); SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy()); if (initializer.InsecureNavigationsToUpgrade()) { for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade()) AddInsecureNavigationUpgrade(to_upgrade); } const ContentSecurityPolicy* policy_to_inherit = nullptr; if (IsSandboxed(kSandboxOrigin)) { cookie_url_ = url_; scoped_refptr<SecurityOrigin> security_origin = SecurityOrigin::CreateUniqueOpaque(); Document* owner = initializer.OwnerDocument(); if (owner) { if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy()) security_origin->SetOpaqueOriginIsPotentiallyTrustworthy(true); if (owner->GetSecurityOrigin()->CanLoadLocalResources()) security_origin->GrantLoadLocalResources(); policy_to_inherit = owner->GetContentSecurityPolicy(); } SetSecurityOrigin(std::move(security_origin)); } else if (Document* owner = initializer.OwnerDocument()) { cookie_url_ = owner->CookieURL(); SetSecurityOrigin(owner->GetMutableSecurityOrigin()); policy_to_inherit = owner->GetContentSecurityPolicy(); } else { cookie_url_ = url_; SetSecurityOrigin(SecurityOrigin::Create(url_)); } if (initializer.IsHostedInReservedIPRange()) { SetAddressSpace(GetSecurityOrigin()->IsLocalhost() ? mojom::IPAddressSpace::kLocal : mojom::IPAddressSpace::kPrivate); } else if (GetSecurityOrigin()->IsLocal()) { SetAddressSpace(mojom::IPAddressSpace::kLocal); } else { SetAddressSpace(mojom::IPAddressSpace::kPublic); } if (ImportsController()) { SetContentSecurityPolicy( ImportsController()->Master()->GetContentSecurityPolicy()); } else { InitContentSecurityPolicy(nullptr, policy_to_inherit, initializer.PreviousDocumentCSP()); } if (Settings* settings = initializer.GetSettings()) { if (!settings->GetWebSecurityEnabled()) { GetMutableSecurityOrigin()->GrantUniversalAccess(); } else if (GetSecurityOrigin()->IsLocal()) { if (settings->GetAllowUniversalAccessFromFileURLs()) { GetMutableSecurityOrigin()->GrantUniversalAccess(); } else if (!settings->GetAllowFileAccessFromFileURLs()) { GetMutableSecurityOrigin()->BlockLocalAccessFromLocalOrigin(); } } } if (GetSecurityOrigin()->IsOpaque() && SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy()) GetMutableSecurityOrigin()->SetOpaqueOriginIsPotentiallyTrustworthy(true); ApplyFeaturePolicy({}); InitSecureContextState(); } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <andypaicu@chromium.org> Reviewed-by: Mike West <mkwst@chromium.org> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
void Document::InitSecurityContext(const DocumentInit& initializer) { DCHECK(!GetSecurityOrigin()); if (!initializer.HasSecurityContext()) { cookie_url_ = KURL(g_empty_string); SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque()); InitContentSecurityPolicy(); ApplyFeaturePolicy({}); return; } SandboxFlags sandbox_flags = initializer.GetSandboxFlags(); if (fetcher_->Archive()) { sandbox_flags |= kSandboxAll & ~(kSandboxPopups | kSandboxPropagatesToAuxiliaryBrowsingContexts); } EnforceSandboxFlags(sandbox_flags); SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy()); if (initializer.InsecureNavigationsToUpgrade()) { for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade()) AddInsecureNavigationUpgrade(to_upgrade); } Document* origin_document = frame_ ? frame_->Loader().GetLastOriginDocument() : nullptr; if (IsSandboxed(kSandboxOrigin)) { cookie_url_ = url_; scoped_refptr<SecurityOrigin> security_origin = SecurityOrigin::CreateUniqueOpaque(); Document* owner = initializer.OwnerDocument(); if (owner) { if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy()) security_origin->SetOpaqueOriginIsPotentiallyTrustworthy(true); if (owner->GetSecurityOrigin()->CanLoadLocalResources()) security_origin->GrantLoadLocalResources(); if (url_.IsEmpty()) origin_document = owner; } SetSecurityOrigin(std::move(security_origin)); } else if (Document* owner = initializer.OwnerDocument()) { cookie_url_ = owner->CookieURL(); SetSecurityOrigin(owner->GetMutableSecurityOrigin()); if (url_.IsEmpty()) origin_document = owner; } else { cookie_url_ = url_; SetSecurityOrigin(SecurityOrigin::Create(url_)); } if (initializer.IsHostedInReservedIPRange()) { SetAddressSpace(GetSecurityOrigin()->IsLocalhost() ? mojom::IPAddressSpace::kLocal : mojom::IPAddressSpace::kPrivate); } else if (GetSecurityOrigin()->IsLocal()) { SetAddressSpace(mojom::IPAddressSpace::kLocal); } else { SetAddressSpace(mojom::IPAddressSpace::kPublic); } if (ImportsController()) { SetContentSecurityPolicy( ImportsController()->Master()->GetContentSecurityPolicy()); } else { InitContentSecurityPolicy(nullptr, origin_document); } if (Settings* settings = initializer.GetSettings()) { if (!settings->GetWebSecurityEnabled()) { GetMutableSecurityOrigin()->GrantUniversalAccess(); } else if (GetSecurityOrigin()->IsLocal()) { if (settings->GetAllowUniversalAccessFromFileURLs()) { GetMutableSecurityOrigin()->GrantUniversalAccess(); } else if (!settings->GetAllowFileAccessFromFileURLs()) { GetMutableSecurityOrigin()->BlockLocalAccessFromLocalOrigin(); } } } if (GetSecurityOrigin()->IsOpaque() && SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy()) GetMutableSecurityOrigin()->SetOpaqueOriginIsPotentiallyTrustworthy(true); ApplyFeaturePolicy({}); InitSecureContextState(); }
173,053
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 mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt) { struct serial_icounter_struct icount; struct sb_uart_icount cnow; struct sb_uart_port *port = state->port; spin_lock_irq(&port->lock); memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount)); spin_unlock_irq(&port->lock); icount.cts = cnow.cts; icount.dsr = cnow.dsr; icount.rng = cnow.rng; icount.dcd = cnow.dcd; icount.rx = cnow.rx; icount.tx = cnow.tx; icount.frame = cnow.frame; icount.overrun = cnow.overrun; icount.parity = cnow.parity; icount.brk = cnow.brk; icount.buf_overrun = cnow.buf_overrun; return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0; } Commit Message: Staging: sb105x: info leak in mp_get_count() The icount.reserved[] array isn't initialized so it leaks stack information to userspace. Reported-by: Nico Golde <nico@ngolde.de> Reported-by: Fabian Yamaguchi <fabs@goesec.de> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-200
static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt) { struct serial_icounter_struct icount = {}; struct sb_uart_icount cnow; struct sb_uart_port *port = state->port; spin_lock_irq(&port->lock); memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount)); spin_unlock_irq(&port->lock); icount.cts = cnow.cts; icount.dsr = cnow.dsr; icount.rng = cnow.rng; icount.dcd = cnow.dcd; icount.rx = cnow.rx; icount.tx = cnow.tx; icount.frame = cnow.frame; icount.overrun = cnow.overrun; icount.parity = cnow.parity; icount.brk = cnow.brk; icount.buf_overrun = cnow.buf_overrun; return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0; }
165,961
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 DoResolveRelativeHost(const char* base_url, const url_parse::Parsed& base_parsed, const CHAR* relative_url, const url_parse::Component& relative_component, CharsetConverter* query_converter, CanonOutput* output, url_parse::Parsed* out_parsed) { url_parse::Parsed relative_parsed; // Everything but the scheme is valid. url_parse::ParseAfterScheme(&relative_url[relative_component.begin], relative_component.len, relative_component.begin, &relative_parsed); Replacements<CHAR> replacements; replacements.SetUsername(relative_url, relative_parsed.username); replacements.SetPassword(relative_url, relative_parsed.password); replacements.SetHost(relative_url, relative_parsed.host); replacements.SetPort(relative_url, relative_parsed.port); replacements.SetPath(relative_url, relative_parsed.path); replacements.SetQuery(relative_url, relative_parsed.query); replacements.SetRef(relative_url, relative_parsed.ref); return ReplaceStandardURL(base_url, base_parsed, replacements, query_converter, output, out_parsed); } Commit Message: Fix OOB read when parsing protocol-relative URLs BUG=285742 Review URL: https://chromiumcodereview.appspot.com/23902014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@223735 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool DoResolveRelativeHost(const char* base_url, const url_parse::Parsed& base_parsed, const CHAR* relative_url, const url_parse::Component& relative_component, CharsetConverter* query_converter, CanonOutput* output, url_parse::Parsed* out_parsed) { url_parse::Parsed relative_parsed; // Everything but the scheme is valid. url_parse::ParseAfterScheme(relative_url, relative_component.end(), relative_component.begin, &relative_parsed); Replacements<CHAR> replacements; replacements.SetUsername(relative_url, relative_parsed.username); replacements.SetPassword(relative_url, relative_parsed.password); replacements.SetHost(relative_url, relative_parsed.host); replacements.SetPort(relative_url, relative_parsed.port); replacements.SetPath(relative_url, relative_parsed.path); replacements.SetQuery(relative_url, relative_parsed.query); replacements.SetRef(relative_url, relative_parsed.ref); return ReplaceStandardURL(base_url, base_parsed, replacements, query_converter, output, out_parsed); }
171,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: int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index) { struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table; int i, err = 0; int free = -1; mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac); mutex_lock(&table->mutex); for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) { if (free < 0 && !table->refs[i]) { free = i; continue; } if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) { /* MAC already registered, increase refernce count */ *index = i; ++table->refs[i]; goto out; } } mlx4_dbg(dev, "Free MAC index is %d\n", free); if (table->total == table->max) { /* No free mac entries */ err = -ENOSPC; goto out; } /* Register new MAC */ table->refs[free] = 1; table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID); err = mlx4_set_port_mac_table(dev, port, table->entries); if (unlikely(err)) { mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac); table->refs[free] = 0; table->entries[free] = 0; goto out; } *index = free; ++table->total; out: mutex_unlock(&table->mutex); return err; } Commit Message: mlx4_en: Fix out of bounds array access When searching for a free entry in either mlx4_register_vlan() or mlx4_register_mac(), and there is no free entry, the loop terminates without updating the local variable free thus causing out of array bounds access. Fix this by adding a proper check outside the loop. Signed-off-by: Eli Cohen <eli@mellanox.co.il> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-119
int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index) { struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table; int i, err = 0; int free = -1; mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac); mutex_lock(&table->mutex); for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) { if (free < 0 && !table->refs[i]) { free = i; continue; } if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) { /* MAC already registered, increase refernce count */ *index = i; ++table->refs[i]; goto out; } } if (free < 0) { err = -ENOMEM; goto out; } mlx4_dbg(dev, "Free MAC index is %d\n", free); if (table->total == table->max) { /* No free mac entries */ err = -ENOSPC; goto out; } /* Register new MAC */ table->refs[free] = 1; table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID); err = mlx4_set_port_mac_table(dev, port, table->entries); if (unlikely(err)) { mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac); table->refs[free] = 0; table->entries[free] = 0; goto out; } *index = free; ++table->total; out: mutex_unlock(&table->mutex); return err; }
169,871
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: DailyDataSavingUpdate( const char* pref_original, const char* pref_received, PrefService* pref_service) : pref_original_(pref_original), pref_received_(pref_received), original_update_(pref_service, pref_original_), received_update_(pref_service, pref_received_) { } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
DailyDataSavingUpdate( const char* pref_original, const char* pref_received, PrefService* pref_service) : original_(pref_original, pref_service), received_(pref_received, pref_service) { }
171,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: DOMHandler::DOMHandler() : DevToolsDomainHandler(DOM::Metainfo::domainName), host_(nullptr) { } Commit Message: [DevTools] Guard DOM.setFileInputFiles under MayAffectLocalFiles Bug: 805557 Change-Id: Ib6f37ec6e1d091ee54621cc0c5c44f1a6beab10f Reviewed-on: https://chromium-review.googlesource.com/c/1334847 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Commit-Queue: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#607902} CWE ID: CWE-254
DOMHandler::DOMHandler() DOMHandler::DOMHandler(bool allow_file_access) : DevToolsDomainHandler(DOM::Metainfo::domainName),
173,112
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 ScreenLayoutObserver::GetDisplayMessageForNotification( const ScreenLayoutObserver::DisplayInfoMap& old_info, base::string16* out_message, base::string16* out_additional_message) { if (old_display_mode_ != current_display_mode_) { if (current_display_mode_ == DisplayMode::MIRRORING) { *out_message = GetEnterMirrorModeMessage(); return true; } if (old_display_mode_ == DisplayMode::MIRRORING && GetExitMirrorModeMessage(out_message, out_additional_message)) { return true; } if (current_display_mode_ == DisplayMode::UNIFIED) { *out_message = GetEnterUnifiedModeMessage(); return true; } if (old_display_mode_ == DisplayMode::UNIFIED) { *out_message = GetExitUnifiedModeMessage(); return true; } if (current_display_mode_ == DisplayMode::DOCKED || old_display_mode_ == DisplayMode::DOCKED) { return false; } } if (display_info_.size() < old_info.size()) { for (const auto& iter : old_info) { if (display_info_.count(iter.first)) continue; *out_message = GetDisplayRemovedMessage(iter.second, out_additional_message); return true; } } else if (display_info_.size() > old_info.size()) { for (const auto& iter : display_info_) { if (old_info.count(iter.first)) continue; *out_message = GetDisplayAddedMessage(iter.first, out_additional_message); return true; } } for (const auto& iter : display_info_) { DisplayInfoMap::const_iterator old_iter = old_info.find(iter.first); if (old_iter == old_info.end()) { NOTREACHED() << "A display mode transition that should have been handled" "earlier."; return false; } if (iter.second.configured_ui_scale() != old_iter->second.configured_ui_scale()) { *out_additional_message = l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_RESOLUTION_CHANGED, GetDisplayName(iter.first), GetDisplaySize(iter.first)); return true; } if (iter.second.GetActiveRotation() != old_iter->second.GetActiveRotation()) { int rotation_text_id = 0; switch (iter.second.GetActiveRotation()) { case display::Display::ROTATE_0: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_STANDARD_ORIENTATION; break; case display::Display::ROTATE_90: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_90; break; case display::Display::ROTATE_180: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_180; break; case display::Display::ROTATE_270: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_270; break; } *out_additional_message = l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_ROTATED, GetDisplayName(iter.first), l10n_util::GetStringUTF16(rotation_text_id)); return true; } } return false; } Commit Message: Avoid Showing rotation change notification when source is accelerometer BUG=717252 TEST=Manually rotate device with accelerometer and observe there's no notification Review-Url: https://codereview.chromium.org/2853113005 Cr-Commit-Position: refs/heads/master@{#469058} CWE ID: CWE-17
bool ScreenLayoutObserver::GetDisplayMessageForNotification( const ScreenLayoutObserver::DisplayInfoMap& old_info, base::string16* out_message, base::string16* out_additional_message) { if (old_display_mode_ != current_display_mode_) { if (current_display_mode_ == DisplayMode::MIRRORING) { *out_message = GetEnterMirrorModeMessage(); return true; } if (old_display_mode_ == DisplayMode::MIRRORING && GetExitMirrorModeMessage(out_message, out_additional_message)) { return true; } if (current_display_mode_ == DisplayMode::UNIFIED) { *out_message = GetEnterUnifiedModeMessage(); return true; } if (old_display_mode_ == DisplayMode::UNIFIED) { *out_message = GetExitUnifiedModeMessage(); return true; } if (current_display_mode_ == DisplayMode::DOCKED || old_display_mode_ == DisplayMode::DOCKED) { return false; } } if (display_info_.size() < old_info.size()) { for (const auto& iter : old_info) { if (display_info_.count(iter.first)) continue; *out_message = GetDisplayRemovedMessage(iter.second, out_additional_message); return true; } } else if (display_info_.size() > old_info.size()) { for (const auto& iter : display_info_) { if (old_info.count(iter.first)) continue; *out_message = GetDisplayAddedMessage(iter.first, out_additional_message); return true; } } for (const auto& iter : display_info_) { DisplayInfoMap::const_iterator old_iter = old_info.find(iter.first); if (old_iter == old_info.end()) { NOTREACHED() << "A display mode transition that should have been handled" "earlier."; return false; } if (iter.second.configured_ui_scale() != old_iter->second.configured_ui_scale()) { *out_additional_message = l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_RESOLUTION_CHANGED, GetDisplayName(iter.first), GetDisplaySize(iter.first)); return true; } // We don't show rotation change notification when the rotation source is // the accelerometer. if (iter.second.active_rotation_source() != display::Display::ROTATION_SOURCE_ACCELEROMETER && iter.second.GetActiveRotation() != old_iter->second.GetActiveRotation()) { int rotation_text_id = 0; switch (iter.second.GetActiveRotation()) { case display::Display::ROTATE_0: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_STANDARD_ORIENTATION; break; case display::Display::ROTATE_90: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_90; break; case display::Display::ROTATE_180: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_180; break; case display::Display::ROTATE_270: rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_270; break; } *out_additional_message = l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_ROTATED, GetDisplayName(iter.first), l10n_util::GetStringUTF16(rotation_text_id)); return true; } } return false; }
172,043
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: Blob::~Blob() { ThreadableBlobRegistry::unregisterBlobURL(m_internalURL); } 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:
Blob::~Blob() { BlobRegistry::unregisterBlobURL(m_internalURL); }
170,679
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 OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } Commit Message: Avoid division by zero in opj_pi_next_rpcl, opj_pi_next_pcrl and opj_pi_next_cprl (#938) Fixes issues with id:000026,sig:08,src:002419,op:int32,pos:60,val:+32 and id:000019,sig:08,src:001098,op:flip1,pos:49 CWE ID: CWE-369
static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ /* in below tests */ /* Fixes reading id:000026,sig:08,src:002419,op:int32,pos:60,val:+32 */ /* of https://github.com/uclouvain/openjpeg/issues/938 */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } /* See ISO-15441. B.12.1.3 Resolution level-position-component-layer progression */ if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; }
168,457
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 btsock_thread_remove_fd_and_close(int thread_handle, int fd) { if (thread_handle < 0 || thread_handle >= MAX_THREAD) { APPL_TRACE_ERROR("%s invalid thread handle: %d", __func__, thread_handle); return false; } if (fd == -1) { APPL_TRACE_ERROR("%s invalid file descriptor.", __func__); return false; } sock_cmd_t cmd = {CMD_REMOVE_FD, fd, 0, 0, 0}; return send(ts[thread_handle].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd); } 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
bool btsock_thread_remove_fd_and_close(int thread_handle, int fd) { if (thread_handle < 0 || thread_handle >= MAX_THREAD) { APPL_TRACE_ERROR("%s invalid thread handle: %d", __func__, thread_handle); return false; } if (fd == -1) { APPL_TRACE_ERROR("%s invalid file descriptor.", __func__); return false; } sock_cmd_t cmd = {CMD_REMOVE_FD, fd, 0, 0, 0}; return TEMP_FAILURE_RETRY(send(ts[thread_handle].cmd_fdw, &cmd, sizeof(cmd), 0)) == sizeof(cmd); }
173,463
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 locationReplaceableAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationReplaceable()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 R=jochen@chromium.org 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 locationReplaceableAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationReplaceable()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); }
171,686
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 SanitizeFrontendPath(const std::string& path) { for (size_t i = 0; i < path.length(); i++) { if (path[i] != '/' && path[i] != '-' && path[i] != '_' && path[i] != '.' && path[i] != '@' && !(path[i] >= '0' && path[i] <= '9') && !(path[i] >= 'a' && path[i] <= 'z') && !(path[i] >= 'A' && path[i] <= 'Z')) { return std::string(); } } return path; } 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
std::string SanitizeFrontendPath(const std::string& path) {
172,458
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 link_pipe(struct pipe_inode_info *ipipe, struct pipe_inode_info *opipe, size_t len, unsigned int flags) { struct pipe_buffer *ibuf, *obuf; int ret = 0, i = 0, nbuf; /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes * could deadlock (one doing tee from A -> B, the other from B -> A). */ pipe_double_lock(ipipe, opipe); do { if (!opipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } /* * If we have iterated all input buffers or ran out of * output room, break. */ if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) break; ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1)); nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); /* * Get a reference to this pipe buffer, * so we can copy the contents over. */ pipe_buf_get(ipipe, ibuf); obuf = opipe->bufs + nbuf; *obuf = *ibuf; /* * Don't inherit the gift flag, we need to * prevent multiple steals of this page. */ obuf->flags &= ~PIPE_BUF_FLAG_GIFT; pipe_buf_mark_unmergeable(obuf); if (obuf->len > len) obuf->len = len; opipe->nrbufs++; ret += obuf->len; len -= obuf->len; i++; } while (len); /* * return EAGAIN if we have the potential of some data in the * future, otherwise just return 0 */ if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK)) ret = -EAGAIN; pipe_unlock(ipipe); pipe_unlock(opipe); /* * If we put data in the output pipe, wakeup any potential readers. */ if (ret > 0) wakeup_pipe_readers(opipe); return ret; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static int link_pipe(struct pipe_inode_info *ipipe, struct pipe_inode_info *opipe, size_t len, unsigned int flags) { struct pipe_buffer *ibuf, *obuf; int ret = 0, i = 0, nbuf; /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes * could deadlock (one doing tee from A -> B, the other from B -> A). */ pipe_double_lock(ipipe, opipe); do { if (!opipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } /* * If we have iterated all input buffers or ran out of * output room, break. */ if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) break; ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1)); nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); /* * Get a reference to this pipe buffer, * so we can copy the contents over. */ if (!pipe_buf_get(ipipe, ibuf)) { if (ret == 0) ret = -EFAULT; break; } obuf = opipe->bufs + nbuf; *obuf = *ibuf; /* * Don't inherit the gift flag, we need to * prevent multiple steals of this page. */ obuf->flags &= ~PIPE_BUF_FLAG_GIFT; pipe_buf_mark_unmergeable(obuf); if (obuf->len > len) obuf->len = len; opipe->nrbufs++; ret += obuf->len; len -= obuf->len; i++; } while (len); /* * return EAGAIN if we have the potential of some data in the * future, otherwise just return 0 */ if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK)) ret = -EAGAIN; pipe_unlock(ipipe); pipe_unlock(opipe); /* * If we put data in the output pipe, wakeup any potential readers. */ if (ret > 0) wakeup_pipe_readers(opipe); return ret; }
170,219
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 SocketStream::HandleCertificateError(int result) { DCHECK(IsCertificateError(result)); SSLClientSocket* ssl_socket = static_cast<SSLClientSocket*>(socket_.get()); DCHECK(ssl_socket); if (!context_.get()) return result; if (SSLClientSocket::IgnoreCertError(result, LOAD_IGNORE_ALL_CERT_ERRORS)) { const HttpNetworkSession::Params* session_params = context_->GetNetworkSessionParams(); if (session_params && session_params->ignore_certificate_errors) return OK; } if (!delegate_) return result; SSLInfo ssl_info; ssl_socket->GetSSLInfo(&ssl_info); TransportSecurityState::DomainState domain_state; const bool fatal = context_->transport_security_state() && context_->transport_security_state()->GetDomainState(url_.host(), SSLConfigService::IsSNIAvailable(context_->ssl_config_service()), &domain_state) && domain_state.ShouldSSLErrorsBeFatal(); delegate_->OnSSLCertificateError(this, ssl_info, fatal); return 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
int SocketStream::HandleCertificateError(int result) { DCHECK(IsCertificateError(result)); SSLClientSocket* ssl_socket = static_cast<SSLClientSocket*>(socket_.get()); DCHECK(ssl_socket); if (!context_) return result; if (SSLClientSocket::IgnoreCertError(result, LOAD_IGNORE_ALL_CERT_ERRORS)) { const HttpNetworkSession::Params* session_params = context_->GetNetworkSessionParams(); if (session_params && session_params->ignore_certificate_errors) return OK; } if (!delegate_) return result; SSLInfo ssl_info; ssl_socket->GetSSLInfo(&ssl_info); TransportSecurityState::DomainState domain_state; const bool fatal = context_->transport_security_state() && context_->transport_security_state()->GetDomainState(url_.host(), SSLConfigService::IsSNIAvailable(context_->ssl_config_service()), &domain_state) && domain_state.ShouldSSLErrorsBeFatal(); delegate_->OnSSLCertificateError(this, ssl_info, fatal); return ERR_IO_PENDING; }
171,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: void gdImageFill(gdImagePtr im, int x, int y, int nc) { int l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; int alphablending_bak; /* stack of filled segments */ /* struct seg stack[FILL_MAX],*sp = stack;; */ struct seg *stack = NULL; struct seg *sp; if (!im->trueColor && nc > (im->colorsTotal -1)) { return; } alphablending_bak = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (nc==gdTiled){ _gdImageFillTiled(im,x,y,nc); im->alphaBlendingFlag = alphablending_bak; return; } wx2=im->sx;wy2=im->sy; oc = gdImageGetPixel(im, x, y); if (oc==nc || x<0 || x>wx2 || y<0 || y>wy2) { im->alphaBlendingFlag = alphablending_bak; return; } /* Do not use the 4 neighbors implementation with * small images */ if (im->sx < 4) { int ix = x, iy = y, c; do { do { c = gdImageGetPixel(im, ix, iy); if (c != oc) { goto done; } gdImageSetPixel(im, ix, iy, nc); } while(ix++ < (im->sx -1)); ix = x; } while(iy++ < (im->sy -1)); goto done; } stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1); sp = stack; /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && gdImageGetPixel(im,x, y)==oc; x--) { gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for (; x<=wx2 && gdImageGetPixel(im,x, y)==oc; x++) { gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for (x++; x<=x2 && (gdImageGetPixel(im, x, y)!=oc); x++); l = x; } while (x<=x2); } efree(stack); done: im->alphaBlendingFlag = alphablending_bak; } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
void gdImageFill(gdImagePtr im, int x, int y, int nc) { int l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; int alphablending_bak; /* stack of filled segments */ /* struct seg stack[FILL_MAX],*sp = stack;; */ struct seg *stack = NULL; struct seg *sp; if (!im->trueColor && nc > (im->colorsTotal -1)) { return; } alphablending_bak = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (nc==gdTiled){ _gdImageFillTiled(im,x,y,nc); im->alphaBlendingFlag = alphablending_bak; return; } wx2=im->sx;wy2=im->sy; oc = gdImageGetPixel(im, x, y); if (oc==nc || x<0 || x>wx2 || y<0 || y>wy2) { im->alphaBlendingFlag = alphablending_bak; return; } /* Do not use the 4 neighbors implementation with * small images */ if (im->sx < 4) { int ix = x, iy = y, c; do { do { c = gdImageGetPixel(im, ix, iy); if (c != oc) { goto done; } gdImageSetPixel(im, ix, iy, nc); } while(ix++ < (im->sx -1)); ix = x; } while(iy++ < (im->sy -1)); goto done; } stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1); sp = stack; /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && gdImageGetPixel(im,x, y)==oc; x--) { gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for (; x<=wx2 && gdImageGetPixel(im,x, y)==oc; x++) { gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for (x++; x<=x2 && (gdImageGetPixel(im, x, y)!=oc); x++); l = x; } while (x<=x2); } efree(stack); done: im->alphaBlendingFlag = alphablending_bak; }
167,128
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 impeg2d_peek_next_start_code(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_dec->s_bit_stream.u4_offset <= ps_dec->s_bit_stream.u4_max_offset)) { impeg2d_bit_stream_get(ps_stream,8); } return; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
void impeg2d_peek_next_start_code(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) { impeg2d_bit_stream_get(ps_stream,8); } return; }
173,951
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: json_t *json_object(void) { json_object_t *object = jsonp_malloc(sizeof(json_object_t)); if(!object) return NULL; json_init(&object->json, JSON_OBJECT); if(hashtable_init(&object->hashtable)) { jsonp_free(object); return NULL; } object->serial = 0; object->visited = 0; return &object->json; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
json_t *json_object(void) { json_object_t *object = jsonp_malloc(sizeof(json_object_t)); if(!object) return NULL; if (!hashtable_seed) { /* Autoseed */ json_object_seed(0); } json_init(&object->json, JSON_OBJECT); if(hashtable_init(&object->hashtable)) { jsonp_free(object); return NULL; } object->serial = 0; object->visited = 0; return &object->json; }
166,535
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: l2tp_call_errors_print(netdissect_options *ndo, const u_char *dat) { const uint16_t *ptr = (const uint16_t *)dat; uint16_t val_h, val_l; ptr++; /* skip "Reserved" */ val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "CRCErr=%u ", (val_h<<16) + val_l)); val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "FrameErr=%u ", (val_h<<16) + val_l)); val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "HardOver=%u ", (val_h<<16) + val_l)); val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "BufOver=%u ", (val_h<<16) + val_l)); val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "Timeout=%u ", (val_h<<16) + val_l)); val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "AlignErr=%u ", (val_h<<16) + val_l)); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_call_errors_print(netdissect_options *ndo, const u_char *dat) l2tp_call_errors_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; uint16_t val_h, val_l; if (length < 2) { ND_PRINT((ndo, "AVP too short")); return; } ptr++; /* skip "Reserved" */ length -= 2; if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2; val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2; ND_PRINT((ndo, "CRCErr=%u ", (val_h<<16) + val_l)); if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2; val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2; ND_PRINT((ndo, "FrameErr=%u ", (val_h<<16) + val_l)); if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2; val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2; ND_PRINT((ndo, "HardOver=%u ", (val_h<<16) + val_l)); if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2; val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2; ND_PRINT((ndo, "BufOver=%u ", (val_h<<16) + val_l)); if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; length -= 2; val_l = EXTRACT_16BITS(ptr); ptr++; length -= 2; ND_PRINT((ndo, "Timeout=%u ", (val_h<<16) + val_l)); if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } val_h = EXTRACT_16BITS(ptr); ptr++; val_l = EXTRACT_16BITS(ptr); ptr++; ND_PRINT((ndo, "AlignErr=%u ", (val_h<<16) + val_l)); }
167,893
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 TearDownTestCase() { vpx_free(source_data_); source_data_ = NULL; vpx_free(reference_data_); reference_data_ = NULL; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void TearDownTestCase() { vpx_free(source_data8_); source_data8_ = NULL; vpx_free(reference_data8_); reference_data8_ = NULL; vpx_free(second_pred8_); second_pred8_ = NULL; vpx_free(source_data16_); source_data16_ = NULL; vpx_free(reference_data16_); reference_data16_ = NULL; vpx_free(second_pred16_); second_pred16_ = NULL; }
174,579
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 rpc_init_task(struct rpc_task *task, const struct rpc_task_setup *task_setup_data) { memset(task, 0, sizeof(*task)); atomic_set(&task->tk_count, 1); task->tk_flags = task_setup_data->flags; task->tk_ops = task_setup_data->callback_ops; task->tk_calldata = task_setup_data->callback_data; INIT_LIST_HEAD(&task->tk_task); /* Initialize retry counters */ task->tk_garb_retry = 2; task->tk_cred_retry = 2; task->tk_priority = task_setup_data->priority - RPC_PRIORITY_LOW; task->tk_owner = current->tgid; /* Initialize workqueue for async tasks */ task->tk_workqueue = task_setup_data->workqueue; if (task->tk_ops->rpc_call_prepare != NULL) task->tk_action = rpc_prepare_task; /* starting timestamp */ task->tk_start = ktime_get(); dprintk("RPC: new task initialized, procpid %u\n", task_pid_nr(current)); } Commit Message: NLM: Don't hang forever on NLM unlock requests If the NLM daemon is killed on the NFS server, we can currently end up hanging forever on an 'unlock' request, instead of aborting. Basically, if the rpcbind request fails, or the server keeps returning garbage, we really want to quit instead of retrying. Tested-by: Vasily Averin <vvs@sw.ru> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> Cc: stable@kernel.org CWE ID: CWE-399
static void rpc_init_task(struct rpc_task *task, const struct rpc_task_setup *task_setup_data) { memset(task, 0, sizeof(*task)); atomic_set(&task->tk_count, 1); task->tk_flags = task_setup_data->flags; task->tk_ops = task_setup_data->callback_ops; task->tk_calldata = task_setup_data->callback_data; INIT_LIST_HEAD(&task->tk_task); /* Initialize retry counters */ task->tk_garb_retry = 2; task->tk_cred_retry = 2; task->tk_rebind_retry = 2; task->tk_priority = task_setup_data->priority - RPC_PRIORITY_LOW; task->tk_owner = current->tgid; /* Initialize workqueue for async tasks */ task->tk_workqueue = task_setup_data->workqueue; if (task->tk_ops->rpc_call_prepare != NULL) task->tk_action = rpc_prepare_task; /* starting timestamp */ task->tk_start = ktime_get(); dprintk("RPC: new task initialized, procpid %u\n", task_pid_nr(current)); }
166,223
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: String InspectorPageAgent::CachedResourceTypeJson( const Resource& cached_resource) { return ResourceTypeJson(CachedResourceType(cached_resource)); } 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 <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
String InspectorPageAgent::CachedResourceTypeJson( const Resource& cached_resource) { return ResourceTypeJson(ToResourceType(cached_resource.GetType())); }
172,470
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + (nbytes + 1); length = *ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); } Commit Message: CWE ID: CWE-682
char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + nbytes; length = *ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); }
164,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: bool Plugin::LoadNaClModuleContinuationIntern(ErrorInfo* error_info) { if (using_ipc_proxy_) return true; if (!main_subprocess_.StartSrpcServices()) { error_info->SetReport(ERROR_SRPC_CONNECTION_FAIL, "SRPC connection failure for " + main_subprocess_.description()); return false; } if (!main_subprocess_.StartJSObjectProxy(this, error_info)) { return false; } PLUGIN_PRINTF(("Plugin::LoadNaClModule (%s)\n", main_subprocess_.detailed_description().c_str())); return true; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool Plugin::LoadNaClModuleContinuationIntern(ErrorInfo* error_info) { if (!main_subprocess_.StartSrpcServices()) { error_info->SetReport(ERROR_SRPC_CONNECTION_FAIL, "SRPC connection failure for " + main_subprocess_.description()); return false; } if (!main_subprocess_.StartJSObjectProxy(this, error_info)) { return false; } PLUGIN_PRINTF(("Plugin::LoadNaClModule (%s)\n", main_subprocess_.detailed_description().c_str())); return true; }
170,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: static int empty_write_end(struct page *page, unsigned from, unsigned to, int mode) { struct inode *inode = page->mapping->host; struct gfs2_inode *ip = GFS2_I(inode); struct buffer_head *bh; unsigned offset, blksize = 1 << inode->i_blkbits; pgoff_t end_index = i_size_read(inode) >> PAGE_CACHE_SHIFT; zero_user(page, from, to-from); mark_page_accessed(page); if (page->index < end_index || !(mode & FALLOC_FL_KEEP_SIZE)) { if (!gfs2_is_writeback(ip)) gfs2_page_add_databufs(ip, page, from, to); block_commit_write(page, from, to); return 0; } offset = 0; bh = page_buffers(page); while (offset < to) { if (offset >= from) { set_buffer_uptodate(bh); mark_buffer_dirty(bh); clear_buffer_new(bh); write_dirty_buffer(bh, WRITE); } offset += blksize; bh = bh->b_this_page; } offset = 0; bh = page_buffers(page); while (offset < to) { if (offset >= from) { wait_on_buffer(bh); if (!buffer_uptodate(bh)) return -EIO; } offset += blksize; bh = bh->b_this_page; } return 0; } Commit Message: GFS2: rewrite fallocate code to write blocks directly GFS2's fallocate code currently goes through the page cache. Since it's only writing to the end of the file or to holes in it, it doesn't need to, and it was causing issues on low memory environments. This patch pulls in some of Steve's block allocation work, and uses it to simply allocate the blocks for the file, and zero them out at allocation time. It provides a slight performance increase, and it dramatically simplifies the code. Signed-off-by: Benjamin Marzinski <bmarzins@redhat.com> Signed-off-by: Steven Whitehouse <swhiteho@redhat.com> CWE ID: CWE-119
static int empty_write_end(struct page *page, unsigned from,
166,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) { assert(pCluster); assert(pCluster->m_index < 0); assert(idx >= m_clusterCount); const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; assert(size >= count); if (count >= size) { const long n = (size <= 0) ? 2048 : 2*size; Cluster** const qq = new Cluster*[n]; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; } assert(m_clusters); Cluster** const p = m_clusters + idx; Cluster** q = m_clusters + count; assert(q >= p); assert(q < (m_clusters + size)); while (q > p) { Cluster** const qq = q - 1; assert((*qq)->m_index < 0); *q = *qq; q = qq; } m_clusters[idx] = pCluster; ++m_clusterPreloadCount; } 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
void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) if (m_clusterPreloadCount > 0) { assert(m_clusters); Cluster** const p = m_clusters + m_clusterCount; assert(*p); assert((*p)->m_index < 0); Cluster** q = p + m_clusterPreloadCount; assert(q < (m_clusters + size)); for (;;) { Cluster** const qq = q - 1; assert((*qq)->m_index < 0); *q = *qq; q = qq; if (q == p) break; } } m_clusters[idx] = pCluster; ++m_clusterCount; }
174,431
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: on_unregister_handler(TCMUService1HandlerManager1 *interface, GDBusMethodInvocation *invocation, gchar *subtype, gpointer user_data) { struct tcmur_handler *handler = find_handler_by_subtype(subtype); struct dbus_info *info = handler->opaque; if (!handler) { g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", FALSE, "unknown subtype")); return TRUE; } dbus_unexport_handler(handler); tcmur_unregister_handler(handler); g_bus_unwatch_name(info->watcher_id); g_free(info); g_free(handler); g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", TRUE, "succeeded")); return TRUE; } Commit Message: fixed local DoS when UnregisterHandler was called for a not existing handler Any user with DBUS access could cause a SEGFAULT in tcmu-runner by running something like this: dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:123 CWE ID: CWE-20
on_unregister_handler(TCMUService1HandlerManager1 *interface, GDBusMethodInvocation *invocation, gchar *subtype, gpointer user_data) { struct tcmur_handler *handler = find_handler_by_subtype(subtype); struct dbus_info *info = handler ? handler->opaque : NULL; if (!handler) { g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", FALSE, "unknown subtype")); return TRUE; } dbus_unexport_handler(handler); tcmur_unregister_handler(handler); g_bus_unwatch_name(info->watcher_id); g_free(info); g_free(handler); g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", TRUE, "succeeded")); return TRUE; }
167,630
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 CmapCoverage::getCoverage(SparseBitSet& coverage, const uint8_t* cmap_data, size_t cmap_size) { vector<uint32_t> coverageVec; const size_t kHeaderSize = 4; const size_t kNumTablesOffset = 2; const size_t kTableSize = 8; const size_t kPlatformIdOffset = 0; const size_t kEncodingIdOffset = 2; const size_t kOffsetOffset = 4; const int kMicrosoftPlatformId = 3; const int kUnicodeBmpEncodingId = 1; const int kUnicodeUcs4EncodingId = 10; if (kHeaderSize > cmap_size) { return false; } int numTables = readU16(cmap_data, kNumTablesOffset); if (kHeaderSize + numTables * kTableSize > cmap_size) { return false; } int bestTable = -1; for (int i = 0; i < numTables; i++) { uint16_t platformId = readU16(cmap_data, kHeaderSize + i * kTableSize + kPlatformIdOffset); uint16_t encodingId = readU16(cmap_data, kHeaderSize + i * kTableSize + kEncodingIdOffset); if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeUcs4EncodingId) { bestTable = i; break; } else if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeBmpEncodingId) { bestTable = i; } } #ifdef PRINTF_DEBUG printf("best table = %d\n", bestTable); #endif if (bestTable < 0) { return false; } uint32_t offset = readU32(cmap_data, kHeaderSize + bestTable * kTableSize + kOffsetOffset); if (offset + 2 > cmap_size) { return false; } uint16_t format = readU16(cmap_data, offset); bool success = false; const uint8_t* tableData = cmap_data + offset; const size_t tableSize = cmap_size - offset; if (format == 4) { success = getCoverageFormat4(coverageVec, tableData, tableSize); } else if (format == 12) { success = getCoverageFormat12(coverageVec, tableData, tableSize); } if (success) { coverage.initFromRanges(&coverageVec.front(), coverageVec.size() >> 1); } #ifdef PRINTF_DEBUG for (int i = 0; i < coverageVec.size(); i += 2) { printf("%x:%x\n", coverageVec[i], coverageVec[i + 1]); } #endif return success; } Commit Message: Reject fonts with invalid ranges in cmap A corrupt or malicious font may have a negative size in its cmap range, which in turn could lead to memory corruption. This patch detects the case and rejects the font, and also includes an assertion in the sparse bit set implementation if we missed any such case. External issue: https://code.google.com/p/android/issues/detail?id=192618 Bug: 26413177 Change-Id: Icc0c80e4ef389abba0964495b89aa0fae3e9f4b2 CWE ID: CWE-20
bool CmapCoverage::getCoverage(SparseBitSet& coverage, const uint8_t* cmap_data, size_t cmap_size) { vector<uint32_t> coverageVec; const size_t kHeaderSize = 4; const size_t kNumTablesOffset = 2; const size_t kTableSize = 8; const size_t kPlatformIdOffset = 0; const size_t kEncodingIdOffset = 2; const size_t kOffsetOffset = 4; const uint16_t kMicrosoftPlatformId = 3; const uint16_t kUnicodeBmpEncodingId = 1; const uint16_t kUnicodeUcs4EncodingId = 10; const uint32_t kNoTable = UINT32_MAX; if (kHeaderSize > cmap_size) { return false; } uint32_t numTables = readU16(cmap_data, kNumTablesOffset); if (kHeaderSize + numTables * kTableSize > cmap_size) { return false; } uint32_t bestTable = kNoTable; for (uint32_t i = 0; i < numTables; i++) { uint16_t platformId = readU16(cmap_data, kHeaderSize + i * kTableSize + kPlatformIdOffset); uint16_t encodingId = readU16(cmap_data, kHeaderSize + i * kTableSize + kEncodingIdOffset); if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeUcs4EncodingId) { bestTable = i; break; } else if (platformId == kMicrosoftPlatformId && encodingId == kUnicodeBmpEncodingId) { bestTable = i; } } #ifdef PRINTF_DEBUG printf("best table = %d\n", bestTable); #endif if (bestTable == kNoTable) { return false; } uint32_t offset = readU32(cmap_data, kHeaderSize + bestTable * kTableSize + kOffsetOffset); if (offset > cmap_size - 2) { return false; } uint16_t format = readU16(cmap_data, offset); bool success = false; const uint8_t* tableData = cmap_data + offset; const size_t tableSize = cmap_size - offset; if (format == 4) { success = getCoverageFormat4(coverageVec, tableData, tableSize); } else if (format == 12) { success = getCoverageFormat12(coverageVec, tableData, tableSize); } if (success) { coverage.initFromRanges(&coverageVec.front(), coverageVec.size() >> 1); } #ifdef PRINTF_DEBUG for (int i = 0; i < coverageVec.size(); i += 2) { printf("%x:%x\n", coverageVec[i], coverageVec[i + 1]); } #endif return success; }
174,233
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 GpuMessageFilter::EstablishChannelCallback( IPC::Message* reply, const IPC::ChannelHandle& channel, base::ProcessHandle gpu_process_for_browser, const content::GPUInfo& gpu_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); base::ProcessHandle renderer_process_for_gpu; if (gpu_process_for_browser != 0) { #if defined(OS_WIN) DuplicateHandle(base::GetCurrentProcessHandle(), peer_handle(), gpu_process_for_browser, &renderer_process_for_gpu, PROCESS_DUP_HANDLE, FALSE, 0); #else renderer_process_for_gpu = peer_handle(); #endif } else { renderer_process_for_gpu = 0; } GpuHostMsg_EstablishGpuChannel::WriteReplyParams( reply, render_process_id_, channel, renderer_process_for_gpu, gpu_info); Send(reply); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuMessageFilter::EstablishChannelCallback( IPC::Message* reply, const IPC::ChannelHandle& channel, const content::GPUInfo& gpu_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); GpuHostMsg_EstablishGpuChannel::WriteReplyParams( reply, render_process_id_, channel, gpu_info); Send(reply); }
170,925
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 long CuePoint::GetTime(const Segment* pSegment) const { assert(pSegment); assert(m_timecode >= 0); const SegmentInfo* const pInfo = pSegment->GetInfo(); assert(pInfo); const long long scale = pInfo->GetTimeCodeScale(); assert(scale >= 1); const long long time = scale * m_timecode; return time; } 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 long CuePoint::GetTime(const Segment* pSegment) const
174,364
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void msleep(uint64_t ms) { usleep(ms * 1000); } 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 void msleep(uint64_t ms) { TEMP_FAILURE_RETRY(usleep(ms * 1000)); }
173,489
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 registerBlobURLFromTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL); } 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:
static void registerBlobURLFromTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) registry->registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL); }
170,686
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 WebContentsImpl::LoadingStateChanged(bool to_different_document, bool due_to_interstitial, LoadNotificationDetails* details) { if (ShowingInterstitialPage() && GetRenderManager()->interstitial_page()->pause_throbber() && !due_to_interstitial) { return; } bool is_loading = IsLoading(); if (!is_loading) { load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE, base::string16()); load_state_host_.clear(); upload_size_ = 0; upload_position_ = 0; } GetRenderManager()->SetIsLoading(is_loading); waiting_for_response_ = is_loading; is_load_to_different_document_ = to_different_document; if (delegate_) delegate_->LoadingStateChanged(this, to_different_document); NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD); std::string url = (details ? details->url.possibly_invalid_spec() : "NULL"); if (is_loading) { TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading", this, "URL", url, "Main FrameTreeNode id", GetFrameTree()->root()->frame_tree_node_id()); for (auto& observer : observers_) observer.DidStartLoading(); } else { TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading", this, "URL", url); for (auto& observer : observers_) observer.DidStopLoading(); } int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP; NotificationDetails det = NotificationService::NoDetails(); if (details) det = Details<LoadNotificationDetails>(details); NotificationService::current()->Notify( type, Source<NavigationController>(&controller_), det); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
void WebContentsImpl::LoadingStateChanged(bool to_different_document, bool due_to_interstitial, LoadNotificationDetails* details) { if (ShowingInterstitialPage() && interstitial_page_->pause_throbber() && !due_to_interstitial) { return; } bool is_loading = IsLoading(); if (!is_loading) { load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE, base::string16()); load_state_host_.clear(); upload_size_ = 0; upload_position_ = 0; } GetRenderManager()->SetIsLoading(is_loading); waiting_for_response_ = is_loading; is_load_to_different_document_ = to_different_document; if (delegate_) delegate_->LoadingStateChanged(this, to_different_document); NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD); std::string url = (details ? details->url.possibly_invalid_spec() : "NULL"); if (is_loading) { TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading", this, "URL", url, "Main FrameTreeNode id", GetFrameTree()->root()->frame_tree_node_id()); for (auto& observer : observers_) observer.DidStartLoading(); } else { TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading", this, "URL", url); for (auto& observer : observers_) observer.DidStopLoading(); } int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP; NotificationDetails det = NotificationService::NoDetails(); if (details) det = Details<LoadNotificationDetails>(details); NotificationService::current()->Notify( type, Source<NavigationController>(&controller_), det); }
172,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 ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) { if (current_input_method_.id != new_input_method.id) { previous_input_method_ = current_input_method_; current_input_method_ = new_input_method; if (!input_method::SetCurrentKeyboardLayoutByName( current_input_method_.keyboard_layout)) { LOG(ERROR) << "Failed to change keyboard layout to " << current_input_method_.keyboard_layout; } ObserverListBase<Observer>::Iterator it(observers_); Observer* first_observer = it.GetNext(); if (first_observer) { first_observer->PreferenceUpdateNeeded(this, previous_input_method_, current_input_method_); } } const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(Observer, observers_, InputMethodChanged(this, current_input_method_, num_active_input_methods)); } 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 ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) { void ChangeCurrentInputMethod(const input_method::InputMethodDescriptor& new_input_method) { if (current_input_method_.id != new_input_method.id) { previous_input_method_ = current_input_method_; current_input_method_ = new_input_method; if (!input_method::SetCurrentKeyboardLayoutByName( current_input_method_.keyboard_layout)) { LOG(ERROR) << "Failed to change keyboard layout to " << current_input_method_.keyboard_layout; } ObserverListBase<InputMethodLibrary::Observer>::Iterator it(observers_); InputMethodLibrary::Observer* first_observer = it.GetNext(); if (first_observer) { first_observer->PreferenceUpdateNeeded(this, previous_input_method_, current_input_method_); } } const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(InputMethodLibrary::Observer, observers_, InputMethodChanged(this, current_input_method_, num_active_input_methods)); }
170,478
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: AppModalDialog::AppModalDialog(WebContents* web_contents, const string16& title) : valid_(true), native_dialog_(NULL), title_(title), web_contents_(web_contents) { } Commit Message: Fix a Windows crash bug with javascript alerts from extension popups. BUG=137707 Review URL: https://chromiumcodereview.appspot.com/10828423 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
AppModalDialog::AppModalDialog(WebContents* web_contents, const string16& title) : valid_(true), native_dialog_(NULL), title_(title), web_contents_(web_contents), completed_(false) { }
170,753
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 SSL_library_init(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_cbc()); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); #if !defined(OPENSSL_NO_MD5) && (defined(__x86_64) || defined(__x86_64__)) EVP_add_cipher(EVP_rc4_hmac_md5()); #endif #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_cbc()); /* Not actually used for SSL/TLS but this makes PKCS#12 work * if an application only calls SSL_library_init(). */ EVP_add_cipher(EVP_rc2_40_cbc()); #endif #ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_256_cbc()); EVP_add_cipher(EVP_aes_128_gcm()); EVP_add_cipher(EVP_aes_256_gcm()); #if 0 /* Disabled because of timing side-channel leaks. */ #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1) EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1()); #endif #endif #endif #ifndef OPENSSL_NO_CAMELLIA #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_256_cbc()); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_cbc()); #endif #ifndef OPENSSL_NO_MD5 EVP_add_digest(EVP_md5()); EVP_add_digest_alias(SN_md5,"ssl2-md5"); EVP_add_digest_alias(SN_md5,"ssl3-md5"); #endif #ifndef OPENSSL_NO_SHA EVP_add_digest(EVP_sha1()); /* RSA with sha1 */ EVP_add_digest_alias(SN_sha1,"ssl3-sha1"); EVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA); #endif #ifndef OPENSSL_NO_SHA256 EVP_add_digest(EVP_sha224()); EVP_add_digest(EVP_sha256()); #endif #ifndef OPENSSL_NO_SHA512 EVP_add_digest(EVP_sha384()); EVP_add_digest(EVP_sha512()); #endif #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA) EVP_add_digest(EVP_dss1()); /* DSA with sha1 */ EVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2); EVP_add_digest_alias(SN_dsaWithSHA1,"DSS1"); EVP_add_digest_alias(SN_dsaWithSHA1,"dss1"); #endif #ifndef OPENSSL_NO_ECDSA EVP_add_digest(EVP_ecdsa()); #endif /* If you want support for phased out ciphers, add the following */ #if 0 EVP_add_digest(EVP_sha()); EVP_add_digest(EVP_dss()); #endif #ifndef OPENSSL_NO_COMP /* This will initialise the built-in compression algorithms. The value returned is a STACK_OF(SSL_COMP), but that can be discarded safely */ (void)SSL_COMP_get_compression_methods(); #endif /* initialize cipher/digest methods table */ ssl_load_ciphers(); return(1); } Commit Message: CWE ID: CWE-310
int SSL_library_init(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_cbc()); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); #if !defined(OPENSSL_NO_MD5) && (defined(__x86_64) || defined(__x86_64__)) EVP_add_cipher(EVP_rc4_hmac_md5()); #endif #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_cbc()); /* Not actually used for SSL/TLS but this makes PKCS#12 work * if an application only calls SSL_library_init(). */ EVP_add_cipher(EVP_rc2_40_cbc()); #endif #ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_256_cbc()); EVP_add_cipher(EVP_aes_128_gcm()); EVP_add_cipher(EVP_aes_256_gcm()); #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1) EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1()); #endif #endif #ifndef OPENSSL_NO_CAMELLIA #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_256_cbc()); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_cbc()); #endif #ifndef OPENSSL_NO_MD5 EVP_add_digest(EVP_md5()); EVP_add_digest_alias(SN_md5,"ssl2-md5"); EVP_add_digest_alias(SN_md5,"ssl3-md5"); #endif #ifndef OPENSSL_NO_SHA EVP_add_digest(EVP_sha1()); /* RSA with sha1 */ EVP_add_digest_alias(SN_sha1,"ssl3-sha1"); EVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA); #endif #ifndef OPENSSL_NO_SHA256 EVP_add_digest(EVP_sha224()); EVP_add_digest(EVP_sha256()); #endif #ifndef OPENSSL_NO_SHA512 EVP_add_digest(EVP_sha384()); EVP_add_digest(EVP_sha512()); #endif #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA) EVP_add_digest(EVP_dss1()); /* DSA with sha1 */ EVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2); EVP_add_digest_alias(SN_dsaWithSHA1,"DSS1"); EVP_add_digest_alias(SN_dsaWithSHA1,"dss1"); #endif #ifndef OPENSSL_NO_ECDSA EVP_add_digest(EVP_ecdsa()); #endif /* If you want support for phased out ciphers, add the following */ #if 0 EVP_add_digest(EVP_sha()); EVP_add_digest(EVP_dss()); #endif #ifndef OPENSSL_NO_COMP /* This will initialise the built-in compression algorithms. The value returned is a STACK_OF(SSL_COMP), but that can be discarded safely */ (void)SSL_COMP_get_compression_methods(); #endif /* initialize cipher/digest methods table */ ssl_load_ciphers(); return(1); }
164,869
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 skt_read(int fd, void *p, size_t len) { int read; struct pollfd pfd; struct timespec ts; FNLOG(); ts_log("skt_read recv", len, NULL); if ((read = recv(fd, p, len, MSG_NOSIGNAL)) == -1) { ERROR("write failed with errno=%d\n", errno); return -1; } return read; } 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 int skt_read(int fd, void *p, size_t len) { int read; struct pollfd pfd; struct timespec ts; FNLOG(); ts_log("skt_read recv", len, NULL); if ((read = TEMP_FAILURE_RETRY(recv(fd, p, len, MSG_NOSIGNAL))) == -1) { ERROR("write failed with errno=%d\n", errno); return -1; } return read; }
173,428
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: FileStream::FileStream(const scoped_refptr<base::TaskRunner>& task_runner) : context_(base::MakeUnique<Context>(task_runner)) {} Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <jbroman@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Bence Béky <bnc@chromium.org> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311
FileStream::FileStream(const scoped_refptr<base::TaskRunner>& task_runner)
173,262
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: MediaRecorder::MediaRecorder(ExecutionContext* context, MediaStream* stream, const MediaRecorderOptions* options, ExceptionState& exception_state) : PausableObject(context), stream_(stream), mime_type_(options->hasMimeType() ? options->mimeType() : kDefaultMimeType), stopped_(true), audio_bits_per_second_(0), video_bits_per_second_(0), state_(State::kInactive), dispatch_scheduled_event_runner_(AsyncMethodRunner<MediaRecorder>::Create( this, &MediaRecorder::DispatchScheduledEvent, context->GetTaskRunner(TaskType::kDOMManipulation))) { DCHECK(stream_->getTracks().size()); recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler( context->GetTaskRunner(TaskType::kInternalMediaRealTime)); DCHECK(recorder_handler_); if (!recorder_handler_) { exception_state.ThrowDOMException( DOMExceptionCode::kNotSupportedError, "No MediaRecorder handler can be created."); return; } AllocateVideoAndAudioBitrates(exception_state, context, options, stream, &audio_bits_per_second_, &video_bits_per_second_); const ContentType content_type(mime_type_); if (!recorder_handler_->Initialize( this, stream->Descriptor(), content_type.GetType(), content_type.Parameter("codecs"), audio_bits_per_second_, video_bits_per_second_)) { exception_state.ThrowDOMException( DOMExceptionCode::kNotSupportedError, "Failed to initialize native MediaRecorder the type provided (" + mime_type_ + ") is not supported."); return; } if (options->mimeType().IsEmpty()) { const String actual_mime_type = recorder_handler_->ActualMimeType(); if (!actual_mime_type.IsEmpty()) mime_type_ = actual_mime_type; } stopped_ = false; } Commit Message: Check context is attached before creating MediaRecorder Bug: 896736 Change-Id: I3ccfd2188fb15704af14c8af050e0a5667855d34 Reviewed-on: https://chromium-review.googlesource.com/c/1324231 Commit-Queue: Emircan Uysaler <emircan@chromium.org> Reviewed-by: Miguel Casas <mcasas@chromium.org> Cr-Commit-Position: refs/heads/master@{#606242} CWE ID: CWE-119
MediaRecorder::MediaRecorder(ExecutionContext* context, MediaStream* stream, const MediaRecorderOptions* options, ExceptionState& exception_state) : PausableObject(context), stream_(stream), mime_type_(options->hasMimeType() ? options->mimeType() : kDefaultMimeType), stopped_(true), audio_bits_per_second_(0), video_bits_per_second_(0), state_(State::kInactive), dispatch_scheduled_event_runner_(AsyncMethodRunner<MediaRecorder>::Create( this, &MediaRecorder::DispatchScheduledEvent, context->GetTaskRunner(TaskType::kDOMManipulation))) { if (context->IsContextDestroyed()) { exception_state.ThrowDOMException(DOMExceptionCode::kNotAllowedError, "Execution context is detached."); return; } DCHECK(stream_->getTracks().size()); recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler( context->GetTaskRunner(TaskType::kInternalMediaRealTime)); DCHECK(recorder_handler_); if (!recorder_handler_) { exception_state.ThrowDOMException( DOMExceptionCode::kNotSupportedError, "No MediaRecorder handler can be created."); return; } AllocateVideoAndAudioBitrates(exception_state, context, options, stream, &audio_bits_per_second_, &video_bits_per_second_); const ContentType content_type(mime_type_); if (!recorder_handler_->Initialize( this, stream->Descriptor(), content_type.GetType(), content_type.Parameter("codecs"), audio_bits_per_second_, video_bits_per_second_)) { exception_state.ThrowDOMException( DOMExceptionCode::kNotSupportedError, "Failed to initialize native MediaRecorder the type provided (" + mime_type_ + ") is not supported."); return; } if (options->mimeType().IsEmpty()) { const String actual_mime_type = recorder_handler_->ActualMimeType(); if (!actual_mime_type.IsEmpty()) mime_type_ = actual_mime_type; } stopped_ = false; }
172,605
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: gdImagePtr gdImageCreate (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sx, sy)) { return NULL; } if (overflow2(sizeof(unsigned char *), sy)) { return NULL; } im = (gdImage *) gdCalloc(1, sizeof(gdImage)); /* Row-major ever since gd 1.3 */ im->pixels = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy); im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy); im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; i < sy; i++) { /* Row-major ever since gd 1.3 */ im->pixels[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char)); im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char)); } im->sx = sx; im->sy = sy; im->colorsTotal = 0; im->transparent = (-1); im->interlace = 0; im->thick = 1; im->AA = 0; im->AA_polygon = 0; for (i = 0; i < gdMaxColors; i++) { im->open[i] = 1; im->red[i] = 0; im->green[i] = 0; im->blue[i] = 0; } im->trueColor = 0; im->tpixels = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
gdImagePtr gdImageCreate (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sx, sy)) { return NULL; } if (overflow2(sizeof(unsigned char *), sy)) { return NULL; } if (overflow2(sizeof(unsigned char *), sx)) { return NULL; } im = (gdImage *) gdCalloc(1, sizeof(gdImage)); /* Row-major ever since gd 1.3 */ im->pixels = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy); im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy); im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; i < sy; i++) { /* Row-major ever since gd 1.3 */ im->pixels[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char)); im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char)); } im->sx = sx; im->sy = sy; im->colorsTotal = 0; im->transparent = (-1); im->interlace = 0; im->thick = 1; im->AA = 0; im->AA_polygon = 0; for (i = 0; i < gdMaxColors; i++) { im->open[i] = 1; im->red[i] = 0; im->green[i] = 0; im->blue[i] = 0; } im->trueColor = 0; im->tpixels = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; }
167,127
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 rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *sigalg, ASN1_BIT_STRING *sig, EVP_PKEY *pkey) { /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) { RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey)) /* Carry on */ return 2; return -1; } Commit Message: CWE ID:
static int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn, X509_ALGOR *sigalg, ASN1_BIT_STRING *sig, EVP_PKEY *pkey) { /* Sanity check: make sure it is PSS */ if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) { RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE); return -1; } if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey) > 0) { /* Carry on */ return 2; } return -1; }
164,820
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 Browser::TabDetachedAt(TabContents* contents, int index) { TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void Browser::TabDetachedAt(TabContents* contents, int index) { void Browser::TabDetachedAt(WebContents* contents, int index) { TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH); }
171,507
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 RunExtremalCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); int max_error = 0; int total_error = 0; const int count_test_block = 100000; DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64); DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, 64); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, 64); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, 64); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < 64; ++j) { src[j] = rnd.Rand8() % 2 ? 255 : 0; dst[j] = src[j] > 0 ? 0 : 255; test_input_block[j] = src[j] - dst[j]; } REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_temp_block, pitch_)); REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, dst, pitch_)); for (int j = 0; j < 64; ++j) { const int diff = dst[j] - src[j]; const int error = diff * diff; if (max_error < error) max_error = error; total_error += error; } EXPECT_GE(1, max_error) << "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has" << "an individual roundtrip error > 1"; EXPECT_GE(count_test_block/5, total_error) << "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has average" << " roundtrip error > 1/5 per block"; } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunExtremalCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); int max_error = 0; int total_error = 0; int total_coeff_error = 0; const int count_test_block = 100000; DECLARE_ALIGNED(16, int16_t, test_input_block[64]); DECLARE_ALIGNED(16, tran_low_t, test_temp_block[64]); DECLARE_ALIGNED(16, tran_low_t, ref_temp_block[64]); DECLARE_ALIGNED(16, uint8_t, dst[64]); DECLARE_ALIGNED(16, uint8_t, src[64]); #if CONFIG_VP9_HIGHBITDEPTH DECLARE_ALIGNED(16, uint16_t, dst16[64]); DECLARE_ALIGNED(16, uint16_t, src16[64]); #endif for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < 64; ++j) { if (bit_depth_ == VPX_BITS_8) { if (i == 0) { src[j] = 255; dst[j] = 0; } else if (i == 1) { src[j] = 0; dst[j] = 255; } else { src[j] = rnd.Rand8() % 2 ? 255 : 0; dst[j] = rnd.Rand8() % 2 ? 255 : 0; } test_input_block[j] = src[j] - dst[j]; #if CONFIG_VP9_HIGHBITDEPTH } else { if (i == 0) { src16[j] = mask_; dst16[j] = 0; } else if (i == 1) { src16[j] = 0; dst16[j] = mask_; } else { src16[j] = rnd.Rand8() % 2 ? mask_ : 0; dst16[j] = rnd.Rand8() % 2 ? mask_ : 0; } test_input_block[j] = src16[j] - dst16[j]; #endif } } ASM_REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_temp_block, pitch_)); ASM_REGISTER_STATE_CHECK( fwd_txfm_ref(test_input_block, ref_temp_block, pitch_, tx_type_)); if (bit_depth_ == VPX_BITS_8) { ASM_REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, dst, pitch_)); #if CONFIG_VP9_HIGHBITDEPTH } else { ASM_REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_)); #endif } for (int j = 0; j < 64; ++j) { #if CONFIG_VP9_HIGHBITDEPTH const int diff = bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; #else const int diff = dst[j] - src[j]; #endif const int error = diff * diff; if (max_error < error) max_error = error; total_error += error; const int coeff_diff = test_temp_block[j] - ref_temp_block[j]; total_coeff_error += abs(coeff_diff); } EXPECT_GE(1 << 2 * (bit_depth_ - 8), max_error) << "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has" << "an individual roundtrip error > 1"; EXPECT_GE((count_test_block << 2 * (bit_depth_ - 8))/5, total_error) << "Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has average" << " roundtrip error > 1/5 per block"; EXPECT_EQ(0, total_coeff_error) << "Error: Extremal 8x8 FDCT/FHT has" << "overflow issues in the intermediate steps > 1"; } }
174,559
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 GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan) { if (paintingDisabled()) return; m_data->context->SetPen(wxPen(strokeColor(), strokeThickness(), strokeStyleToWxPenStyle(strokeStyle()))); m_data->context->DrawEllipticArc(rect.x(), rect.y(), rect.width(), rect.height(), startAngle, angleSpan); } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan) { if (paintingDisabled()) return; m_data->context->SetPen(wxPen(strokeColor(), strokeThickness(), strokeStyleToWxPenStyle(strokeStyle()))); m_data->context->DrawEllipticArc(rect.x(), rect.y(), rect.width(), rect.height(), startAngle, startAngle + angleSpan); }
170,427
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: ProcPutImage(ClientPtr client) { GC *pGC; DrawablePtr pDraw; long length; /* length of scanline server padded */ long lengthProto; /* length of scanline protocol padded */ char *tmpImage; REQUEST(xPutImageReq); REQUEST_AT_LEAST_SIZE(xPutImageReq); VALIDATE_DRAWABLE_AND_GC(stuff->drawable, pDraw, DixWriteAccess); if (stuff->format == XYBitmap) { if ((stuff->depth != 1) || (stuff->leftPad >= (unsigned int) screenInfo.bitmapScanlinePad)) return BadMatch; length = BitmapBytePad(stuff->width + stuff->leftPad); } else if (stuff->format == XYPixmap) { if ((pDraw->depth != stuff->depth) || (stuff->leftPad >= (unsigned int) screenInfo.bitmapScanlinePad)) return BadMatch; length = BitmapBytePad(stuff->width + stuff->leftPad); length *= stuff->depth; } else if (stuff->format == ZPixmap) { if ((pDraw->depth != stuff->depth) || (stuff->leftPad != 0)) return BadMatch; length = PixmapBytePad(stuff->width, stuff->depth); } else { client->errorValue = stuff->format; return BadValue; } tmpImage = (char *) &stuff[1]; lengthProto = length; if (lengthProto >= (INT32_MAX / stuff->height)) return BadLength; if ((bytes_to_int32(lengthProto * stuff->height) + bytes_to_int32(sizeof(xPutImageReq))) != client->req_len) return BadLength; ReformatImage(tmpImage, lengthProto * stuff->height, stuff->format == ZPixmap ? BitsPerPixel(stuff->depth) : 1, ClientOrder(client)); (*pGC->ops->PutImage) (pDraw, pGC, stuff->depth, stuff->dstX, stuff->dstY, stuff->width, stuff->height, stuff->leftPad, stuff->format, tmpImage); return Success; } Commit Message: CWE ID: CWE-369
ProcPutImage(ClientPtr client) { GC *pGC; DrawablePtr pDraw; long length; /* length of scanline server padded */ long lengthProto; /* length of scanline protocol padded */ char *tmpImage; REQUEST(xPutImageReq); REQUEST_AT_LEAST_SIZE(xPutImageReq); VALIDATE_DRAWABLE_AND_GC(stuff->drawable, pDraw, DixWriteAccess); if (stuff->format == XYBitmap) { if ((stuff->depth != 1) || (stuff->leftPad >= (unsigned int) screenInfo.bitmapScanlinePad)) return BadMatch; length = BitmapBytePad(stuff->width + stuff->leftPad); } else if (stuff->format == XYPixmap) { if ((pDraw->depth != stuff->depth) || (stuff->leftPad >= (unsigned int) screenInfo.bitmapScanlinePad)) return BadMatch; length = BitmapBytePad(stuff->width + stuff->leftPad); length *= stuff->depth; } else if (stuff->format == ZPixmap) { if ((pDraw->depth != stuff->depth) || (stuff->leftPad != 0)) return BadMatch; length = PixmapBytePad(stuff->width, stuff->depth); } else { client->errorValue = stuff->format; return BadValue; } tmpImage = (char *) &stuff[1]; lengthProto = length; if (stuff->height != 0 && lengthProto >= (INT32_MAX / stuff->height)) return BadLength; if ((bytes_to_int32(lengthProto * stuff->height) + bytes_to_int32(sizeof(xPutImageReq))) != client->req_len) return BadLength; ReformatImage(tmpImage, lengthProto * stuff->height, stuff->format == ZPixmap ? BitsPerPixel(stuff->depth) : 1, ClientOrder(client)); (*pGC->ops->PutImage) (pDraw, pGC, stuff->depth, stuff->dstX, stuff->dstY, stuff->width, stuff->height, stuff->leftPad, stuff->format, tmpImage); return Success; }
165,308
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: WebstoreBindings::WebstoreBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("Install", base::Bind(&WebstoreBindings::Install, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
WebstoreBindings::WebstoreBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("Install", "webstore", base::Bind(&WebstoreBindings::Install, base::Unretained(this))); }
172,245
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintWebViewHelper::OnPrintPages() { blink::WebLocalFrame* frame; if (!GetPrintFrame(&frame)) return; auto plugin = delegate_->GetPdfElement(frame); Print(frame, plugin, false); } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
void PrintWebViewHelper::OnPrintPages() { CHECK_LE(ipc_nesting_level_, 1); blink::WebLocalFrame* frame; if (!GetPrintFrame(&frame)) return; auto plugin = delegate_->GetPdfElement(frame); Print(frame, plugin, false); }
171,875
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: de_dotdot( char* file ) { char* cp; char* cp2; int l; /* Collapse any multiple / sequences. */ while ( ( cp = strstr( file, "//") ) != (char*) 0 ) { for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 ) continue; (void) strcpy( cp + 1, cp2 ); } /* Remove leading ./ and any /./ sequences. */ while ( strncmp( file, "./", 2 ) == 0 ) (void) memmove( file, file + 2, strlen( file ) - 1 ); while ( ( cp = strstr( file, "/./") ) != (char*) 0 ) (void) memmove( cp, cp + 2, strlen( file ) - 1 ); /* Alternate between removing leading ../ and removing xxx/../ */ for (;;) { while ( strncmp( file, "../", 3 ) == 0 ) (void) memmove( file, file + 3, strlen( file ) - 2 ); cp = strstr( file, "/../" ); if ( cp == (char*) 0 ) break; for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; (void) strcpy( cp2 + 1, cp + 4 ); } /* Also elide any xxx/.. at the end. */ while ( ( l = strlen( file ) ) > 3 && strcmp( ( cp = file + l - 3 ), "/.." ) == 0 ) { for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; if ( cp2 < file ) break; *cp2 = '\0'; } } Commit Message: Fix heap buffer overflow in de_dotdot CWE ID: CWE-119
de_dotdot( char* file ) { char* cp; char* cp2; int l; /* Collapse any multiple / sequences. */ while ( ( cp = strstr( file, "//") ) != (char*) 0 ) { for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 ) continue; (void) strcpy( cp + 1, cp2 ); } /* Remove leading ./ and any /./ sequences. */ while ( strncmp( file, "./", 2 ) == 0 ) (void) memmove( file, file + 2, strlen( file ) - 1 ); while ( ( cp = strstr( file, "/./") ) != (char*) 0 ) (void) memmove( cp, cp + 2, strlen( cp ) - 1 ); /* Alternate between removing leading ../ and removing xxx/../ */ for (;;) { while ( strncmp( file, "../", 3 ) == 0 ) (void) memmove( file, file + 3, strlen( file ) - 2 ); cp = strstr( file, "/../" ); if ( cp == (char*) 0 ) break; for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; (void) strcpy( cp2 + 1, cp + 4 ); } /* Also elide any xxx/.. at the end. */ while ( ( l = strlen( file ) ) > 3 && strcmp( ( cp = file + l - 3 ), "/.." ) == 0 ) { for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 ) continue; if ( cp2 < file ) break; *cp2 = '\0'; } }
168,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: SPL_METHOD(DirectoryIterator, isDot) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, isDot) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name)); }
167,037
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 DetectFlow(ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { /* No need to perform any detection on this packet, if the the given flag is set.*/ if ((p->flags & PKT_NOPACKET_INSPECTION) || (PACKET_TEST_ACTION(p, ACTION_DROP))) { /* hack: if we are in pass the entire flow mode, we need to still * update the inspect_id forward. So test for the condition here, * and call the update code if necessary. */ const int pass = ((p->flow->flags & FLOW_NOPACKET_INSPECTION)); const AppProto alproto = FlowGetAppProtocol(p->flow); if (pass && AppLayerParserProtocolSupportsTxs(p->proto, alproto)) { uint8_t flags; if (p->flowflags & FLOW_PKT_TOSERVER) { flags = STREAM_TOSERVER; } else { flags = STREAM_TOCLIENT; } flags = FlowGetDisruptionFlags(p->flow, flags); DeStateUpdateInspectTransactionId(p->flow, flags, true); } return; } /* see if the packet matches one or more of the sigs */ (void)DetectRun(tv, de_ctx, det_ctx, p); } Commit Message: stream: still inspect packets dropped by stream The detect engine would bypass packets that are set as dropped. This seems sane, as these packets are going to be dropped anyway. However, it lead to the following corner case: stream events that triggered the drop could not be matched on the rules. The packet with the event wouldn't make it to the detect engine due to the bypass. This patch changes the logic to not bypass DROP packets anymore. Packets that are dropped by the stream engine will set the no payload inspection flag, so avoid needless cost. CWE ID: CWE-693
static void DetectFlow(ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { if (p->flags & PKT_NOPACKET_INSPECTION) { /* hack: if we are in pass the entire flow mode, we need to still * update the inspect_id forward. So test for the condition here, * and call the update code if necessary. */ const int pass = ((p->flow->flags & FLOW_NOPACKET_INSPECTION)); const AppProto alproto = FlowGetAppProtocol(p->flow); if (pass && AppLayerParserProtocolSupportsTxs(p->proto, alproto)) { uint8_t flags; if (p->flowflags & FLOW_PKT_TOSERVER) { flags = STREAM_TOSERVER; } else { flags = STREAM_TOCLIENT; } flags = FlowGetDisruptionFlags(p->flow, flags); DeStateUpdateInspectTransactionId(p->flow, flags, true); } SCLogDebug("p->pcap %"PRIu64": no detection on packet, " "PKT_NOPACKET_INSPECTION is set", p->pcap_cnt); return; } /* see if the packet matches one or more of the sigs */ (void)DetectRun(tv, de_ctx, det_ctx, p); }
169,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: get_caller_uid (GDBusMethodInvocation *context, gint *uid) { PolkitSubject *subject; PolkitSubject *process; subject = polkit_system_bus_name_new (g_dbus_method_invocation_get_sender (context)); process = polkit_system_bus_name_get_process_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, NULL); if (!process) { g_object_unref (subject); return FALSE; } *uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (process)); g_object_unref (subject); g_object_unref (process); return TRUE; } Commit Message: CWE ID: CWE-362
get_caller_uid (GDBusMethodInvocation *context, gint *uid) get_caller_uid (GDBusMethodInvocation *context, gint *uid) { GVariant *reply; GError *error; error = NULL; reply = g_dbus_connection_call_sync (g_dbus_method_invocation_get_connection (context), "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetConnectionUnixUser", g_variant_new ("(s)", g_dbus_method_invocation_get_sender (context)), G_VARIANT_TYPE ("(u)"), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (reply == NULL) { g_warning ("Could not talk to message bus to find uid of sender %s: %s", g_dbus_method_invocation_get_sender (context), error->message); g_error_free (error); return FALSE; } g_variant_get (reply, "(u)", uid); g_variant_unref (reply); return TRUE; }
165,011
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 TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("options_page")); GURL omnibox(chrome::kChromeUIOmniboxURL); ui_test_utils::NavigateToURL(browser(), omnibox); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(omnibox, tab1->GetURL()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2); GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph1); GURL extension_url("chrome-extension://" + extension->id()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), extension_url); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), extension_url); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <alexmos@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Commit-Queue: Charlie Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285
void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("options_page")); // Change the first tab to be the omnibox page (WebUI). GURL omnibox(chrome::kChromeUIOmniboxURL); ui_test_utils::NavigateToURL(browser(), omnibox); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(omnibox, tab1->GetURL()); EXPECT_EQ(host_count, RenderProcessHostCount()); // Create a new normal tab with a data URL. It should be in its own process. GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); // Create another data URL tab. With Site Isolation, this will require its // own process, but without Site Isolation, it can share the previous // process. GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; if (content::AreAllSitesIsolatedForTesting()) host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); if (content::AreAllSitesIsolatedForTesting()) EXPECT_NE(tab2->GetMainFrame()->GetProcess(), rph2); else EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2); // Create another WebUI tab. It should share the process with omnibox. // Note: intentionally create this tab after the normal tabs to exercise bug // 43448 where extension and WebUI tabs could get combined into normal // renderers. GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph1); // Create an extension tab. It should be in its own process. GURL extension_url("chrome-extension://" + extension->id()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), extension_url); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), extension_url); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); }
173,180
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 PluginInfoMessageFilter::Context::DecidePluginStatus( const GetPluginInfo_Params& params, const WebPluginInfo& plugin, PluginFinder* plugin_finder, ChromeViewHostMsg_GetPluginInfo_Status* status, std::string* group_identifier, string16* group_name) const { PluginInstaller* installer = plugin_finder->GetPluginInstaller(plugin); *group_name = installer->name(); *group_identifier = installer->identifier(); ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT; bool uses_default_content_setting = true; GetPluginContentSetting(plugin, params.top_origin_url, params.url, *group_identifier, &plugin_setting, &uses_default_content_setting); DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT); #if defined(ENABLE_PLUGIN_INSTALLATION) PluginInstaller::SecurityStatus plugin_status = installer->GetSecurityStatus(plugin); if (plugin_status == PluginInstaller::SECURITY_STATUS_OUT_OF_DATE && !allow_outdated_plugins_.GetValue()) { if (allow_outdated_plugins_.IsManaged()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed; } else { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked; } return; } if ((plugin_status == PluginInstaller::SECURITY_STATUS_REQUIRES_AUTHORIZATION || PluginService::GetInstance()->IsPluginUnstable(plugin.path)) && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } #endif if (plugin_setting == CONTENT_SETTING_ASK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay; else if (plugin_setting == CONTENT_SETTING_BLOCK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kBlocked; } Commit Message: Handle crashing Pepper plug-ins the same as crashing NPAPI plug-ins. BUG=151895 Review URL: https://chromiumcodereview.appspot.com/10956065 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158364 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void PluginInfoMessageFilter::Context::DecidePluginStatus( const GetPluginInfo_Params& params, const WebPluginInfo& plugin, PluginFinder* plugin_finder, ChromeViewHostMsg_GetPluginInfo_Status* status, std::string* group_identifier, string16* group_name) const { PluginInstaller* installer = plugin_finder->GetPluginInstaller(plugin); *group_name = installer->name(); *group_identifier = installer->identifier(); ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT; bool uses_default_content_setting = true; GetPluginContentSetting(plugin, params.top_origin_url, params.url, *group_identifier, &plugin_setting, &uses_default_content_setting); DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT); #if defined(ENABLE_PLUGIN_INSTALLATION) PluginInstaller::SecurityStatus plugin_status = installer->GetSecurityStatus(plugin); if (plugin_status == PluginInstaller::SECURITY_STATUS_OUT_OF_DATE && !allow_outdated_plugins_.GetValue()) { if (allow_outdated_plugins_.IsManaged()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed; } else { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked; } return; } if (plugin_status == PluginInstaller::SECURITY_STATUS_REQUIRES_AUTHORIZATION && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } // Check if the plug-in is crashing too much. if (PluginService::GetInstance()->IsPluginUnstable(plugin.path) && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } #endif if (plugin_setting == CONTENT_SETTING_ASK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay; else if (plugin_setting == CONTENT_SETTING_BLOCK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kBlocked; }
170,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: static int __poke_user_compat(struct task_struct *child, addr_t addr, addr_t data) { struct compat_user *dummy32 = NULL; __u32 tmp = (__u32) data; addr_t offset; if (addr < (addr_t) &dummy32->regs.acrs) { struct pt_regs *regs = task_pt_regs(child); /* * psw, gprs, acrs and orig_gpr2 are stored on the stack */ if (addr == (addr_t) &dummy32->regs.psw.mask) { __u32 mask = PSW32_MASK_USER; mask |= is_ri_task(child) ? PSW32_MASK_RI : 0; /* Build a 64 bit psw mask from 31 bit mask. */ if ((tmp & ~mask) != PSW32_USER_BITS) /* Invalid psw mask. */ return -EINVAL; regs->psw.mask = (regs->psw.mask & ~PSW_MASK_USER) | (regs->psw.mask & PSW_MASK_BA) | (__u64)(tmp & mask) << 32; } else if (addr == (addr_t) &dummy32->regs.psw.addr) { /* Build a 64 bit psw address from 31 bit address. */ regs->psw.addr = (__u64) tmp & PSW32_ADDR_INSN; /* Transfer 31 bit amode bit to psw mask. */ regs->psw.mask = (regs->psw.mask & ~PSW_MASK_BA) | (__u64)(tmp & PSW32_ADDR_AMODE); } else { /* gpr 0-15 */ *(__u32*)((addr_t) &regs->psw + addr*2 + 4) = tmp; } } else if (addr < (addr_t) (&dummy32->regs.orig_gpr2)) { /* * access registers are stored in the thread structure */ offset = addr - (addr_t) &dummy32->regs.acrs; *(__u32*)((addr_t) &child->thread.acrs + offset) = tmp; } else if (addr == (addr_t) (&dummy32->regs.orig_gpr2)) { /* * orig_gpr2 is stored on the kernel stack */ *(__u32*)((addr_t) &task_pt_regs(child)->orig_gpr2 + 4) = tmp; } else if (addr < (addr_t) &dummy32->regs.fp_regs) { /* * prevent writess of padding hole between * orig_gpr2 and fp_regs on s390. */ return 0; } else if (addr < (addr_t) (&dummy32->regs.fp_regs + 1)) { /* * floating point regs. are stored in the thread structure */ if (addr == (addr_t) &dummy32->regs.fp_regs.fpc && test_fp_ctl(tmp)) return -EINVAL; offset = addr - (addr_t) &dummy32->regs.fp_regs; *(__u32 *)((addr_t) &child->thread.fp_regs + offset) = tmp; } else if (addr < (addr_t) (&dummy32->regs.per_info + 1)) { /* * Handle access to the per_info structure. */ addr -= (addr_t) &dummy32->regs.per_info; __poke_user_per_compat(child, addr, data); } return 0; } Commit Message: s390/ptrace: fix PSW mask check The PSW mask check of the PTRACE_POKEUSR_AREA command is incorrect. The PSW_MASK_USER define contains the PSW_MASK_ASC bits, the ptrace interface accepts all combinations for the address-space-control bits. To protect the kernel space the PSW mask check in ptrace needs to reject the address-space-control bit combination for home space. Fixes CVE-2014-3534 Cc: stable@vger.kernel.org Signed-off-by: Martin Schwidefsky <schwidefsky@de.ibm.com> CWE ID: CWE-264
static int __poke_user_compat(struct task_struct *child, addr_t addr, addr_t data) { struct compat_user *dummy32 = NULL; __u32 tmp = (__u32) data; addr_t offset; if (addr < (addr_t) &dummy32->regs.acrs) { struct pt_regs *regs = task_pt_regs(child); /* * psw, gprs, acrs and orig_gpr2 are stored on the stack */ if (addr == (addr_t) &dummy32->regs.psw.mask) { __u32 mask = PSW32_MASK_USER; mask |= is_ri_task(child) ? PSW32_MASK_RI : 0; /* Build a 64 bit psw mask from 31 bit mask. */ if ((tmp ^ PSW32_USER_BITS) & ~mask) /* Invalid psw mask. */ return -EINVAL; if ((data & PSW32_MASK_ASC) == PSW32_ASC_HOME) /* Invalid address-space-control bits */ return -EINVAL; regs->psw.mask = (regs->psw.mask & ~PSW_MASK_USER) | (regs->psw.mask & PSW_MASK_BA) | (__u64)(tmp & mask) << 32; } else if (addr == (addr_t) &dummy32->regs.psw.addr) { /* Build a 64 bit psw address from 31 bit address. */ regs->psw.addr = (__u64) tmp & PSW32_ADDR_INSN; /* Transfer 31 bit amode bit to psw mask. */ regs->psw.mask = (regs->psw.mask & ~PSW_MASK_BA) | (__u64)(tmp & PSW32_ADDR_AMODE); } else { /* gpr 0-15 */ *(__u32*)((addr_t) &regs->psw + addr*2 + 4) = tmp; } } else if (addr < (addr_t) (&dummy32->regs.orig_gpr2)) { /* * access registers are stored in the thread structure */ offset = addr - (addr_t) &dummy32->regs.acrs; *(__u32*)((addr_t) &child->thread.acrs + offset) = tmp; } else if (addr == (addr_t) (&dummy32->regs.orig_gpr2)) { /* * orig_gpr2 is stored on the kernel stack */ *(__u32*)((addr_t) &task_pt_regs(child)->orig_gpr2 + 4) = tmp; } else if (addr < (addr_t) &dummy32->regs.fp_regs) { /* * prevent writess of padding hole between * orig_gpr2 and fp_regs on s390. */ return 0; } else if (addr < (addr_t) (&dummy32->regs.fp_regs + 1)) { /* * floating point regs. are stored in the thread structure */ if (addr == (addr_t) &dummy32->regs.fp_regs.fpc && test_fp_ctl(tmp)) return -EINVAL; offset = addr - (addr_t) &dummy32->regs.fp_regs; *(__u32 *)((addr_t) &child->thread.fp_regs + offset) = tmp; } else if (addr < (addr_t) (&dummy32->regs.per_info + 1)) { /* * Handle access to the per_info structure. */ addr -= (addr_t) &dummy32->regs.per_info; __poke_user_per_compat(child, addr, data); } return 0; }
166,363
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 enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { if (settings.verbose > 0) fprintf(stderr, "Couldn't realloc input buffer\n"); c->rbytes = 0; /* ignore what we read */ out_string(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = read(c->sfd, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; } Commit Message: Issue 102: Piping null to the server will crash it CWE ID: CWE-20
static enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; int num_allocs = 0; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { if (num_allocs == 4) { return gotdata; } ++num_allocs; char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { if (settings.verbose > 0) fprintf(stderr, "Couldn't realloc input buffer\n"); c->rbytes = 0; /* ignore what we read */ out_string(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = read(c->sfd, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; }
169,876
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 long Cluster::GetTimeCode() const { long long pos; long len; const long status = Load(pos, len); if (status < 0) //error return status; return m_timecode; } 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 long Cluster::GetTimeCode() const const long status = Load(pos, len); if (status < 0) // error return status; return m_timecode; } long long Cluster::GetTime() const { const long long tc = GetTimeCode(); if (tc < 0) return tc; const SegmentInfo* const pInfo = m_pSegment->GetInfo(); assert(pInfo); const long long scale = pInfo->GetTimeCodeScale(); assert(scale >= 1); const long long t = m_timecode * scale; return t; } long long Cluster::GetFirstTime() const { const BlockEntry* pEntry; const long status = GetFirst(pEntry); if (status < 0) // error return status; if (pEntry == NULL) // empty cluster return GetTime(); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); return pBlock->GetTime(this); } long long Cluster::GetLastTime() const { const BlockEntry* pEntry; const long status = GetLast(pEntry); if (status < 0) // error return status; if (pEntry == NULL) // empty cluster return GetTime(); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); return pBlock->GetTime(this); } long Cluster::CreateBlock(long long id, long long pos, // absolute pos of payload long long size, long long discard_padding) { assert((id == 0x20) || (id == 0x23)); // BlockGroup or SimpleBlock if (m_entries_count < 0) { // haven't parsed anything yet assert(m_entries == NULL); assert(m_entries_size == 0); m_entries_size = 1024; m_entries = new BlockEntry* [m_entries_size]; m_entries_count = 0; } else { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (m_entries_count >= m_entries_size) { const long entries_size = 2 * m_entries_size; BlockEntry** const entries = new BlockEntry* [entries_size]; assert(entries); BlockEntry** src = m_entries; BlockEntry** const src_end = src + m_entries_count; BlockEntry** dst = entries; while (src != src_end) *dst++ = *src++; delete[] m_entries; m_entries = entries; m_entries_size = entries_size; } } if (id == 0x20) // BlockGroup ID return CreateBlockGroup(pos, size, discard_padding); else // SimpleBlock ID return CreateSimpleBlock(pos, size); } long Cluster::CreateBlockGroup(long long start_offset, long long size, long long discard_padding) { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count >= 0); assert(m_entries_count < m_entries_size); IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = start_offset; const long long stop = start_offset + size; // For WebM files, there is a bias towards previous reference times //(in order to support alt-ref frames, which refer back to the previous // keyframe). Normally a 0 value is not possible, but here we tenatively // allow 0 as the value of a reference frame, with the interpretation // that this is a "previous" reference time. long long prev = 1; // nonce long long next = 0; // nonce long long duration = -1; // really, this is unsigned long long bpos = -1; long long bsize = -1; while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); // TODO assert((pos + len) <= stop); pos += len; // consume size if (id == 0x21) { // Block ID if (bpos < 0) { // Block ID bpos = pos; bsize = size; } } else if (id == 0x1B) { // Duration ID assert(size <= 8); duration = UnserializeUInt(pReader, pos, size); assert(duration >= 0); // TODO } else if (id == 0x7B) { // ReferenceBlock assert(size <= 8); const long size_ = static_cast<long>(size); long long time; long status = UnserializeInt(pReader, pos, size_, time); assert(status == 0); if (status != 0) return -1; if (time <= 0) // see note above prev = time; else // weird next = time; } pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); assert(bpos >= 0); assert(bsize >= 0); const long idx = m_entries_count; BlockEntry** const ppEntry = m_entries + idx; BlockEntry*& pEntry = *ppEntry; pEntry = new (std::nothrow) BlockGroup(this, idx, bpos, bsize, prev, next, duration, discard_padding); if (pEntry == NULL) return -1; // generic error BlockGroup* const p = static_cast<BlockGroup*>(pEntry); const long status = p->Parse(); if (status == 0) { // success ++m_entries_count; return 0; } delete pEntry; pEntry = 0; return status; } long Cluster::CreateSimpleBlock(long long st, long long sz) { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count >= 0); assert(m_entries_count < m_entries_size); const long idx = m_entries_count; BlockEntry** const ppEntry = m_entries + idx; BlockEntry*& pEntry = *ppEntry; pEntry = new (std::nothrow) SimpleBlock(this, idx, st, sz); if (pEntry == NULL) return -1; // generic error SimpleBlock* const p = static_cast<SimpleBlock*>(pEntry); const long status = p->Parse(); if (status == 0) { ++m_entries_count; return 0; } delete pEntry; pEntry = 0; return status; } long Cluster::GetFirst(const BlockEntry*& pFirst) const { if (m_entries_count <= 0) { long long pos; long len; const long status = Parse(pos, len);
174,365
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 bool ldm_frag_add (const u8 *data, int size, struct list_head *frags) { struct frag *f; struct list_head *item; int rec, num, group; BUG_ON (!data || !frags); if (size < 2 * VBLK_SIZE_HEAD) { ldm_error("Value of size is to small."); return false; } group = get_unaligned_be32(data + 0x08); rec = get_unaligned_be16(data + 0x0C); num = get_unaligned_be16(data + 0x0E); if ((num < 1) || (num > 4)) { ldm_error ("A VBLK claims to have %d parts.", num); return false; } if (rec >= num) { ldm_error("REC value (%d) exceeds NUM value (%d)", rec, num); return false; } list_for_each (item, frags) { f = list_entry (item, struct frag, list); if (f->group == group) goto found; } f = kmalloc (sizeof (*f) + size*num, GFP_KERNEL); if (!f) { ldm_crit ("Out of memory."); return false; } f->group = group; f->num = num; f->rec = rec; f->map = 0xFF << num; list_add_tail (&f->list, frags); found: if (f->map & (1 << rec)) { ldm_error ("Duplicate VBLK, part %d.", rec); f->map &= 0x7F; /* Mark the group as broken */ return false; } f->map |= (1 << rec); data += VBLK_SIZE_HEAD; size -= VBLK_SIZE_HEAD; memcpy (f->data+rec*(size-VBLK_SIZE_HEAD)+VBLK_SIZE_HEAD, data, size); return true; } Commit Message: Fix for buffer overflow in ldm_frag_add not sufficient As Ben Hutchings discovered [1], the patch for CVE-2011-1017 (buffer overflow in ldm_frag_add) is not sufficient. The original patch in commit c340b1d64000 ("fs/partitions/ldm.c: fix oops caused by corrupted partition table") does not consider that, for subsequent fragments, previously allocated memory is used. [1] http://lkml.org/lkml/2011/5/6/407 Reported-by: Ben Hutchings <ben@decadent.org.uk> Signed-off-by: Timo Warns <warns@pre-sense.de> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-119
static bool ldm_frag_add (const u8 *data, int size, struct list_head *frags) { struct frag *f; struct list_head *item; int rec, num, group; BUG_ON (!data || !frags); if (size < 2 * VBLK_SIZE_HEAD) { ldm_error("Value of size is to small."); return false; } group = get_unaligned_be32(data + 0x08); rec = get_unaligned_be16(data + 0x0C); num = get_unaligned_be16(data + 0x0E); if ((num < 1) || (num > 4)) { ldm_error ("A VBLK claims to have %d parts.", num); return false; } if (rec >= num) { ldm_error("REC value (%d) exceeds NUM value (%d)", rec, num); return false; } list_for_each (item, frags) { f = list_entry (item, struct frag, list); if (f->group == group) goto found; } f = kmalloc (sizeof (*f) + size*num, GFP_KERNEL); if (!f) { ldm_crit ("Out of memory."); return false; } f->group = group; f->num = num; f->rec = rec; f->map = 0xFF << num; list_add_tail (&f->list, frags); found: if (rec >= f->num) { ldm_error("REC value (%d) exceeds NUM value (%d)", rec, f->num); return false; } if (f->map & (1 << rec)) { ldm_error ("Duplicate VBLK, part %d.", rec); f->map &= 0x7F; /* Mark the group as broken */ return false; } f->map |= (1 << rec); data += VBLK_SIZE_HEAD; size -= VBLK_SIZE_HEAD; memcpy (f->data+rec*(size-VBLK_SIZE_HEAD)+VBLK_SIZE_HEAD, data, size); return true; }
165,872
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 ImageResource::IsAccessAllowed( const SecurityOrigin* security_origin, ImageResourceInfo::DoesCurrentFrameHaveSingleSecurityOrigin does_current_frame_has_single_security_origin) const { if (GetCORSStatus() == CORSStatus::kServiceWorkerOpaque) return false; if (does_current_frame_has_single_security_origin != ImageResourceInfo::kHasSingleSecurityOrigin) return false; if (IsSameOriginOrCORSSuccessful()) return true; return !security_origin->TaintsCanvas(GetResponse().Url()); } Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin Partial revert of https://chromium-review.googlesource.com/535694. Bug: 799477 Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3 Reviewed-on: https://chromium-review.googlesource.com/898427 Commit-Queue: Hiroshige Hayashizaki <hiroshige@chromium.org> Reviewed-by: Kouhei Ueno <kouhei@chromium.org> Reviewed-by: Yutaka Hirano <yhirano@chromium.org> Reviewed-by: Takeshi Yoshino <tyoshino@chromium.org> Cr-Commit-Position: refs/heads/master@{#535176} CWE ID: CWE-200
bool ImageResource::IsAccessAllowed( const SecurityOrigin* security_origin, ImageResourceInfo::DoesCurrentFrameHaveSingleSecurityOrigin does_current_frame_has_single_security_origin) const { if (GetResponse().WasFetchedViaServiceWorker()) return GetCORSStatus() != CORSStatus::kServiceWorkerOpaque; if (does_current_frame_has_single_security_origin != ImageResourceInfo::kHasSingleSecurityOrigin) return false; DCHECK(security_origin); if (PassesAccessControlCheck(*security_origin)) return true; return !security_origin->TaintsCanvas(GetResponse().Url()); }
172,888
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: setkey_principal3_2_svc(setkey3_arg *arg, struct svc_req *rqstp) { static generic_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_generic_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; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_SETKEY, arg->princ, NULL)) { ret.code = kadm5_setkey_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->keyblocks, arg->n_keys); } else { log_unauth("kadm5_setkey_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_SETKEY; } if(ret.code != KADM5_AUTH_SETKEY) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_setkey_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); 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
setkey_principal3_2_svc(setkey3_arg *arg, struct svc_req *rqstp) { static generic_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_generic_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; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_SETKEY, arg->princ, NULL)) { ret.code = kadm5_setkey_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->keyblocks, arg->n_keys); } else { log_unauth("kadm5_setkey_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_SETKEY; } if(ret.code != KADM5_AUTH_SETKEY) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_setkey_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,525
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t GraphicBuffer::unflatten( void const*& buffer, size_t& size, int const*& fds, size_t& count) { if (size < 8*sizeof(int)) return NO_MEMORY; int const* buf = static_cast<int const*>(buffer); if (buf[0] != 'GBFR') return BAD_TYPE; const size_t numFds = buf[8]; const size_t numInts = buf[9]; const size_t sizeNeeded = (10 + numInts) * sizeof(int); if (size < sizeNeeded) return NO_MEMORY; size_t fdCountNeeded = 0; if (count < fdCountNeeded) return NO_MEMORY; if (handle) { free_handle(); } if (numFds || numInts) { width = buf[1]; height = buf[2]; stride = buf[3]; format = buf[4]; usage = buf[5]; native_handle* h = native_handle_create(numFds, numInts); memcpy(h->data, fds, numFds*sizeof(int)); memcpy(h->data + numFds, &buf[10], numInts*sizeof(int)); handle = h; } else { width = height = stride = format = usage = 0; handle = NULL; } mId = static_cast<uint64_t>(buf[6]) << 32; mId |= static_cast<uint32_t>(buf[7]); mOwner = ownHandle; if (handle != 0) { status_t err = mBufferMapper.registerBuffer(handle); if (err != NO_ERROR) { width = height = stride = format = usage = 0; handle = NULL; ALOGE("unflatten: registerBuffer failed: %s (%d)", strerror(-err), err); return err; } } buffer = reinterpret_cast<void const*>(static_cast<int const*>(buffer) + sizeNeeded); size -= sizeNeeded; fds += numFds; count -= numFds; return NO_ERROR; } Commit Message: Fix for corruption when numFds or numInts is too large. Bug: 18076253 Change-Id: I4c5935440013fc755e1d123049290383f4659fb6 (cherry picked from commit dfd06b89a4b77fc75eb85a3c1c700da3621c0118) CWE ID: CWE-189
status_t GraphicBuffer::unflatten( void const*& buffer, size_t& size, int const*& fds, size_t& count) { if (size < 8*sizeof(int)) return NO_MEMORY; int const* buf = static_cast<int const*>(buffer); if (buf[0] != 'GBFR') return BAD_TYPE; const size_t numFds = buf[8]; const size_t numInts = buf[9]; const size_t maxNumber = UINT_MAX / sizeof(int); if (numFds >= maxNumber || numInts >= (maxNumber - 10)) { width = height = stride = format = usage = 0; handle = NULL; ALOGE("unflatten: numFds or numInts is too large: %d, %d", numFds, numInts); return BAD_VALUE; } const size_t sizeNeeded = (10 + numInts) * sizeof(int); if (size < sizeNeeded) return NO_MEMORY; size_t fdCountNeeded = numFds; if (count < fdCountNeeded) return NO_MEMORY; if (handle) { free_handle(); } if (numFds || numInts) { width = buf[1]; height = buf[2]; stride = buf[3]; format = buf[4]; usage = buf[5]; native_handle* h = native_handle_create(numFds, numInts); if (!h) { width = height = stride = format = usage = 0; handle = NULL; ALOGE("unflatten: native_handle_create failed"); return NO_MEMORY; } memcpy(h->data, fds, numFds*sizeof(int)); memcpy(h->data + numFds, &buf[10], numInts*sizeof(int)); handle = h; } else { width = height = stride = format = usage = 0; handle = NULL; } mId = static_cast<uint64_t>(buf[6]) << 32; mId |= static_cast<uint32_t>(buf[7]); mOwner = ownHandle; if (handle != 0) { status_t err = mBufferMapper.registerBuffer(handle); if (err != NO_ERROR) { width = height = stride = format = usage = 0; handle = NULL; ALOGE("unflatten: registerBuffer failed: %s (%d)", strerror(-err), err); return err; } } buffer = reinterpret_cast<void const*>(static_cast<int const*>(buffer) + sizeNeeded); size -= sizeNeeded; fds += numFds; count -= numFds; return NO_ERROR; }
173,374
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: P2PQuicStreamImpl* P2PQuicTransportImpl::CreateStreamInternal( quic::QuicStreamId id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(crypto_stream_); DCHECK(IsEncryptionEstablished()); DCHECK(!IsClosed()); return new P2PQuicStreamImpl(id, 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 <shampson@chromium.org> Reviewed-by: Henrik Boström <hbos@chromium.org> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
P2PQuicStreamImpl* P2PQuicTransportImpl::CreateStreamInternal( quic::QuicStreamId id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(crypto_stream_); DCHECK(IsEncryptionEstablished()); DCHECK(!IsClosed()); return new P2PQuicStreamImpl(id, this, stream_write_buffer_size_); }
172,265
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 DisconnectWindowLinux::Show(remoting::ChromotingHost* host, const std::string& username) { NOTIMPLEMENTED(); } Commit Message: Initial implementation of DisconnectWindow on Linux. BUG=None TEST=Manual Review URL: http://codereview.chromium.org/7089016 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88889 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void DisconnectWindowLinux::Show(remoting::ChromotingHost* host, const std::string& username) { host_ = host; CreateWindow(); gtk_label_set_text(GTK_LABEL(user_label_), username.c_str()); gtk_window_present(GTK_WINDOW(disconnect_window_)); }
170,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SocketStream::set_context(URLRequestContext* context) { const URLRequestContext* prev_context = context_.get(); if (context) { context_ = context->AsWeakPtr(); } else { context_.reset(); } if (prev_context != context) { if (prev_context && pac_request_) { prev_context->proxy_service()->CancelPacRequest(pac_request_); pac_request_ = NULL; } net_log_.EndEvent(NetLog::TYPE_REQUEST_ALIVE); net_log_ = BoundNetLog(); if (context) { net_log_ = BoundNetLog::Make( context->net_log(), NetLog::SOURCE_SOCKET_STREAM); net_log_.BeginEvent(NetLog::TYPE_REQUEST_ALIVE); } } } 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::set_context(URLRequestContext* context) { const URLRequestContext* prev_context = context_; context_ = context; if (prev_context != context) { if (prev_context && pac_request_) { prev_context->proxy_service()->CancelPacRequest(pac_request_); pac_request_ = NULL; } net_log_.EndEvent(NetLog::TYPE_REQUEST_ALIVE); net_log_ = BoundNetLog(); if (context) { net_log_ = BoundNetLog::Make( context->net_log(), NetLog::SOURCE_SOCKET_STREAM); net_log_.BeginEvent(NetLog::TYPE_REQUEST_ALIVE); } } }
171,257
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WT_InterpolateMono (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_I32 *pMixBuffer; const EAS_I8 *pLoopEnd; const EAS_I8 *pCurrentPhaseInt; EAS_I32 numSamples; EAS_I32 gain; EAS_I32 gainIncrement; EAS_I32 currentPhaseFrac; EAS_I32 phaseInc; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 tmp2; EAS_I8 *pLoopStart; numSamples = pWTIntFrame->numSamples; pMixBuffer = pWTIntFrame->pMixBuffer; /* calculate gain increment */ gainIncrement = (pWTIntFrame->gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS); if (gainIncrement < 0) gainIncrement++; gain = pWTIntFrame->prevGain << 16; pCurrentPhaseInt = pWTVoice->pPhaseAccum; currentPhaseFrac = pWTVoice->phaseFrac; phaseInc = pWTIntFrame->phaseIncrement; pLoopStart = pWTVoice->pLoopStart; pLoopEnd = pWTVoice->pLoopEnd + 1; InterpolationLoop: tmp0 = (EAS_I32)(pCurrentPhaseInt - pLoopEnd); if (tmp0 >= 0) pCurrentPhaseInt = pLoopStart + tmp0; tmp0 = *pCurrentPhaseInt; tmp1 = *(pCurrentPhaseInt + 1); tmp2 = phaseInc + currentPhaseFrac; tmp1 = tmp1 - tmp0; tmp1 = tmp1 * currentPhaseFrac; tmp1 = tmp0 + (tmp1 >> NUM_EG1_FRAC_BITS); pCurrentPhaseInt += (tmp2 >> NUM_PHASE_FRAC_BITS); currentPhaseFrac = tmp2 & PHASE_FRAC_MASK; gain += gainIncrement; tmp2 = (gain >> SYNTH_UPDATE_PERIOD_IN_BITS); tmp0 = *pMixBuffer; tmp2 = tmp1 * tmp2; tmp2 = (tmp2 >> 9); tmp0 = tmp2 + tmp0; *pMixBuffer++ = tmp0; numSamples--; if (numSamples > 0) goto InterpolationLoop; pWTVoice->pPhaseAccum = pCurrentPhaseInt; pWTVoice->phaseFrac = currentPhaseFrac; /*lint -e{702} <avoid divide>*/ pWTVoice->gain = (EAS_I16)(gain >> SYNTH_UPDATE_PERIOD_IN_BITS); } Commit Message: Sonivox: sanity check numSamples. Bug: 26366256 Change-Id: I066888c25035ea4c60c88f316db4508dc4dab6bc CWE ID: CWE-119
void WT_InterpolateMono (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_I32 *pMixBuffer; const EAS_I8 *pLoopEnd; const EAS_I8 *pCurrentPhaseInt; EAS_I32 numSamples; EAS_I32 gain; EAS_I32 gainIncrement; EAS_I32 currentPhaseFrac; EAS_I32 phaseInc; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 tmp2; EAS_I8 *pLoopStart; numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); return; } pMixBuffer = pWTIntFrame->pMixBuffer; /* calculate gain increment */ gainIncrement = (pWTIntFrame->gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS); if (gainIncrement < 0) gainIncrement++; gain = pWTIntFrame->prevGain << 16; pCurrentPhaseInt = pWTVoice->pPhaseAccum; currentPhaseFrac = pWTVoice->phaseFrac; phaseInc = pWTIntFrame->phaseIncrement; pLoopStart = pWTVoice->pLoopStart; pLoopEnd = pWTVoice->pLoopEnd + 1; InterpolationLoop: tmp0 = (EAS_I32)(pCurrentPhaseInt - pLoopEnd); if (tmp0 >= 0) pCurrentPhaseInt = pLoopStart + tmp0; tmp0 = *pCurrentPhaseInt; tmp1 = *(pCurrentPhaseInt + 1); tmp2 = phaseInc + currentPhaseFrac; tmp1 = tmp1 - tmp0; tmp1 = tmp1 * currentPhaseFrac; tmp1 = tmp0 + (tmp1 >> NUM_EG1_FRAC_BITS); pCurrentPhaseInt += (tmp2 >> NUM_PHASE_FRAC_BITS); currentPhaseFrac = tmp2 & PHASE_FRAC_MASK; gain += gainIncrement; tmp2 = (gain >> SYNTH_UPDATE_PERIOD_IN_BITS); tmp0 = *pMixBuffer; tmp2 = tmp1 * tmp2; tmp2 = (tmp2 >> 9); tmp0 = tmp2 + tmp0; *pMixBuffer++ = tmp0; numSamples--; if (numSamples > 0) goto InterpolationLoop; pWTVoice->pPhaseAccum = pCurrentPhaseInt; pWTVoice->phaseFrac = currentPhaseFrac; /*lint -e{702} <avoid divide>*/ pWTVoice->gain = (EAS_I16)(gain >> SYNTH_UPDATE_PERIOD_IN_BITS); }
173,918
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: UWORD16 impeg2d_get_mb_addr_incr(stream_t *ps_stream) { UWORD16 u2_mb_addr_incr = 0; while (impeg2d_bit_stream_nxt(ps_stream,MB_ESCAPE_CODE_LEN) == MB_ESCAPE_CODE) { impeg2d_bit_stream_flush(ps_stream,MB_ESCAPE_CODE_LEN); u2_mb_addr_incr += 33; } u2_mb_addr_incr += impeg2d_dec_vld_symbol(ps_stream,gai2_impeg2d_mb_addr_incr,MB_ADDR_INCR_LEN) + MB_ADDR_INCR_OFFSET; return(u2_mb_addr_incr); } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
UWORD16 impeg2d_get_mb_addr_incr(stream_t *ps_stream) { UWORD16 u2_mb_addr_incr = 0; while (impeg2d_bit_stream_nxt(ps_stream,MB_ESCAPE_CODE_LEN) == MB_ESCAPE_CODE && ps_stream->u4_offset < ps_stream->u4_max_offset) { impeg2d_bit_stream_flush(ps_stream,MB_ESCAPE_CODE_LEN); u2_mb_addr_incr += 33; } u2_mb_addr_incr += impeg2d_dec_vld_symbol(ps_stream,gai2_impeg2d_mb_addr_incr,MB_ADDR_INCR_LEN) + MB_ADDR_INCR_OFFSET; return(u2_mb_addr_incr); }
173,952
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: init_remote_listener(int port, gboolean encrypted) { int rc; int *ssock = NULL; struct sockaddr_in saddr; int optval; static struct mainloop_fd_callbacks remote_listen_fd_callbacks = { .dispatch = cib_remote_listen, .destroy = remote_connection_destroy, }; if (port <= 0) { /* dont start it */ return 0; } if (encrypted) { #ifndef HAVE_GNUTLS_GNUTLS_H crm_warn("TLS support is not available"); return 0; #else crm_notice("Starting a tls listener on port %d.", port); gnutls_global_init(); /* gnutls_global_set_log_level (10); */ gnutls_global_set_log_function(debug_log); gnutls_dh_params_init(&dh_params); gnutls_dh_params_generate2(dh_params, DH_BITS); gnutls_anon_allocate_server_credentials(&anon_cred_s); gnutls_anon_set_server_dh_params(anon_cred_s, dh_params); #endif } else { crm_warn("Starting a plain_text listener on port %d.", port); } #ifndef HAVE_PAM crm_warn("PAM is _not_ enabled!"); #endif /* create server socket */ ssock = malloc(sizeof(int)); *ssock = socket(AF_INET, SOCK_STREAM, 0); if (*ssock == -1) { crm_perror(LOG_ERR, "Can not create server socket." ERROR_SUFFIX); free(ssock); return -1; } /* reuse address */ optval = 1; rc = setsockopt(*ssock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if(rc < 0) { crm_perror(LOG_INFO, "Couldn't allow the reuse of local addresses by our remote listener"); } /* bind server socket */ memset(&saddr, '\0', sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = INADDR_ANY; saddr.sin_port = htons(port); if (bind(*ssock, (struct sockaddr *)&saddr, sizeof(saddr)) == -1) { crm_perror(LOG_ERR, "Can not bind server socket." ERROR_SUFFIX); close(*ssock); free(ssock); return -2; } if (listen(*ssock, 10) == -1) { crm_perror(LOG_ERR, "Can not start listen." ERROR_SUFFIX); close(*ssock); free(ssock); return -3; } mainloop_add_fd("cib-remote", G_PRIORITY_DEFAULT, *ssock, ssock, &remote_listen_fd_callbacks); return *ssock; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
init_remote_listener(int port, gboolean encrypted) { int rc; int *ssock = NULL; struct sockaddr_in saddr; int optval; static struct mainloop_fd_callbacks remote_listen_fd_callbacks = { .dispatch = cib_remote_listen, .destroy = remote_connection_destroy, }; if (port <= 0) { /* dont start it */ return 0; } if (encrypted) { #ifndef HAVE_GNUTLS_GNUTLS_H crm_warn("TLS support is not available"); return 0; #else crm_notice("Starting a tls listener on port %d.", port); gnutls_global_init(); /* gnutls_global_set_log_level (10); */ gnutls_global_set_log_function(debug_log); gnutls_dh_params_init(&dh_params); gnutls_dh_params_generate2(dh_params, DH_BITS); gnutls_anon_allocate_server_credentials(&anon_cred_s); gnutls_anon_set_server_dh_params(anon_cred_s, dh_params); #endif } else { crm_warn("Starting a plain_text listener on port %d.", port); } #ifndef HAVE_PAM crm_warn("PAM is _not_ enabled!"); #endif /* create server socket */ ssock = malloc(sizeof(int)); *ssock = socket(AF_INET, SOCK_STREAM, 0); if (*ssock == -1) { crm_perror(LOG_ERR, "Can not create server socket." ERROR_SUFFIX); free(ssock); return -1; } /* reuse address */ optval = 1; rc = setsockopt(*ssock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if(rc < 0) { crm_perror(LOG_INFO, "Couldn't allow the reuse of local addresses by our remote listener"); } /* bind server socket */ memset(&saddr, '\0', sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = INADDR_ANY; saddr.sin_port = htons(port); if (bind(*ssock, (struct sockaddr *)&saddr, sizeof(saddr)) == -1) { crm_perror(LOG_ERR, "Can not bind server socket." ERROR_SUFFIX); close(*ssock); free(ssock); return -2; } if (listen(*ssock, 10) == -1) { crm_perror(LOG_ERR, "Can not start listen." ERROR_SUFFIX); close(*ssock); free(ssock); return -3; } mainloop_add_fd("cib-remote", G_PRIORITY_DEFAULT, *ssock, ssock, &remote_listen_fd_callbacks); return *ssock; }
166,150
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 ServiceWorkerContextCore::OnReportConsoleMessage( ServiceWorkerVersion* version, blink::mojom::ConsoleMessageSource source, blink::mojom::ConsoleMessageLevel message_level, const base::string16& message, int line_number, const GURL& source_url) { DCHECK_CURRENTLY_ON(BrowserThread::IO); const bool is_builtin_component = HasWebUIScheme(source_url); LogConsoleMessage(ConsoleMessageLevelToLogSeverity(message_level), message, line_number, is_builtin_component, wrapper_->is_incognito(), base::UTF8ToUTF16(source_url.spec())); observer_list_->Notify( FROM_HERE, &ServiceWorkerContextCoreObserver::OnReportConsoleMessage, version->version_id(), ConsoleMessage(source, message_level, message, line_number, source_url)); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <lowell@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
void ServiceWorkerContextCore::OnReportConsoleMessage( ServiceWorkerVersion* version, blink::mojom::ConsoleMessageSource source, blink::mojom::ConsoleMessageLevel message_level, const base::string16& message, int line_number, const GURL& source_url) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // RenderFrameHostImpl::DidAddMessageToConsole, which also asks the const bool is_builtin_component = HasWebUIScheme(source_url); LogConsoleMessage(ConsoleMessageLevelToLogSeverity(message_level), message, line_number, is_builtin_component, wrapper_->is_incognito(), base::UTF8ToUTF16(source_url.spec())); observer_list_->Notify( FROM_HERE, &ServiceWorkerContextCoreObserver::OnReportConsoleMessage, version->version_id(), ConsoleMessage(source, message_level, message, line_number, source_url)); }
172,487
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 SendAutomationJSONRequest(AutomationMessageSender* sender, const DictionaryValue& request_dict, DictionaryValue* reply_dict, std::string* error_msg) { std::string request, reply; base::JSONWriter::Write(&request_dict, false, &request); bool success = false; int timeout_ms = TestTimeouts::action_max_timeout_ms(); base::Time before_sending = base::Time::Now(); if (!SendAutomationJSONRequest( sender, request, timeout_ms, &reply, &success)) { int64 elapsed_ms = (base::Time::Now() - before_sending).InMilliseconds(); std::string command; request_dict.GetString("command", &command); if (elapsed_ms >= timeout_ms) { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Request may have timed out. " "Elapsed time was %" PRId64 " ms. Request timeout was %d ms. " "Request details: (%s).", command.c_str(), elapsed_ms, timeout_ms, request.c_str()); } else { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Elapsed time was %" PRId64 " ms. " "Request details: (%s).", command.c_str(), elapsed_ms, request.c_str()); } return false; } scoped_ptr<Value> value(base::JSONReader::Read(reply, true)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) { std::string command; request_dict.GetString("command", &command); LOG(ERROR) << "JSON request did not return dict: " << command << "\n"; return false; } DictionaryValue* dict = static_cast<DictionaryValue*>(value.get()); if (!success) { std::string command, error; request_dict.GetString("command", &command); dict->GetString("error", &error); *error_msg = base::StringPrintf( "Internal Chrome error during '%s': (%s). Request details: (%s).", command.c_str(), error.c_str(), request.c_str()); LOG(ERROR) << "JSON request failed: " << command << "\n" << " with error: " << error; return false; } reply_dict->MergeDictionary(dict); return true; } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool SendAutomationJSONRequest(AutomationMessageSender* sender, const DictionaryValue& request_dict, DictionaryValue* reply_dict, std::string* error_msg) { std::string request, reply; base::JSONWriter::Write(&request_dict, false, &request); std::string command; request_dict.GetString("command", &command); LOG(INFO) << "Sending '" << command << "' command."; base::Time before_sending = base::Time::Now(); bool success = false; if (!SendAutomationJSONRequestWithDefaultTimeout( sender, request, &reply, &success)) { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Elapsed time was %" PRId64 " ms. " "Request details: (%s).", command.c_str(), (base::Time::Now() - before_sending).InMilliseconds(), request.c_str()); return false; } scoped_ptr<Value> value(base::JSONReader::Read(reply, true)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) { LOG(ERROR) << "JSON request did not return dict: " << command << "\n"; return false; } DictionaryValue* dict = static_cast<DictionaryValue*>(value.get()); if (!success) { std::string error; dict->GetString("error", &error); *error_msg = base::StringPrintf( "Internal Chrome error during '%s': (%s). Request details: (%s).", command.c_str(), error.c_str(), request.c_str()); LOG(ERROR) << "JSON request failed: " << command << "\n" << " with error: " << error; return false; } reply_dict->MergeDictionary(dict); return true; }
170,451
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: xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata) { xmlChar buf[XML_PARSER_BIG_BUFFER_SIZE + 5]; int nbchar = 0; int cur, l; int count = 0; SHRINK; GROW; cur = CUR_CHAR(l); while ((cur != '<') && /* checked */ (cur != '&') && (IS_CHAR(cur))) /* test also done in xmlCurrentChar() */ { if ((cur == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (cdata) break; else { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); } } COPY_BUF(l,buf,nbchar,cur); if (nbchar >= XML_PARSER_BIG_BUFFER_SIZE) { buf[nbchar] = 0; /* * OK the segment is to be consumed as chars. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (areBlanks(ctxt, buf, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, nbchar); if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) && (*ctxt->space == -1)) *ctxt->space = -2; } } nbchar = 0; /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } count++; if (count > 50) { GROW; count = 0; } NEXTL(l); cur = CUR_CHAR(l); } if (nbchar != 0) { buf[nbchar] = 0; /* * OK the segment is to be consumed as chars. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (areBlanks(ctxt, buf, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, nbchar); if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) && (*ctxt->space == -1)) *ctxt->space = -2; } } } if ((cur != 0) && (!IS_CHAR(cur))) { /* Generate the error and skip the offending character */ xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "PCDATA invalid Char value %d\n", cur); NEXTL(l); } } 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
xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata) { xmlChar buf[XML_PARSER_BIG_BUFFER_SIZE + 5]; int nbchar = 0; int cur, l; int count = 0; SHRINK; GROW; cur = CUR_CHAR(l); while ((cur != '<') && /* checked */ (cur != '&') && (IS_CHAR(cur))) /* test also done in xmlCurrentChar() */ { if ((cur == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (cdata) break; else { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); } } COPY_BUF(l,buf,nbchar,cur); if (nbchar >= XML_PARSER_BIG_BUFFER_SIZE) { buf[nbchar] = 0; /* * OK the segment is to be consumed as chars. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (areBlanks(ctxt, buf, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, nbchar); if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) && (*ctxt->space == -1)) *ctxt->space = -2; } } nbchar = 0; /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } count++; if (count > 50) { GROW; count = 0; if (ctxt->instate == XML_PARSER_EOF) return; } NEXTL(l); cur = CUR_CHAR(l); } if (nbchar != 0) { buf[nbchar] = 0; /* * OK the segment is to be consumed as chars. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (areBlanks(ctxt, buf, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, nbchar); if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) && (*ctxt->space == -1)) *ctxt->space = -2; } } } if ((cur != 0) && (!IS_CHAR(cur))) { /* Generate the error and skip the offending character */ xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "PCDATA invalid Char value %d\n", cur); NEXTL(l); } }
171,275
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: nfs4_state_set_mode_locked(struct nfs4_state *state, mode_t mode) { if (state->state == mode) return; /* NB! List reordering - see the reclaim code for why. */ if ((mode & FMODE_WRITE) != (state->state & FMODE_WRITE)) { if (mode & FMODE_WRITE) list_move(&state->open_states, &state->owner->so_states); else list_move_tail(&state->open_states, &state->owner->so_states); } state->state = mode; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
nfs4_state_set_mode_locked(struct nfs4_state *state, mode_t mode) nfs4_state_set_mode_locked(struct nfs4_state *state, fmode_t fmode) { if (state->state == fmode) return; /* NB! List reordering - see the reclaim code for why. */ if ((fmode & FMODE_WRITE) != (state->state & FMODE_WRITE)) { if (fmode & FMODE_WRITE) list_move(&state->open_states, &state->owner->so_states); else list_move_tail(&state->open_states, &state->owner->so_states); } state->state = fmode; }
165,712
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_replace(struct net *net, const void __user *user, unsigned int len) { int ret, countersize; struct ebt_table_info *newinfo; struct ebt_replace tmp; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; if (len != sizeof(tmp) + tmp.entries_size) { BUGPRINT("Wrong len argument\n"); return -EINVAL; } if (tmp.entries_size == 0) { BUGPRINT("Entries_size never zero\n"); return -EINVAL; } /* overflow check */ if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) / NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter)) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter)) return -ENOMEM; countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids; newinfo = vmalloc(sizeof(*newinfo) + countersize); if (!newinfo) return -ENOMEM; if (countersize) memset(newinfo->counters, 0, countersize); newinfo->entries = vmalloc(tmp.entries_size); if (!newinfo->entries) { ret = -ENOMEM; goto free_newinfo; } if (copy_from_user( newinfo->entries, tmp.entries, tmp.entries_size) != 0) { BUGPRINT("Couldn't copy entries from userspace\n"); ret = -EFAULT; goto free_entries; } ret = do_replace_finish(net, &tmp, newinfo); if (ret == 0) return ret; free_entries: vfree(newinfo->entries); free_newinfo: vfree(newinfo); return ret; } Commit Message: bridge: netfilter: fix information leak Struct tmp is copied from userspace. It is not checked whether the "name" field is NULL terminated. This may lead to buffer overflow and passing contents of kernel stack as a module name to try_then_request_module() and, consequently, to modprobe commandline. It would be seen by all userspace processes. Signed-off-by: Vasiliy Kulikov <segoon@openwall.com> Signed-off-by: Patrick McHardy <kaber@trash.net> CWE ID: CWE-20
static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret, countersize; struct ebt_table_info *newinfo; struct ebt_replace tmp; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; if (len != sizeof(tmp) + tmp.entries_size) { BUGPRINT("Wrong len argument\n"); return -EINVAL; } if (tmp.entries_size == 0) { BUGPRINT("Entries_size never zero\n"); return -EINVAL; } /* overflow check */ if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) / NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter)) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter)) return -ENOMEM; tmp.name[sizeof(tmp.name) - 1] = 0; countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids; newinfo = vmalloc(sizeof(*newinfo) + countersize); if (!newinfo) return -ENOMEM; if (countersize) memset(newinfo->counters, 0, countersize); newinfo->entries = vmalloc(tmp.entries_size); if (!newinfo->entries) { ret = -ENOMEM; goto free_newinfo; } if (copy_from_user( newinfo->entries, tmp.entries, tmp.entries_size) != 0) { BUGPRINT("Couldn't copy entries from userspace\n"); ret = -EFAULT; goto free_entries; } ret = do_replace_finish(net, &tmp, newinfo); if (ret == 0) return ret; free_entries: vfree(newinfo->entries); free_newinfo: vfree(newinfo); return ret; }
165,896
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: unsigned long long Track::GetUid() const { return m_info.uid; } 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
unsigned long long Track::GetUid() const
174,378
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftVPXEncoder::setConfig( OMX_INDEXTYPE index, const OMX_PTR _params) { switch (index) { case OMX_IndexConfigVideoIntraVOPRefresh: { OMX_CONFIG_INTRAREFRESHVOPTYPE *params = (OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params; if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } mKeyFrameRequested = params->IntraRefreshVOP; return OMX_ErrorNone; } case OMX_IndexConfigVideoBitrate: { OMX_VIDEO_CONFIG_BITRATETYPE *params = (OMX_VIDEO_CONFIG_BITRATETYPE *)_params; if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } if (mBitrate != params->nEncodeBitrate) { mBitrate = params->nEncodeBitrate; mBitrateUpdated = true; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::setConfig(index, _params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftVPXEncoder::setConfig( OMX_INDEXTYPE index, const OMX_PTR _params) { switch (index) { case OMX_IndexConfigVideoIntraVOPRefresh: { OMX_CONFIG_INTRAREFRESHVOPTYPE *params = (OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params; if (!isValidOMXParam(params)) { return OMX_ErrorBadParameter; } if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } mKeyFrameRequested = params->IntraRefreshVOP; return OMX_ErrorNone; } case OMX_IndexConfigVideoBitrate: { OMX_VIDEO_CONFIG_BITRATETYPE *params = (OMX_VIDEO_CONFIG_BITRATETYPE *)_params; if (!isValidOMXParam(params)) { return OMX_ErrorBadParameter; } if (params->nPortIndex != kOutputPortIndex) { return OMX_ErrorBadPortIndex; } if (mBitrate != params->nEncodeBitrate) { mBitrate = params->nEncodeBitrate; mBitrateUpdated = true; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::setConfig(index, _params); } }
174,215
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: ResourceRequestBlockedReason BaseFetchContext::CanRequest( Resource::Type type, const ResourceRequest& resource_request, const KURL& url, const ResourceLoaderOptions& options, SecurityViolationReportingPolicy reporting_policy, FetchParameters::OriginRestriction origin_restriction, ResourceRequest::RedirectStatus redirect_status) const { ResourceRequestBlockedReason blocked_reason = CanRequestInternal(type, resource_request, url, options, reporting_policy, origin_restriction, redirect_status); if (blocked_reason != ResourceRequestBlockedReason::kNone && reporting_policy == SecurityViolationReportingPolicy::kReport) { DispatchDidBlockRequest(resource_request, options.initiator_info, blocked_reason); } return blocked_reason; } 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 <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
ResourceRequestBlockedReason BaseFetchContext::CanRequest( Resource::Type type, const ResourceRequest& resource_request, const KURL& url, const ResourceLoaderOptions& options, SecurityViolationReportingPolicy reporting_policy, FetchParameters::OriginRestriction origin_restriction, ResourceRequest::RedirectStatus redirect_status) const { ResourceRequestBlockedReason blocked_reason = CanRequestInternal(type, resource_request, url, options, reporting_policy, origin_restriction, redirect_status); if (blocked_reason != ResourceRequestBlockedReason::kNone && reporting_policy == SecurityViolationReportingPolicy::kReport) { DispatchDidBlockRequest(resource_request, options.initiator_info, blocked_reason, type); } return blocked_reason; }
172,472
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 DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) { wchar_t argument[50]; for (int i = 0; argument_c[i]; ++i) argument[i] = argument_c[i]; int argument_len = lstrlen(argument); int command_line_len = lstrlen(command_line); while (command_line_len > argument_len) { wchar_t first_char = command_line[0]; wchar_t last_char = command_line[argument_len+1]; if ((first_char == L'-' || first_char == L'/') && (last_char == L' ' || last_char == 0 || last_char == L'=')) { command_line[argument_len+1] = 0; if (lstrcmpi(command_line+1, argument) == 0) { command_line[argument_len+1] = last_char; return true; } command_line[argument_len+1] = last_char; } ++command_line; --command_line_len; } return false; } Commit Message: Fix null-termination on string copy in debug-on-start code. BUG=73740 Review URL: http://codereview.chromium.org/6549019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75629 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) { wchar_t argument[50] = {}; for (int i = 0; argument_c[i]; ++i) argument[i] = argument_c[i]; int argument_len = lstrlen(argument); int command_line_len = lstrlen(command_line); while (command_line_len > argument_len) { wchar_t first_char = command_line[0]; wchar_t last_char = command_line[argument_len+1]; if ((first_char == L'-' || first_char == L'/') && (last_char == L' ' || last_char == 0 || last_char == L'=')) { command_line[argument_len+1] = 0; if (lstrcmpi(command_line+1, argument) == 0) { command_line[argument_len+1] = last_char; return true; } command_line[argument_len+1] = last_char; } ++command_line; --command_line_len; } return false; }
170,650
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 * calloc(size_t n, size_t lb) { if (lb && n > SIZE_MAX / lb) return NULL; # if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */ /* libpthread allocated some memory that is only pointed to by */ /* mmapped thread stacks. Make sure it's not collectable. */ { static GC_bool lib_bounds_set = FALSE; ptr_t caller = (ptr_t)__builtin_return_address(0); /* This test does not need to ensure memory visibility, since */ /* the bounds will be set when/if we create another thread. */ if (!EXPECT(lib_bounds_set, TRUE)) { GC_init_lib_bounds(); lib_bounds_set = TRUE; } if (((word)caller >= (word)GC_libpthread_start && (word)caller < (word)GC_libpthread_end) || ((word)caller >= (word)GC_libld_start && (word)caller < (word)GC_libld_end)) return GC_malloc_uncollectable(n*lb); /* The two ranges are actually usually adjacent, so there may */ /* be a way to speed this up. */ } # endif return((void *)REDIRECT_MALLOC(n*lb)); } Commit Message: Fix calloc-related code to prevent SIZE_MAX redefinition in sys headers * malloc.c: Include limits.h for SIZE_MAX. * malloc.c (SIZE_MAX, calloc): Define GC_SIZE_MAX instead of SIZE_MAX. CWE ID: CWE-189
void * calloc(size_t n, size_t lb) { if (lb && n > GC_SIZE_MAX / lb) return NULL; # if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */ /* libpthread allocated some memory that is only pointed to by */ /* mmapped thread stacks. Make sure it's not collectable. */ { static GC_bool lib_bounds_set = FALSE; ptr_t caller = (ptr_t)__builtin_return_address(0); /* This test does not need to ensure memory visibility, since */ /* the bounds will be set when/if we create another thread. */ if (!EXPECT(lib_bounds_set, TRUE)) { GC_init_lib_bounds(); lib_bounds_set = TRUE; } if (((word)caller >= (word)GC_libpthread_start && (word)caller < (word)GC_libpthread_end) || ((word)caller >= (word)GC_libld_start && (word)caller < (word)GC_libld_end)) return GC_malloc_uncollectable(n*lb); /* The two ranges are actually usually adjacent, so there may */ /* be a way to speed this up. */ } # endif return((void *)REDIRECT_MALLOC(n*lb)); }
169,880
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 PHP_GINIT_FUNCTION(libxml) { libxml_globals->stream_context = NULL; libxml_globals->error_buffer.c = NULL; libxml_globals->error_list = NULL; } Commit Message: CWE ID: CWE-200
static PHP_GINIT_FUNCTION(libxml) { libxml_globals->stream_context = NULL; libxml_globals->error_buffer.c = NULL; libxml_globals->error_list = NULL; libxml_globals->entity_loader_disabled = 0; }
164,744
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: DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) { if (base::win::GetVersion() < base::win::VERSION_VISTA) return ERROR_SUCCESS; const wchar_t* integrity_level_str = GetIntegrityLevelString(integrity_level); if (!integrity_level_str) { return ERROR_SUCCESS; } std::wstring ace_access = SDDL_NO_READ_UP; ace_access += SDDL_NO_WRITE_UP; DWORD error = SetObjectIntegrityLabel(::GetCurrentProcess(), SE_KERNEL_OBJECT, ace_access.c_str(), integrity_level_str); if (ERROR_SUCCESS != error) return error; HANDLE token_handle; if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT, &token_handle)) return ::GetLastError(); base::win::ScopedHandle token(token_handle); return SetTokenIntegrityLevel(token.Get(), integrity_level); } Commit Message: Prevent sandboxed processes from opening each other TBR=brettw BUG=117627 BUG=119150 TEST=sbox_validation_tests Review URL: https://chromiumcodereview.appspot.com/9716027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) { if (base::win::GetVersion() < base::win::VERSION_VISTA) return ERROR_SUCCESS; // We don't check for an invalid level here because we'll just let it // fail on the SetTokenIntegrityLevel call later on. if (integrity_level == INTEGRITY_LEVEL_LAST) { return ERROR_SUCCESS; } HANDLE token_handle; if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT, &token_handle)) return ::GetLastError(); base::win::ScopedHandle token(token_handle); return SetTokenIntegrityLevel(token.Get(), integrity_level); }
170,914
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 CoordinatorImpl::RegisterClientProcess( mojom::ClientProcessPtr client_process_ptr, mojom::ProcessType process_type) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); mojom::ClientProcess* client_process = client_process_ptr.get(); client_process_ptr.set_connection_error_handler( base::BindOnce(&CoordinatorImpl::UnregisterClientProcess, base::Unretained(this), client_process)); auto identity = GetClientIdentityForCurrentRequest(); auto client_info = std::make_unique<ClientInfo>( std::move(identity), std::move(client_process_ptr), process_type); auto iterator_and_inserted = clients_.emplace(client_process, std::move(client_info)); DCHECK(iterator_and_inserted.second); } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <hjd@chromium.org> Commit-Queue: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416
void CoordinatorImpl::RegisterClientProcess( mojom::ClientProcessPtr client_process_ptr, mojom::ProcessType process_type) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); mojom::ClientProcess* client_process = client_process_ptr.get(); client_process_ptr.set_connection_error_handler( base::BindOnce(&CoordinatorImpl::UnregisterClientProcess, weak_ptr_factory_.GetWeakPtr(), client_process)); auto identity = GetClientIdentityForCurrentRequest(); auto client_info = std::make_unique<ClientInfo>( std::move(identity), std::move(client_process_ptr), process_type); auto iterator_and_inserted = clients_.emplace(client_process, std::move(client_info)); DCHECK(iterator_and_inserted.second); }
173,215
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_t esp_reg_read(ESPState *s, uint32_t saddr) { uint32_t old_val; trace_esp_mem_readb(saddr, s->rregs[saddr]); switch (saddr) { case ESP_FIFO: if (s->ti_size > 0) { s->ti_size--; if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) { /* Data out. */ qemu_log_mask(LOG_UNIMP, "esp: PIO data read not implemented\n"); s->rregs[ESP_FIFO] = 0; } else { s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++]; } esp_raise_irq(s); } if (s->ti_size == 0) { s->ti_rptr = 0; s->ti_wptr = 0; } s->ti_wptr = 0; } break; case ESP_RINTR: /* Clear sequence step, interrupt register and all status bits except TC */ old_val = s->rregs[ESP_RINTR]; s->rregs[ESP_RINTR] = 0; s->rregs[ESP_RSTAT] &= ~STAT_TC; s->rregs[ESP_RSEQ] = SEQ_CD; esp_lower_irq(s); return old_val; case ESP_TCHI: /* Return the unique id if the value has never been written */ if (!s->tchi_written) { return s->chip_id; } default: break; } Commit Message: CWE ID: CWE-20
uint64_t esp_reg_read(ESPState *s, uint32_t saddr) { uint32_t old_val; trace_esp_mem_readb(saddr, s->rregs[saddr]); switch (saddr) { case ESP_FIFO: if ((s->rregs[ESP_RSTAT] & STAT_PIO_MASK) == 0) { /* Data out. */ qemu_log_mask(LOG_UNIMP, "esp: PIO data read not implemented\n"); s->rregs[ESP_FIFO] = 0; esp_raise_irq(s); } else if (s->ti_rptr < s->ti_wptr) { s->ti_size--; s->rregs[ESP_FIFO] = s->ti_buf[s->ti_rptr++]; esp_raise_irq(s); } if (s->ti_rptr == s->ti_wptr) { s->ti_rptr = 0; s->ti_wptr = 0; } s->ti_wptr = 0; } break; case ESP_RINTR: /* Clear sequence step, interrupt register and all status bits except TC */ old_val = s->rregs[ESP_RINTR]; s->rregs[ESP_RINTR] = 0; s->rregs[ESP_RSTAT] &= ~STAT_TC; s->rregs[ESP_RSEQ] = SEQ_CD; esp_lower_irq(s); return old_val; case ESP_TCHI: /* Return the unique id if the value has never been written */ if (!s->tchi_written) { return s->chip_id; } default: break; }
165,012
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { Mutex::Autolock _l(mLock); ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); if (mState == DESTROYED || mEffectInterface == NULL) { return NO_INIT; } if (mStatus != NO_ERROR) { return mStatus; } status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData); if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { uint32_t size = (replySize == NULL) ? 0 : *replySize; for (size_t i = 1; i < mHandles.size(); i++) { EffectHandle *h = mHandles[i]; if (h != NULL && !h->destroyed_l()) { h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); } } } return status; } Commit Message: Check effect command reply size in AudioFlinger Bug: 29251553 Change-Id: I1bcc1281f1f0542bb645f6358ce31631f2a8ffbf CWE ID: CWE-20
status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { Mutex::Autolock _l(mLock); ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); if (mState == DESTROYED || mEffectInterface == NULL) { return NO_INIT; } if (mStatus != NO_ERROR) { return mStatus; } if (cmdCode == EFFECT_CMD_GET_PARAM && (*replySize < sizeof(effect_param_t) || ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) { android_errorWriteLog(0x534e4554, "29251553"); return -EINVAL; } status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData); if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { uint32_t size = (replySize == NULL) ? 0 : *replySize; for (size_t i = 1; i < mHandles.size(); i++) { EffectHandle *h = mHandles[i]; if (h != NULL && !h->destroyed_l()) { h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); } } } return status; }
173,518
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(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } }
167,046
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: SubprocessMetricsProviderTest() : thread_bundle_(content::TestBrowserThreadBundle::DEFAULT) { base::PersistentHistogramAllocator::GetCreateHistogramResultHistogram(); provider_.MergeHistogramDeltas(); test_recorder_ = base::StatisticsRecorder::CreateTemporaryForTesting(); base::GlobalHistogramAllocator::CreateWithLocalMemory(TEST_MEMORY_SIZE, 0, ""); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <bcwhite@chromium.org> Reviewed-by: Alexei Svitkine <asvitkine@chromium.org> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
SubprocessMetricsProviderTest() : thread_bundle_(content::TestBrowserThreadBundle::DEFAULT) { provider_.MergeHistogramDeltas(); test_recorder_ = base::StatisticsRecorder::CreateTemporaryForTesting(); base::GlobalHistogramAllocator::CreateWithLocalMemory(TEST_MEMORY_SIZE, 0, ""); }
172,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) { struct lib_t *libs; int i; if (!bin->nlibs) return NULL; if (!(libs = calloc ((bin->nlibs + 1), sizeof(struct lib_t)))) return NULL; for (i = 0; i < bin->nlibs; i++) { strncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH); libs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\0'; libs[i].last = 0; } libs[i].last = 1; return libs; } Commit Message: Fix null deref and uaf in mach0 parser CWE ID: CWE-416
struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) { struct lib_t *libs; int i; if (!bin->nlibs) { return NULL; } if (!(libs = calloc ((bin->nlibs + 1), sizeof(struct lib_t)))) { return NULL; } for (i = 0; i < bin->nlibs; i++) { strncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH); libs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\0'; libs[i].last = 0; } libs[i].last = 1; return libs; }
168,234
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_default_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) UNUSED(bit_depth) this->next = *that; *that = this; return 1; } 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_default_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) UNUSED(bit_depth) this->next = *that; *that = this; return 1; }
173,620
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; } Commit Message: Prevent sandboxed processes from opening each other TBR=brettw BUG=117627 BUG=119150 TEST=sbox_validation_tests Review URL: https://chromiumcodereview.appspot.com/9716027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) { sandbox::ResultCode result; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Event"); if (result != sandbox::SBOX_ALL_OK) return false; policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0); sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED; if (base::win::GetVersion() > base::win::VERSION_XP) { initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS; } policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN); // Prevents the renderers from manipulating low-integrity processes. policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED); bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAltWinstation); if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) { DLOG(WARNING) << "Failed to apply desktop security to the renderer"; } AddGenericDllEvictionPolicy(policy); return true; }
170,912
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: size_t NormalPage::objectPayloadSizeForTesting() { size_t objectPayloadSize = 0; Address headerAddress = payload(); markAsSwept(); ASSERT(headerAddress != payloadEnd()); do { HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(headerAddress); if (!header->isFree()) { ASSERT(header->checkHeader()); objectPayloadSize += header->payloadSize(); } ASSERT(header->size() < blinkPagePayloadSize()); headerAddress += header->size(); ASSERT(headerAddress <= payloadEnd()); } while (headerAddress < payloadEnd()); return objectPayloadSize; } 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
size_t NormalPage::objectPayloadSizeForTesting() { size_t objectPayloadSize = 0; Address headerAddress = payload(); markAsSwept(); ASSERT(headerAddress != payloadEnd()); do { HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(headerAddress); if (!header->isFree()) { header->checkHeader(); objectPayloadSize += header->payloadSize(); } ASSERT(header->size() < blinkPagePayloadSize()); headerAddress += header->size(); ASSERT(headerAddress <= payloadEnd()); } while (headerAddress < payloadEnd()); return objectPayloadSize; }
172,713
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 tls_get_message_header(SSL *s, int *mt) { /* s->init_num < SSL3_HM_HEADER_LENGTH */ int skip_message, i, recvd_type, al; unsigned char *p; unsigned long l; p = (unsigned char *)s->init_buf->data; do { while (s->init_num < SSL3_HM_HEADER_LENGTH) { i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type, &p[s->init_num], SSL3_HM_HEADER_LENGTH - s->init_num, 0); if (i <= 0) { s->rwstate = SSL_READING; return 0; } if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) { /* * A ChangeCipherSpec must be a single byte and may not occur * in the middle of a handshake message. */ if (s->init_num != 0 || i != 1 || p[0] != SSL3_MT_CCS) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_BAD_CHANGE_CIPHER_SPEC); goto f_err; } s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC; s->init_num = i - 1; s->s3->tmp.message_size = i; return 1; } else if (recvd_type != SSL3_RT_HANDSHAKE) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY); goto f_err; } s->init_num += i; } skip_message = 0; if (!s->server) if (p[0] == SSL3_MT_HELLO_REQUEST) /* * The server may always send 'Hello Request' messages -- * we are doing a handshake anyway now, so ignore them if * their format is correct. Does not count for 'Finished' * MAC. */ if (p[1] == 0 && p[2] == 0 && p[3] == 0) { s->init_num = 0; skip_message = 1; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, SSL3_HM_HEADER_LENGTH, s, s->msg_callback_arg); } } while (skip_message); /* s->init_num == SSL3_HM_HEADER_LENGTH */ *mt = *p; s->s3->tmp.message_type = *(p++); if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) { /* * Only happens with SSLv3+ in an SSLv2 backward compatible * ClientHello * * Total message size is the remaining record bytes to read * plus the SSL3_HM_HEADER_LENGTH bytes that we already read */ l = RECORD_LAYER_get_rrec_length(&s->rlayer) + SSL3_HM_HEADER_LENGTH; if (l && !BUF_MEM_grow_clean(s->init_buf, (int)l)) { SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, ERR_R_BUF_LIB); goto err; } s->s3->tmp.message_size = l; s->init_msg = s->init_buf->data; } s->s3->tmp.message_size = l; s->init_msg = s->init_buf->data; s->init_num = SSL3_HM_HEADER_LENGTH; } else { SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE); goto f_err; } Commit Message: CWE ID: CWE-400
int tls_get_message_header(SSL *s, int *mt) { /* s->init_num < SSL3_HM_HEADER_LENGTH */ int skip_message, i, recvd_type, al; unsigned char *p; unsigned long l; p = (unsigned char *)s->init_buf->data; do { while (s->init_num < SSL3_HM_HEADER_LENGTH) { i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &recvd_type, &p[s->init_num], SSL3_HM_HEADER_LENGTH - s->init_num, 0); if (i <= 0) { s->rwstate = SSL_READING; return 0; } if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) { /* * A ChangeCipherSpec must be a single byte and may not occur * in the middle of a handshake message. */ if (s->init_num != 0 || i != 1 || p[0] != SSL3_MT_CCS) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_BAD_CHANGE_CIPHER_SPEC); goto f_err; } s->s3->tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC; s->init_num = i - 1; s->s3->tmp.message_size = i; return 1; } else if (recvd_type != SSL3_RT_HANDSHAKE) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_CCS_RECEIVED_EARLY); goto f_err; } s->init_num += i; } skip_message = 0; if (!s->server) if (p[0] == SSL3_MT_HELLO_REQUEST) /* * The server may always send 'Hello Request' messages -- * we are doing a handshake anyway now, so ignore them if * their format is correct. Does not count for 'Finished' * MAC. */ if (p[1] == 0 && p[2] == 0 && p[3] == 0) { s->init_num = 0; skip_message = 1; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, SSL3_HM_HEADER_LENGTH, s, s->msg_callback_arg); } } while (skip_message); /* s->init_num == SSL3_HM_HEADER_LENGTH */ *mt = *p; s->s3->tmp.message_type = *(p++); if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) { /* * Only happens with SSLv3+ in an SSLv2 backward compatible * ClientHello * * Total message size is the remaining record bytes to read * plus the SSL3_HM_HEADER_LENGTH bytes that we already read */ l = RECORD_LAYER_get_rrec_length(&s->rlayer) + SSL3_HM_HEADER_LENGTH; s->s3->tmp.message_size = l; s->init_msg = s->init_buf->data; } s->s3->tmp.message_size = l; s->init_msg = s->init_buf->data; s->init_num = SSL3_HM_HEADER_LENGTH; } else { SSLerr(SSL_F_TLS_GET_MESSAGE_HEADER, SSL_R_EXCESSIVE_MESSAGE_SIZE); goto f_err; }
164,963
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 int rtecp_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_file_t **file_out_copy, *file; int r; assert(card && card->ctx && in_path); switch (in_path->type) { case SC_PATH_TYPE_DF_NAME: case SC_PATH_TYPE_FROM_CURRENT: case SC_PATH_TYPE_PARENT: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } assert(iso_ops && iso_ops->select_file); file_out_copy = file_out; r = iso_ops->select_file(card, in_path, file_out_copy); if (r || file_out_copy == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); assert(file_out_copy); file = *file_out_copy; assert(file); if (file->sec_attr && file->sec_attr_len == SC_RTECP_SEC_ATTR_SIZE) set_acl_from_sec_attr(card, file); else r = SC_ERROR_UNKNOWN_DATA_RECEIVED; if (r) sc_file_free(file); else { assert(file_out); *file_out = file; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
static int rtecp_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_file_t **file_out_copy, *file; int r; assert(card && card->ctx && in_path); switch (in_path->type) { case SC_PATH_TYPE_DF_NAME: case SC_PATH_TYPE_FROM_CURRENT: case SC_PATH_TYPE_PARENT: SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED); } assert(iso_ops && iso_ops->select_file); file_out_copy = file_out; r = iso_ops->select_file(card, in_path, file_out_copy); if (r || file_out_copy == NULL) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); assert(file_out_copy); file = *file_out_copy; assert(file); if (file->sec_attr && file->sec_attr_len == SC_RTECP_SEC_ATTR_SIZE) set_acl_from_sec_attr(card, file); else r = SC_ERROR_UNKNOWN_DATA_RECEIVED; if (r && !file_out) sc_file_free(file); else { assert(file_out); *file_out = file; } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); }
169,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: content::WebUIDataSource* CreateOobeUIDataSource( const base::DictionaryValue& localized_strings, const std::string& display_type) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOobeHost); source->AddLocalizedStrings(localized_strings); source->SetJsonPath(kStringsJSPath); if (display_type == OobeUI::kOobeDisplay) { source->SetDefaultResource(IDR_OOBE_HTML); source->AddResourcePath(kOobeJSPath, IDR_OOBE_JS); source->AddResourcePath(kCustomElementsHTMLPath, IDR_CUSTOM_ELEMENTS_OOBE_HTML); source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_OOBE_JS); } else { source->SetDefaultResource(IDR_LOGIN_HTML); source->AddResourcePath(kLoginJSPath, IDR_LOGIN_JS); source->AddResourcePath(kCustomElementsHTMLPath, IDR_CUSTOM_ELEMENTS_LOGIN_HTML); source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_LOGIN_JS); } source->AddResourcePath(kPolymerConfigJSPath, IDR_POLYMER_CONFIG_JS); source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS); source->OverrideContentSecurityPolicyFrameSrc( base::StringPrintf( "frame-src chrome://terms/ %s/;", extensions::kGaiaAuthExtensionOrigin)); source->OverrideContentSecurityPolicyObjectSrc("object-src *;"); bool is_webview_signin_enabled = StartupUtils::IsWebviewSigninEnabled(); source->AddResourcePath("gaia_auth_host.js", is_webview_signin_enabled ? IDR_GAIA_AUTH_AUTHENTICATOR_JS : IDR_GAIA_AUTH_HOST_JS); source->AddResourcePath(kEnrollmentHTMLPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_HTML : IDR_OOBE_ENROLLMENT_HTML); source->AddResourcePath(kEnrollmentCSSPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_CSS : IDR_OOBE_ENROLLMENT_CSS); source->AddResourcePath(kEnrollmentJSPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_JS : IDR_OOBE_ENROLLMENT_JS); if (display_type == OobeUI::kOobeDisplay) { source->AddResourcePath("Roboto-Thin.ttf", IDR_FONT_ROBOTO_THIN); source->AddResourcePath("Roboto-Light.ttf", IDR_FONT_ROBOTO_LIGHT); source->AddResourcePath("Roboto-Regular.ttf", IDR_FONT_ROBOTO_REGULAR); source->AddResourcePath("Roboto-Medium.ttf", IDR_FONT_ROBOTO_MEDIUM); source->AddResourcePath("Roboto-Bold.ttf", IDR_FONT_ROBOTO_BOLD); } return source; } Commit Message: One polymer_config.js to rule them all. R=michaelpg@chromium.org,fukino@chromium.org,mfoltz@chromium.org BUG=425626 Review URL: https://codereview.chromium.org/1224783005 Cr-Commit-Position: refs/heads/master@{#337882} CWE ID: CWE-399
content::WebUIDataSource* CreateOobeUIDataSource( const base::DictionaryValue& localized_strings, const std::string& display_type) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOobeHost); source->AddLocalizedStrings(localized_strings); source->SetJsonPath(kStringsJSPath); if (display_type == OobeUI::kOobeDisplay) { source->SetDefaultResource(IDR_OOBE_HTML); source->AddResourcePath(kOobeJSPath, IDR_OOBE_JS); source->AddResourcePath(kCustomElementsHTMLPath, IDR_CUSTOM_ELEMENTS_OOBE_HTML); source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_OOBE_JS); } else { source->SetDefaultResource(IDR_LOGIN_HTML); source->AddResourcePath(kLoginJSPath, IDR_LOGIN_JS); source->AddResourcePath(kCustomElementsHTMLPath, IDR_CUSTOM_ELEMENTS_LOGIN_HTML); source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_LOGIN_JS); } source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS); source->OverrideContentSecurityPolicyFrameSrc( base::StringPrintf( "frame-src chrome://terms/ %s/;", extensions::kGaiaAuthExtensionOrigin)); source->OverrideContentSecurityPolicyObjectSrc("object-src *;"); bool is_webview_signin_enabled = StartupUtils::IsWebviewSigninEnabled(); source->AddResourcePath("gaia_auth_host.js", is_webview_signin_enabled ? IDR_GAIA_AUTH_AUTHENTICATOR_JS : IDR_GAIA_AUTH_HOST_JS); source->AddResourcePath(kEnrollmentHTMLPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_HTML : IDR_OOBE_ENROLLMENT_HTML); source->AddResourcePath(kEnrollmentCSSPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_CSS : IDR_OOBE_ENROLLMENT_CSS); source->AddResourcePath(kEnrollmentJSPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_JS : IDR_OOBE_ENROLLMENT_JS); if (display_type == OobeUI::kOobeDisplay) { source->AddResourcePath("Roboto-Thin.ttf", IDR_FONT_ROBOTO_THIN); source->AddResourcePath("Roboto-Light.ttf", IDR_FONT_ROBOTO_LIGHT); source->AddResourcePath("Roboto-Regular.ttf", IDR_FONT_ROBOTO_REGULAR); source->AddResourcePath("Roboto-Medium.ttf", IDR_FONT_ROBOTO_MEDIUM); source->AddResourcePath("Roboto-Bold.ttf", IDR_FONT_ROBOTO_BOLD); } return source; }
171,707