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: static int nlmsg_populate_mdb_fill(struct sk_buff *skb, struct net_device *dev, struct br_mdb_entry *entry, u32 pid, u32 seq, int type, unsigned int flags) { struct nlmsghdr *nlh; struct br_port_msg *bpm; struct nlattr *nest, *nest2; nlh = nlmsg_put(skb, pid, seq, type, sizeof(*bpm), NLM_F_MULTI); if (!nlh) return -EMSGSIZE; bpm = nlmsg_data(nlh); bpm->family = AF_BRIDGE; bpm->ifindex = dev->ifindex; nest = nla_nest_start(skb, MDBA_MDB); if (nest == NULL) goto cancel; nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY); if (nest2 == NULL) goto end; if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(*entry), entry)) goto end; nla_nest_end(skb, nest2); nla_nest_end(skb, nest); return nlmsg_end(skb, nlh); end: nla_nest_end(skb, nest); cancel: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } Commit Message: bridge: fix mdb info leaks The bridging code discloses heap and stack bytes via the RTM_GETMDB netlink interface and via the notify messages send to group RTNLGRP_MDB afer a successful add/del. Fix both cases by initializing all unset members/padding bytes with memset(0). Cc: Stephen Hemminger <stephen@networkplumber.org> Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
static int nlmsg_populate_mdb_fill(struct sk_buff *skb, struct net_device *dev, struct br_mdb_entry *entry, u32 pid, u32 seq, int type, unsigned int flags) { struct nlmsghdr *nlh; struct br_port_msg *bpm; struct nlattr *nest, *nest2; nlh = nlmsg_put(skb, pid, seq, type, sizeof(*bpm), NLM_F_MULTI); if (!nlh) return -EMSGSIZE; bpm = nlmsg_data(nlh); memset(bpm, 0, sizeof(*bpm)); bpm->family = AF_BRIDGE; bpm->ifindex = dev->ifindex; nest = nla_nest_start(skb, MDBA_MDB); if (nest == NULL) goto cancel; nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY); if (nest2 == NULL) goto end; if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(*entry), entry)) goto end; nla_nest_end(skb, nest2); nla_nest_end(skb, nest); return nlmsg_end(skb, nlh); end: nla_nest_end(skb, nest); cancel: nlmsg_cancel(skb, nlh); return -EMSGSIZE; }
166,055
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SoftAACEncoder::~SoftAACEncoder() { delete[] mInputFrame; mInputFrame = NULL; if (mEncoderHandle) { CHECK_EQ(VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle)); mEncoderHandle = NULL; } delete mApiHandle; mApiHandle = NULL; delete mMemOperator; mMemOperator = NULL; } Commit Message: codecs: handle onReset() for a few encoders Test: Run PoC binaries Bug: 34749392 Bug: 34705519 Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd CWE ID:
SoftAACEncoder::~SoftAACEncoder() { onReset(); if (mEncoderHandle) { CHECK_EQ(VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle)); mEncoderHandle = NULL; } delete mApiHandle; mApiHandle = NULL; delete mMemOperator; mMemOperator = NULL; }
174,008
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n"); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n"); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; } Commit Message: avcodec/mpeg4videodec: Check idx in mpeg4_decode_studio_block() Fixes: Out of array access Fixes: 13500/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_MPEG4_fuzzer-5769760178962432 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg Reviewed-by: Kieran Kunhya <kierank@obe.tv> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-125
static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n) { Mpeg4DecContext *ctx = s->avctx->priv_data; int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0, additional_code_len, sign, mismatch; VLC *cur_vlc = &ctx->studio_intra_tab[0]; uint8_t *const scantable = s->intra_scantable.permutated; const uint16_t *quant_matrix; uint32_t flc; const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6)); const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1); mismatch = 1; memset(block, 0, 64 * sizeof(int32_t)); if (n < 4) { cc = 0; dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->intra_matrix; } else { cc = (n & 1) + 1; if (ctx->rgb) dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2); else dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2); quant_matrix = s->chroma_intra_matrix; } if (dct_dc_size < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n"); return AVERROR_INVALIDDATA; } else if (dct_dc_size == 0) { dct_diff = 0; } else { dct_diff = get_xbits(&s->gb, dct_dc_size); if (dct_dc_size > 8) { if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8")) return AVERROR_INVALIDDATA; } } s->last_dc[cc] += dct_diff; if (s->mpeg_quant) block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision); else block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision); /* TODO: support mpeg_quant for AC coefficients */ block[0] = av_clip(block[0], min, max); mismatch ^= block[0]; /* AC Coefficients */ while (1) { group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2); if (group < 0) { av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n"); return AVERROR_INVALIDDATA; } additional_code_len = ac_state_tab[group][0]; cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]]; if (group == 0) { /* End of Block */ break; } else if (group >= 1 && group <= 6) { /* Zero run length (Table B.47) */ run = 1 << additional_code_len; if (additional_code_len) run += get_bits(&s->gb, additional_code_len); idx += run; continue; } else if (group >= 7 && group <= 12) { /* Zero run length and +/-1 level (Table B.48) */ code = get_bits(&s->gb, additional_code_len); sign = code & 1; code >>= 1; run = (1 << (additional_code_len - 1)) + code; idx += run; if (idx > 63) return AVERROR_INVALIDDATA; j = scantable[idx++]; block[j] = sign ? 1 : -1; } else if (group >= 13 && group <= 20) { /* Level value (Table B.49) */ if (idx > 63) return AVERROR_INVALIDDATA; j = scantable[idx++]; block[j] = get_xbits(&s->gb, additional_code_len); } else if (group == 21) { /* Escape */ if (idx > 63) return AVERROR_INVALIDDATA; j = scantable[idx++]; additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4; flc = get_bits(&s->gb, additional_code_len); if (flc >> (additional_code_len-1)) block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1); else block[j] = flc; } block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32; block[j] = av_clip(block[j], min, max); mismatch ^= block[j]; } block[63] ^= mismatch & 1; return 0; }
169,705
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(locale_get_primary_language ) { get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_get_primary_language ) PHP_FUNCTION(locale_get_primary_language ) { get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); }
167,184
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BlockEntry::Kind BlockGroup::GetKind() const { return kBlockGroup; } 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
BlockEntry::Kind BlockGroup::GetKind() const
174,333
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParsePEReference(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr entity = NULL; xmlParserInputPtr input; if (RAW != '%') return; NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParsePEReference: no name\n"); return; } if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); return; } NEXT; /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Request the entity from SAX */ if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must * precede any reference to it... */ xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } } else { /* * Internal checking in case the entity quest barfed */ if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) { xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "Internal: %%%s; is not a parameter entity\n", name, NULL); } else if (ctxt->input->free != deallocblankswrapper) { input = xmlNewBlanksWrapperInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; } else { /* * TODO !!! * handle the extra spaces added before and after * c.f. http://www.w3.org/TR/REC-xml#as-PE */ input = xmlNewEntityInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing * right here */ ctxt->instate = XML_PARSER_EOF; return; } } } } ctxt->hasPErefs = 1; } 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
xmlParsePEReference(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr entity = NULL; xmlParserInputPtr input; if (RAW != '%') return; NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParsePEReference: no name\n"); return; } if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); return; } NEXT; /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Request the entity from SAX */ if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (ctxt->instate == XML_PARSER_EOF) return; if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must * precede any reference to it... */ xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } } else { /* * Internal checking in case the entity quest barfed */ if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) { xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "Internal: %%%s; is not a parameter entity\n", name, NULL); } else if (ctxt->input->free != deallocblankswrapper) { input = xmlNewBlanksWrapperInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; } else { /* * TODO !!! * handle the extra spaces added before and after * c.f. http://www.w3.org/TR/REC-xml#as-PE */ input = xmlNewEntityInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing * right here */ ctxt->instate = XML_PARSER_EOF; return; } } } } ctxt->hasPErefs = 1; }
171,299
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WillDispatchTabUpdatedEvent(WebContents* contents, Profile* profile, const Extension* extension, ListValue* event_args) { DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue( contents, extension); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
static void WillDispatchTabUpdatedEvent(WebContents* contents, static void WillDispatchTabUpdatedEvent( WebContents* contents, const DictionaryValue* changed_properties, Profile* profile, const Extension* extension, ListValue* event_args) { // Overwrite the second argument with the appropriate properties dictionary, // depending on extension permissions. DictionaryValue* properties_value = changed_properties->DeepCopy(); ExtensionTabUtil::ScrubTabValueForExtension(contents, extension, properties_value); event_args->Set(1, properties_value); // Overwrite the third arg with our tab value as seen by this extension. DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue( contents, extension); }
171,453
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len, compat_ulong_t, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode, compat_ulong_t, flags) { long err = 0; unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; nodemask_t bm; nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { err = compat_get_bitmap(nodes_addr(bm), nmask, nr_bits); nm = compat_alloc_user_space(alloc_size); err |= copy_to_user(nm, nodes_addr(bm), alloc_size); } if (err) return -EFAULT; return sys_mbind(start, len, mode, nm, nr_bits+1, flags); } Commit Message: mm/mempolicy.c: fix error handling in set_mempolicy and mbind. In the case that compat_get_bitmap fails we do not want to copy the bitmap to the user as it will contain uninitialized stack data and leak sensitive data. Signed-off-by: Chris Salls <salls@cs.ucsb.edu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-388
COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len, compat_ulong_t, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode, compat_ulong_t, flags) { unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; nodemask_t bm; nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { if (compat_get_bitmap(nodes_addr(bm), nmask, nr_bits)) return -EFAULT; nm = compat_alloc_user_space(alloc_size); if (copy_to_user(nm, nodes_addr(bm), alloc_size)) return -EFAULT; } return sys_mbind(start, len, mode, nm, nr_bits+1, flags); }
168,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TestAppendTabsToTabStrip(bool focus_tab_strip) { LifecycleUnit* first_lifecycle_unit = nullptr; LifecycleUnit* second_lifecycle_unit = nullptr; CreateTwoTabs(focus_tab_strip, &first_lifecycle_unit, &second_lifecycle_unit); const base::TimeTicks first_tab_last_focused_time = first_lifecycle_unit->GetLastFocusedTime(); const base::TimeTicks second_tab_last_focused_time = second_lifecycle_unit->GetLastFocusedTime(); task_runner_->FastForwardBy(kShortDelay); LifecycleUnit* third_lifecycle_unit = nullptr; EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)) .WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) { third_lifecycle_unit = lifecycle_unit; if (focus_tab_strip) { EXPECT_EQ(first_tab_last_focused_time, first_lifecycle_unit->GetLastFocusedTime()); EXPECT_TRUE(IsFocused(second_lifecycle_unit)); } else { EXPECT_EQ(first_tab_last_focused_time, first_lifecycle_unit->GetLastFocusedTime()); EXPECT_EQ(second_tab_last_focused_time, second_lifecycle_unit->GetLastFocusedTime()); } EXPECT_EQ(NowTicks(), third_lifecycle_unit->GetLastFocusedTime()); })); std::unique_ptr<content::WebContents> third_web_contents = CreateAndNavigateWebContents(); content::WebContents* raw_third_web_contents = third_web_contents.get(); tab_strip_model_->AppendWebContents(std::move(third_web_contents), false); testing::Mock::VerifyAndClear(&source_observer_); EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_third_web_contents)); CloseTabsAndExpectNotifications( tab_strip_model_.get(), {first_lifecycle_unit, second_lifecycle_unit, third_lifecycle_unit}); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void TestAppendTabsToTabStrip(bool focus_tab_strip) { LifecycleUnit* first_lifecycle_unit = nullptr; LifecycleUnit* second_lifecycle_unit = nullptr; CreateTwoTabs(focus_tab_strip, &first_lifecycle_unit, &second_lifecycle_unit); const base::TimeTicks first_tab_last_focused_time = first_lifecycle_unit->GetLastFocusedTime(); const base::TimeTicks second_tab_last_focused_time = second_lifecycle_unit->GetLastFocusedTime(); task_runner_->FastForwardBy(kShortDelay); LifecycleUnit* third_lifecycle_unit = nullptr; EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(::testing::_)) .WillOnce(::testing::Invoke([&](LifecycleUnit* lifecycle_unit) { third_lifecycle_unit = lifecycle_unit; if (focus_tab_strip) { EXPECT_EQ(first_tab_last_focused_time, first_lifecycle_unit->GetLastFocusedTime()); EXPECT_TRUE(IsFocused(second_lifecycle_unit)); } else { EXPECT_EQ(first_tab_last_focused_time, first_lifecycle_unit->GetLastFocusedTime()); EXPECT_EQ(second_tab_last_focused_time, second_lifecycle_unit->GetLastFocusedTime()); } EXPECT_EQ(NowTicks(), third_lifecycle_unit->GetLastFocusedTime()); })); std::unique_ptr<content::WebContents> third_web_contents = CreateAndNavigateWebContents(); content::WebContents* raw_third_web_contents = third_web_contents.get(); tab_strip_model_->AppendWebContents(std::move(third_web_contents), false); ::testing::Mock::VerifyAndClear(&source_observer_); EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_third_web_contents)); CloseTabsAndExpectNotifications( tab_strip_model_.get(), {first_lifecycle_unit, second_lifecycle_unit, third_lifecycle_unit}); }
172,227
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: vips_malloc( VipsObject *object, size_t size ) { void *buf; buf = g_malloc( size ); if( object ) { g_signal_connect( object, "postclose", G_CALLBACK( vips_malloc_cb ), buf ); object->local_memory += size; } return( buf ); } Commit Message: zero memory on malloc to prevent write of uninit memory under some error conditions thanks Balint CWE ID: CWE-200
vips_malloc( VipsObject *object, size_t size ) { void *buf; buf = g_malloc0( size ); if( object ) { g_signal_connect( object, "postclose", G_CALLBACK( vips_malloc_cb ), buf ); object->local_memory += size; } return( buf ); }
169,739
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long mkvparser::UnserializeString( IMkvReader* pReader, long long pos, long long size_, char*& str) { delete[] str; str = NULL; if (size_ >= LONG_MAX) //we need (size+1) chars return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); str = new (std::nothrow) char[size+1]; if (str == NULL) return -1; unsigned char* const buf = reinterpret_cast<unsigned char*>(str); const long status = pReader->Read(pos, size, buf); if (status) { delete[] str; str = NULL; return status; } str[size] = '\0'; 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 mkvparser::UnserializeString( if (status) { delete[] str; str = NULL; return status; } str[size] = '\0'; return 0; // success }
174,449
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: smb_fdata(netdissect_options *ndo, const u_char *buf, const char *fmt, const u_char *maxbuf, int unicodestr) { static int depth = 0; char s[128]; char *p; while (*fmt) { switch (*fmt) { case '*': fmt++; while (buf < maxbuf) { const u_char *buf2; depth++; buf2 = smb_fdata(ndo, buf, fmt, maxbuf, unicodestr); depth--; if (buf2 == NULL) return(NULL); if (buf2 == buf) return(buf); buf = buf2; } return(buf); case '|': fmt++; if (buf >= maxbuf) return(buf); break; case '%': fmt++; buf = maxbuf; break; case '#': fmt++; return(buf); break; case '[': fmt++; if (buf >= maxbuf) return(buf); memset(s, 0, sizeof(s)); p = strchr(fmt, ']'); if ((size_t)(p - fmt + 1) > sizeof(s)) { /* overrun */ return(buf); } strncpy(s, fmt, p - fmt); s[p - fmt] = '\0'; fmt = p + 1; buf = smb_fdata1(ndo, buf, s, maxbuf, unicodestr); if (buf == NULL) return(NULL); break; default: ND_PRINT((ndo, "%c", *fmt)); fmt++; break; } } if (!depth && buf < maxbuf) { size_t len = PTR_DIFF(maxbuf, buf); ND_PRINT((ndo, "Data: (%lu bytes)\n", (unsigned long)len)); smb_print_data(ndo, buf, len); return(buf + len); } return(buf); } Commit Message: (for 4.9.3) CVE-2018-16452/SMB: prevent stack exhaustion Enforce a limit on how many times smb_fdata() can recurse. This fixes a stack exhaustion discovered by Include Security working under the Mozilla SOS program in 2018 by means of code audit. CWE ID: CWE-674
smb_fdata(netdissect_options *ndo, const u_char *buf, const char *fmt, const u_char *maxbuf, int unicodestr) { static int depth = 0; char s[128]; char *p; while (*fmt) { switch (*fmt) { case '*': fmt++; while (buf < maxbuf) { const u_char *buf2; depth++; /* Not sure how this relates with the protocol specification, * but in order to avoid stack exhaustion recurse at most that * many levels. */ if (depth == 10) ND_PRINT((ndo, "(too many nested levels, not recursing)")); else buf2 = smb_fdata(ndo, buf, fmt, maxbuf, unicodestr); depth--; if (buf2 == NULL) return(NULL); if (buf2 == buf) return(buf); buf = buf2; } return(buf); case '|': fmt++; if (buf >= maxbuf) return(buf); break; case '%': fmt++; buf = maxbuf; break; case '#': fmt++; return(buf); break; case '[': fmt++; if (buf >= maxbuf) return(buf); memset(s, 0, sizeof(s)); p = strchr(fmt, ']'); if ((size_t)(p - fmt + 1) > sizeof(s)) { /* overrun */ return(buf); } strncpy(s, fmt, p - fmt); s[p - fmt] = '\0'; fmt = p + 1; buf = smb_fdata1(ndo, buf, s, maxbuf, unicodestr); if (buf == NULL) return(NULL); break; default: ND_PRINT((ndo, "%c", *fmt)); fmt++; break; } } if (!depth && buf < maxbuf) { size_t len = PTR_DIFF(maxbuf, buf); ND_PRINT((ndo, "Data: (%lu bytes)\n", (unsigned long)len)); smb_print_data(ndo, buf, len); return(buf + len); } return(buf); }
169,814
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ContentEncoding::ContentCompression::~ContentCompression() { delete [] settings; } 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
ContentEncoding::ContentCompression::~ContentCompression() { delete[] settings; }
174,459
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) { WLog_DBG(TAG, "%s (Len: %"PRIu16" MaxLen: %"PRIu16" BufferOffset: %"PRIu32")", name, fields->Len, fields->MaxLen, fields->BufferOffset); if (fields->Len > 0) winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len); } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) static void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) { WLog_DBG(TAG, "%s (Len: %"PRIu16" MaxLen: %"PRIu16" BufferOffset: %"PRIu32")", name, fields->Len, fields->MaxLen, fields->BufferOffset); if (fields->Len > 0) winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len); }
169,274
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DefragMfIpv6Test(void) { int retval = 0; int ip_id = 9; Packet *p = NULL; DefragInit(); Packet *p1 = IPV6BuildTestPacket(ip_id, 2, 1, 'C', 8); Packet *p2 = IPV6BuildTestPacket(ip_id, 0, 1, 'A', 8); Packet *p3 = IPV6BuildTestPacket(ip_id, 1, 0, 'B', 8); if (p1 == NULL || p2 == NULL || p3 == NULL) { goto end; } p = Defrag(NULL, NULL, p1, NULL); if (p != NULL) { goto end; } p = Defrag(NULL, NULL, p2, NULL); if (p != NULL) { goto end; } /* This should return a packet as MF=0. */ p = Defrag(NULL, NULL, p3, NULL); if (p == NULL) { goto end; } /* For IPv6 the expected length is just the length of the payload * of 2 fragments, so 16. */ if (IPV6_GET_PLEN(p) != 16) { goto end; } retval = 1; end: if (p1 != NULL) { SCFree(p1); } if (p2 != NULL) { SCFree(p2); } if (p3 != NULL) { SCFree(p3); } if (p != NULL) { SCFree(p); } DefragDestroy(); return retval; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
static int DefragMfIpv6Test(void) { int retval = 0; int ip_id = 9; Packet *p = NULL; DefragInit(); Packet *p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 2, 1, 'C', 8); Packet *p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 0, 1, 'A', 8); Packet *p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 1, 0, 'B', 8); if (p1 == NULL || p2 == NULL || p3 == NULL) { goto end; } p = Defrag(NULL, NULL, p1, NULL); if (p != NULL) { goto end; } p = Defrag(NULL, NULL, p2, NULL); if (p != NULL) { goto end; } /* This should return a packet as MF=0. */ p = Defrag(NULL, NULL, p3, NULL); if (p == NULL) { goto end; } /* For IPv6 the expected length is just the length of the payload * of 2 fragments, so 16. */ if (IPV6_GET_PLEN(p) != 16) { goto end; } retval = 1; end: if (p1 != NULL) { SCFree(p1); } if (p2 != NULL) { SCFree(p2); } if (p3 != NULL) { SCFree(p3); } if (p != NULL) { SCFree(p); } DefragDestroy(); return retval; }
168,300
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 copyMultiCh8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i] << 8; } } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyMultiCh8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) static void copyMultiCh8(short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i] << 8; } } }
174,020
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_8byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x)
170,049
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nautilus_file_mark_desktop_file_trusted (GFile *file, GtkWindow *parent_window, gboolean interactive, NautilusOpCallback done_callback, gpointer done_callback_data) { GTask *task; MarkTrustedJob *job; job = op_job_new (MarkTrustedJob, parent_window); job->file = g_object_ref (file); job->interactive = interactive; job->done_callback = done_callback; job->done_callback_data = done_callback_data; task = g_task_new (NULL, NULL, mark_trusted_task_done, job); g_task_set_task_data (task, job, NULL); g_task_run_in_thread (task, mark_trusted_task_thread_func); g_object_unref (task); } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20
nautilus_file_mark_desktop_file_trusted (GFile *file, nautilus_file_mark_desktop_file_executable (GFile *file, GtkWindow *parent_window, gboolean interactive, NautilusOpCallback done_callback, gpointer done_callback_data) { GTask *task; MarkTrustedJob *job; job = op_job_new (MarkTrustedJob, parent_window); job->file = g_object_ref (file); job->interactive = interactive; job->done_callback = done_callback; job->done_callback_data = done_callback_data; task = g_task_new (NULL, NULL, mark_desktop_file_executable_task_done, job); g_task_set_task_data (task, job, NULL); g_task_run_in_thread (task, mark_desktop_file_executable_task_thread_func); g_object_unref (task); }
167,751
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct kioctx *ioctx_alloc(unsigned nr_events) { struct mm_struct *mm = current->mm; struct kioctx *ctx; int err = -ENOMEM; /* * We keep track of the number of available ringbuffer slots, to prevent * overflow (reqs_available), and we also use percpu counters for this. * * So since up to half the slots might be on other cpu's percpu counters * and unavailable, double nr_events so userspace sees what they * expected: additionally, we move req_batch slots to/from percpu * counters at a time, so make sure that isn't 0: */ nr_events = max(nr_events, num_possible_cpus() * 4); nr_events *= 2; /* Prevent overflows */ if ((nr_events > (0x10000000U / sizeof(struct io_event))) || (nr_events > (0x10000000U / sizeof(struct kiocb)))) { pr_debug("ENOMEM: nr_events too high\n"); return ERR_PTR(-EINVAL); } if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL)) return ERR_PTR(-EAGAIN); ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL); if (!ctx) return ERR_PTR(-ENOMEM); ctx->max_reqs = nr_events; if (percpu_ref_init(&ctx->users, free_ioctx_users)) goto err; if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs)) goto err; spin_lock_init(&ctx->ctx_lock); spin_lock_init(&ctx->completion_lock); mutex_init(&ctx->ring_lock); init_waitqueue_head(&ctx->wait); INIT_LIST_HEAD(&ctx->active_reqs); ctx->cpu = alloc_percpu(struct kioctx_cpu); if (!ctx->cpu) goto err; if (aio_setup_ring(ctx) < 0) goto err; atomic_set(&ctx->reqs_available, ctx->nr_events - 1); ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4); if (ctx->req_batch < 1) ctx->req_batch = 1; /* limit the number of system wide aios */ spin_lock(&aio_nr_lock); if (aio_nr + nr_events > (aio_max_nr * 2UL) || aio_nr + nr_events < aio_nr) { spin_unlock(&aio_nr_lock); err = -EAGAIN; goto err; } aio_nr += ctx->max_reqs; spin_unlock(&aio_nr_lock); percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */ err = ioctx_add_table(ctx, mm); if (err) goto err_cleanup; pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n", ctx, ctx->user_id, mm, ctx->nr_events); return ctx; err_cleanup: aio_nr_sub(ctx->max_reqs); err: aio_free_ring(ctx); free_percpu(ctx->cpu); free_percpu(ctx->reqs.pcpu_count); free_percpu(ctx->users.pcpu_count); kmem_cache_free(kioctx_cachep, ctx); pr_debug("error allocating ioctx %d\n", err); return ERR_PTR(err); } Commit Message: aio: prevent double free in ioctx_alloc ioctx_alloc() calls aio_setup_ring() to allocate a ring. If aio_setup_ring() fails to do so it would call aio_free_ring() before returning, but ioctx_alloc() would call aio_free_ring() again causing a double free of the ring. This is easily reproducible from userspace. Signed-off-by: Sasha Levin <sasha.levin@oracle.com> Signed-off-by: Benjamin LaHaise <bcrl@kvack.org> CWE ID: CWE-399
static struct kioctx *ioctx_alloc(unsigned nr_events) { struct mm_struct *mm = current->mm; struct kioctx *ctx; int err = -ENOMEM; /* * We keep track of the number of available ringbuffer slots, to prevent * overflow (reqs_available), and we also use percpu counters for this. * * So since up to half the slots might be on other cpu's percpu counters * and unavailable, double nr_events so userspace sees what they * expected: additionally, we move req_batch slots to/from percpu * counters at a time, so make sure that isn't 0: */ nr_events = max(nr_events, num_possible_cpus() * 4); nr_events *= 2; /* Prevent overflows */ if ((nr_events > (0x10000000U / sizeof(struct io_event))) || (nr_events > (0x10000000U / sizeof(struct kiocb)))) { pr_debug("ENOMEM: nr_events too high\n"); return ERR_PTR(-EINVAL); } if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL)) return ERR_PTR(-EAGAIN); ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL); if (!ctx) return ERR_PTR(-ENOMEM); ctx->max_reqs = nr_events; if (percpu_ref_init(&ctx->users, free_ioctx_users)) goto err; if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs)) goto err; spin_lock_init(&ctx->ctx_lock); spin_lock_init(&ctx->completion_lock); mutex_init(&ctx->ring_lock); init_waitqueue_head(&ctx->wait); INIT_LIST_HEAD(&ctx->active_reqs); ctx->cpu = alloc_percpu(struct kioctx_cpu); if (!ctx->cpu) goto err; if (aio_setup_ring(ctx) < 0) goto err; atomic_set(&ctx->reqs_available, ctx->nr_events - 1); ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4); if (ctx->req_batch < 1) ctx->req_batch = 1; /* limit the number of system wide aios */ spin_lock(&aio_nr_lock); if (aio_nr + nr_events > (aio_max_nr * 2UL) || aio_nr + nr_events < aio_nr) { spin_unlock(&aio_nr_lock); err = -EAGAIN; goto err; } aio_nr += ctx->max_reqs; spin_unlock(&aio_nr_lock); percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */ err = ioctx_add_table(ctx, mm); if (err) goto err_cleanup; pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n", ctx, ctx->user_id, mm, ctx->nr_events); return ctx; err_cleanup: aio_nr_sub(ctx->max_reqs); err: free_percpu(ctx->cpu); free_percpu(ctx->reqs.pcpu_count); free_percpu(ctx->users.pcpu_count); kmem_cache_free(kioctx_cachep, ctx); pr_debug("error allocating ioctx %d\n", err); return ERR_PTR(err); }
166,468
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite( BrowserContext* browser_context, const GURL& url) { SiteProcessMap* map = GetSiteProcessMapForBrowserContext(browser_context); std::string site = SiteInstance::GetSiteForURL(browser_context, url) .possibly_invalid_spec(); return map->FindProcess(site); } Commit Message: Check for appropriate bindings in process-per-site mode. BUG=174059 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/12188025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181386 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite( BrowserContext* browser_context, const GURL& url) { SiteProcessMap* map = GetSiteProcessMapForBrowserContext(browser_context); // See if we have an existing process with appropriate bindings for this site. // If not, the caller should create a new process and register it. std::string site = SiteInstance::GetSiteForURL(browser_context, url) .possibly_invalid_spec(); RenderProcessHost* host = map->FindProcess(site); if (host && !IsSuitableHost(host, browser_context, url)) { // The registered process does not have an appropriate set of bindings for // the url. Remove it from the map so we can register a better one. RecordAction(UserMetricsAction("BindingsMismatch_GetProcessHostPerSite")); map->RemoveProcess(host); host = NULL; } return host; }
171,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CreatePersistentHistogramAllocator() { GlobalHistogramAllocator::GetCreateHistogramResultHistogram(); GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "HistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); } 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
void CreatePersistentHistogramAllocator() { GlobalHistogramAllocator::CreateWithLocalMemory( kAllocatorMemorySize, 0, "HistogramAllocatorTest"); allocator_ = GlobalHistogramAllocator::Get()->memory_allocator(); }
172,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeContentRendererClient::RenderThreadStarted() { chrome_observer_.reset(new ChromeRenderProcessObserver()); extension_dispatcher_.reset(new ExtensionDispatcher()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); net_predictor_.reset(new RendererNetPredictor()); spellcheck_.reset(new SpellCheck()); visited_link_slave_.reset(new VisitedLinkSlave()); phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create()); RenderThread* thread = RenderThread::current(); thread->AddFilter(new DevToolsAgentFilter()); thread->AddObserver(chrome_observer_.get()); thread->AddObserver(extension_dispatcher_.get()); thread->AddObserver(histogram_snapshots_.get()); thread->AddObserver(phishing_classifier_.get()); thread->AddObserver(spellcheck_.get()); thread->AddObserver(visited_link_slave_.get()); thread->RegisterExtension(extensions_v8::ExternalExtension::Get()); thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get()); v8::Extension* search_extension = extensions_v8::SearchExtension::Get(); if (search_extension) thread->RegisterExtension(search_extension); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { thread->RegisterExtension(DomAutomationV8Extension::Get()); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableIPCFuzzing)) { thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer()); } WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme); WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme)); WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme); } Commit Message: Prevent navigation to chrome-devtools: and chrome-internal: schemas from http BUG=87815 Review URL: http://codereview.chromium.org/7275032 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91002 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void ChromeContentRendererClient::RenderThreadStarted() { chrome_observer_.reset(new ChromeRenderProcessObserver()); extension_dispatcher_.reset(new ExtensionDispatcher()); histogram_snapshots_.reset(new RendererHistogramSnapshots()); net_predictor_.reset(new RendererNetPredictor()); spellcheck_.reset(new SpellCheck()); visited_link_slave_.reset(new VisitedLinkSlave()); phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create()); RenderThread* thread = RenderThread::current(); thread->AddFilter(new DevToolsAgentFilter()); thread->AddObserver(chrome_observer_.get()); thread->AddObserver(extension_dispatcher_.get()); thread->AddObserver(histogram_snapshots_.get()); thread->AddObserver(phishing_classifier_.get()); thread->AddObserver(spellcheck_.get()); thread->AddObserver(visited_link_slave_.get()); thread->RegisterExtension(extensions_v8::ExternalExtension::Get()); thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get()); v8::Extension* search_extension = extensions_v8::SearchExtension::Get(); if (search_extension) thread->RegisterExtension(search_extension); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDomAutomationController)) { thread->RegisterExtension(DomAutomationV8Extension::Get()); } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableIPCFuzzing)) { thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer()); } // chrome:, chrome-devtools:, and chrome-internal: pages should not be // accessible by normal content, and should also be unable to script // anything but themselves (to help limit the damage that a corrupt // page could cause). WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme); WebString dev_tools_scheme(ASCIIToUTF16(chrome::kChromeDevToolsScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(dev_tools_scheme); WebString internal_scheme(ASCIIToUTF16(chrome::kChromeInternalScheme)); WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(internal_scheme); WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme)); WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme); }
170,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SendRequest() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!service_) return; bool is_extended_reporting = false; if (item_->GetBrowserContext()) { Profile* profile = Profile::FromBrowserContext(item_->GetBrowserContext()); is_extended_reporting = profile && profile->GetPrefs()->GetBoolean( prefs::kSafeBrowsingExtendedReportingEnabled); } ClientDownloadRequest request; if (is_extended_reporting) { request.mutable_population()->set_user_population( ChromeUserPopulation::EXTENDED_REPORTING); } else { request.mutable_population()->set_user_population( ChromeUserPopulation::SAFE_BROWSING); } request.set_url(SanitizeUrl(item_->GetUrlChain().back())); request.mutable_digests()->set_sha256(item_->GetHash()); request.set_length(item_->GetReceivedBytes()); for (size_t i = 0; i < item_->GetUrlChain().size(); ++i) { ClientDownloadRequest::Resource* resource = request.add_resources(); resource->set_url(SanitizeUrl(item_->GetUrlChain()[i])); if (i == item_->GetUrlChain().size() - 1) { resource->set_type(ClientDownloadRequest::DOWNLOAD_URL); resource->set_referrer(SanitizeUrl(item_->GetReferrerUrl())); DVLOG(2) << "dl url " << resource->url(); if (!item_->GetRemoteAddress().empty()) { resource->set_remote_ip(item_->GetRemoteAddress()); DVLOG(2) << " dl url remote addr: " << resource->remote_ip(); } DVLOG(2) << "dl referrer " << resource->referrer(); } else { DVLOG(2) << "dl redirect " << i << " " << resource->url(); resource->set_type(ClientDownloadRequest::DOWNLOAD_REDIRECT); } } for (size_t i = 0; i < tab_redirects_.size(); ++i) { ClientDownloadRequest::Resource* resource = request.add_resources(); DVLOG(2) << "tab redirect " << i << " " << tab_redirects_[i].spec(); resource->set_url(SanitizeUrl(tab_redirects_[i])); resource->set_type(ClientDownloadRequest::TAB_REDIRECT); } if (tab_url_.is_valid()) { ClientDownloadRequest::Resource* resource = request.add_resources(); resource->set_url(SanitizeUrl(tab_url_)); DVLOG(2) << "tab url " << resource->url(); resource->set_type(ClientDownloadRequest::TAB_URL); if (tab_referrer_url_.is_valid()) { resource->set_referrer(SanitizeUrl(tab_referrer_url_)); DVLOG(2) << "tab referrer " << resource->referrer(); } } request.set_user_initiated(item_->HasUserGesture()); request.set_file_basename( item_->GetTargetFilePath().BaseName().AsUTF8Unsafe()); request.set_download_type(type_); request.mutable_signature()->CopyFrom(signature_info_); if (image_headers_) request.set_allocated_image_headers(image_headers_.release()); if (zipped_executable_) request.mutable_archived_binary()->Swap(&archived_binary_); if (!request.SerializeToString(&client_download_request_data_)) { FinishRequest(UNKNOWN, REASON_INVALID_REQUEST_PROTO); return; } service_->client_download_request_callbacks_.Notify(item_, &request); DVLOG(2) << "Sending a request for URL: " << item_->GetUrlChain().back(); fetcher_ = net::URLFetcher::Create(0 /* ID used for testing */, GetDownloadRequestUrl(), net::URLFetcher::POST, this); fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE); fetcher_->SetAutomaticallyRetryOn5xx(false); // Don't retry on error. fetcher_->SetRequestContext(service_->request_context_getter_.get()); fetcher_->SetUploadData("application/octet-stream", client_download_request_data_); request_start_time_ = base::TimeTicks::Now(); UMA_HISTOGRAM_COUNTS("SBClientDownload.DownloadRequestPayloadSize", client_download_request_data_.size()); fetcher_->Start(); } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 R=isherman@chromium.org, kenrb@chromium.org, mattm@chromium.org, thestig@chromium.org Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} CWE ID:
void SendRequest() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!service_) return; bool is_extended_reporting = false; if (item_->GetBrowserContext()) { Profile* profile = Profile::FromBrowserContext(item_->GetBrowserContext()); is_extended_reporting = profile && profile->GetPrefs()->GetBoolean( prefs::kSafeBrowsingExtendedReportingEnabled); } ClientDownloadRequest request; if (is_extended_reporting) { request.mutable_population()->set_user_population( ChromeUserPopulation::EXTENDED_REPORTING); } else { request.mutable_population()->set_user_population( ChromeUserPopulation::SAFE_BROWSING); } request.set_url(SanitizeUrl(item_->GetUrlChain().back())); request.mutable_digests()->set_sha256(item_->GetHash()); request.set_length(item_->GetReceivedBytes()); for (size_t i = 0; i < item_->GetUrlChain().size(); ++i) { ClientDownloadRequest::Resource* resource = request.add_resources(); resource->set_url(SanitizeUrl(item_->GetUrlChain()[i])); if (i == item_->GetUrlChain().size() - 1) { resource->set_type(ClientDownloadRequest::DOWNLOAD_URL); resource->set_referrer(SanitizeUrl(item_->GetReferrerUrl())); DVLOG(2) << "dl url " << resource->url(); if (!item_->GetRemoteAddress().empty()) { resource->set_remote_ip(item_->GetRemoteAddress()); DVLOG(2) << " dl url remote addr: " << resource->remote_ip(); } DVLOG(2) << "dl referrer " << resource->referrer(); } else { DVLOG(2) << "dl redirect " << i << " " << resource->url(); resource->set_type(ClientDownloadRequest::DOWNLOAD_REDIRECT); } } for (size_t i = 0; i < tab_redirects_.size(); ++i) { ClientDownloadRequest::Resource* resource = request.add_resources(); DVLOG(2) << "tab redirect " << i << " " << tab_redirects_[i].spec(); resource->set_url(SanitizeUrl(tab_redirects_[i])); resource->set_type(ClientDownloadRequest::TAB_REDIRECT); } if (tab_url_.is_valid()) { ClientDownloadRequest::Resource* resource = request.add_resources(); resource->set_url(SanitizeUrl(tab_url_)); DVLOG(2) << "tab url " << resource->url(); resource->set_type(ClientDownloadRequest::TAB_URL); if (tab_referrer_url_.is_valid()) { resource->set_referrer(SanitizeUrl(tab_referrer_url_)); DVLOG(2) << "tab referrer " << resource->referrer(); } } request.set_user_initiated(item_->HasUserGesture()); request.set_file_basename( item_->GetTargetFilePath().BaseName().AsUTF8Unsafe()); request.set_download_type(type_); request.mutable_signature()->CopyFrom(signature_info_); if (image_headers_) request.set_allocated_image_headers(image_headers_.release()); if (archived_executable_) request.mutable_archived_binary()->Swap(&archived_binary_); if (!request.SerializeToString(&client_download_request_data_)) { FinishRequest(UNKNOWN, REASON_INVALID_REQUEST_PROTO); return; } service_->client_download_request_callbacks_.Notify(item_, &request); DVLOG(2) << "Sending a request for URL: " << item_->GetUrlChain().back(); DVLOG(2) << "Detected " << request.archived_binary().size() << " archived " << "binaries"; fetcher_ = net::URLFetcher::Create(0 /* ID used for testing */, GetDownloadRequestUrl(), net::URLFetcher::POST, this); fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE); fetcher_->SetAutomaticallyRetryOn5xx(false); // Don't retry on error. fetcher_->SetRequestContext(service_->request_context_getter_.get()); fetcher_->SetUploadData("application/octet-stream", client_download_request_data_); request_start_time_ = base::TimeTicks::Now(); UMA_HISTOGRAM_COUNTS("SBClientDownload.DownloadRequestPayloadSize", client_download_request_data_.size()); fetcher_->Start(); }
171,714
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NetworkHandler::DeleteCookies( const std::string& name, Maybe<std::string> url, Maybe<std::string> domain, Maybe<std::string> path, std::unique_ptr<DeleteCookiesCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } if (!url.isJust() && !domain.isJust()) { callback->sendFailure(Response::InvalidParams( "At least one of the url and domain needs to be specified")); } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &DeleteCookiesOnIO, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()), name, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""), base::BindOnce(&DeleteCookiesCallback::sendSuccess, std::move(callback)))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void NetworkHandler::DeleteCookies( const std::string& name, Maybe<std::string> url, Maybe<std::string> domain, Maybe<std::string> path, std::unique_ptr<DeleteCookiesCallback> callback) { if (!storage_partition_) { callback->sendFailure(Response::InternalError()); return; } if (!url.isJust() && !domain.isJust()) { callback->sendFailure(Response::InvalidParams( "At least one of the url and domain needs to be specified")); } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &DeleteCookiesOnIO, base::Unretained(storage_partition_->GetURLRequestContext()), name, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""), base::BindOnce(&DeleteCookiesCallback::sendSuccess, std::move(callback)))); }
172,755
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_args (MyObject *obj, guint32 x, const char *str, double trouble, double *d_ret, char **str_ret, GError **error) { *d_ret = trouble + (x * 2); *str_ret = g_ascii_strup (str, -1); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_many_args (MyObject *obj, guint32 x, const char *str, double trouble, double *d_ret, char **str_ret, GError **error)
165,110
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 x86newTokenType getToken(const char *str, size_t *begin, size_t *end) { while (begin && isspace ((ut8)str[*begin])) { ++(*begin); } if (!str[*begin]) { // null byte *end = *begin; return TT_EOF; } else if (isalpha ((ut8)str[*begin])) { // word token *end = *begin; while (end && isalnum ((ut8)str[*end])) { ++(*end); } return TT_WORD; } else if (isdigit ((ut8)str[*begin])) { // number token *end = *begin; while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex. ++(*end); } return TT_NUMBER; } else { // special character: [, ], +, *, ... *end = *begin + 1; return TT_SPECIAL; } } Commit Message: Fix #12239 - crash in the x86.nz assembler ##asm (#12252) CWE ID: CWE-125
static x86newTokenType getToken(const char *str, size_t *begin, size_t *end) { if (*begin > strlen (str)) { return TT_EOF; } while (begin && str[*begin] && isspace ((ut8)str[*begin])) { ++(*begin); } if (!str[*begin]) { // null byte *end = *begin; return TT_EOF; } if (isalpha ((ut8)str[*begin])) { // word token *end = *begin; while (end && str[*end] && isalnum ((ut8)str[*end])) { ++(*end); } return TT_WORD; } if (isdigit ((ut8)str[*begin])) { // number token *end = *begin; while (end && isalnum ((ut8)str[*end])) { // accept alphanumeric characters, because hex. ++(*end); } return TT_NUMBER; } else { // special character: [, ], +, *, ... *end = *begin + 1; return TT_SPECIAL; } }
168,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 XMLHttpRequest::networkError() { genericError(); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().errorEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().errorEvent)); internalAbort(); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void XMLHttpRequest::networkError() void XMLHttpRequest::dispatchEventAndLoadEnd(const AtomicString& type) { if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(type)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(type)); } void XMLHttpRequest::handleNetworkError() { m_exceptionCode = NetworkError; handleDidFailGeneric(); if (m_async) { changeState(DONE); dispatchEventAndLoadEnd(eventNames().errorEvent); } else { m_state = DONE; } internalAbort(); }
171,169
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cJSON_InitHooks(cJSON_Hooks* hooks) { if ( ! hooks ) { /* Reset hooks. */ cJSON_malloc = malloc; cJSON_free = free; return; } cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc; cJSON_free = (hooks->free_fn) ? hooks->free_fn : free; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
void cJSON_InitHooks(cJSON_Hooks* hooks) static char* cJSON_strdup(const char* str) {
167,290
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CameraClient::dump(int fd, const Vector<String16>& args) { const size_t SIZE = 256; char buffer[SIZE]; size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); len = (len > SIZE - 1) ? SIZE - 1 : len; write(fd, buffer, len); return mHardware->dump(fd, args); } Commit Message: Camera: Disallow dumping clients directly Camera service dumps should only be initiated through ICameraService::dump. Bug: 26265403 Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803 CWE ID: CWE-264
status_t CameraClient::dump(int fd, const Vector<String16>& args) { return BasicClient::dump(fd, args); } status_t CameraClient::dumpClient(int fd, const Vector<String16>& args) { const size_t SIZE = 256; char buffer[SIZE]; size_t len = snprintf(buffer, SIZE, "Client[%d] (%p) PID: %d\n", mCameraId, getRemoteCallback()->asBinder().get(), mClientPid); len = (len > SIZE - 1) ? SIZE - 1 : len; write(fd, buffer, len); return mHardware->dump(fd, args); }
173,938
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BrowserContext* OTRBrowserContextImpl::GetOriginalContext() const { return original_context_.get(); } Commit Message: CWE ID: CWE-20
BrowserContext* OTRBrowserContextImpl::GetOriginalContext() const { BrowserContext* OTRBrowserContextImpl::GetOriginalContext() { return original_context_; }
165,414
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mux_session_confirm(int id, int success, void *arg) { struct mux_session_confirm_ctx *cctx = arg; const char *display; Channel *c, *cc; int i; Buffer reply; if (cctx == NULL) fatal("%s: cctx == NULL", __func__); if ((c = channel_by_id(id)) == NULL) fatal("%s: no channel for id %d", __func__, id); if ((cc = channel_by_id(c->ctl_chan)) == NULL) fatal("%s: channel %d lacks control channel %d", __func__, id, c->ctl_chan); if (!success) { debug3("%s: sending failure reply", __func__); /* prepare reply */ buffer_init(&reply); buffer_put_int(&reply, MUX_S_FAILURE); buffer_put_int(&reply, cctx->rid); buffer_put_cstring(&reply, "Session open refused by peer"); goto done; } display = getenv("DISPLAY"); if (cctx->want_x_fwd && options.forward_x11 && display != NULL) { char *proto, *data; /* Get reasonable local authentication information. */ client_x11_get_proto(display, options.xauth_location, options.forward_x11_trusted, options.forward_x11_timeout, &proto, &data); /* Request forwarding with authentication spoofing. */ debug("Requesting X11 forwarding with authentication " "spoofing."); x11_request_forwarding_with_spoofing(id, display, proto, data, 1); client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN); /* XXX exit_on_forward_failure */ } if (cctx->want_agent_fwd && options.forward_agent) { packet_send(); } client_session2_setup(id, cctx->want_tty, cctx->want_subsys, cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env); debug3("%s: sending success reply", __func__); /* prepare reply */ buffer_init(&reply); buffer_put_int(&reply, MUX_S_SESSION_OPENED); buffer_put_int(&reply, cctx->rid); buffer_put_int(&reply, c->self); done: /* Send reply */ buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply)); buffer_free(&reply); if (cc->mux_pause <= 0) fatal("%s: mux_pause %d", __func__, cc->mux_pause); cc->mux_pause = 0; /* start processing messages again */ c->open_confirm_ctx = NULL; buffer_free(&cctx->cmd); free(cctx->term); if (cctx->env != NULL) { for (i = 0; cctx->env[i] != NULL; i++) free(cctx->env[i]); free(cctx->env); } free(cctx); } Commit Message: CWE ID: CWE-254
mux_session_confirm(int id, int success, void *arg) { struct mux_session_confirm_ctx *cctx = arg; const char *display; Channel *c, *cc; int i; Buffer reply; if (cctx == NULL) fatal("%s: cctx == NULL", __func__); if ((c = channel_by_id(id)) == NULL) fatal("%s: no channel for id %d", __func__, id); if ((cc = channel_by_id(c->ctl_chan)) == NULL) fatal("%s: channel %d lacks control channel %d", __func__, id, c->ctl_chan); if (!success) { debug3("%s: sending failure reply", __func__); /* prepare reply */ buffer_init(&reply); buffer_put_int(&reply, MUX_S_FAILURE); buffer_put_int(&reply, cctx->rid); buffer_put_cstring(&reply, "Session open refused by peer"); goto done; } display = getenv("DISPLAY"); if (cctx->want_x_fwd && options.forward_x11 && display != NULL) { char *proto, *data; /* Get reasonable local authentication information. */ if (client_x11_get_proto(display, options.xauth_location, options.forward_x11_trusted, options.forward_x11_timeout, &proto, &data) == 0) { /* Request forwarding with authentication spoofing. */ debug("Requesting X11 forwarding with authentication " "spoofing."); x11_request_forwarding_with_spoofing(id, display, proto, data, 1); /* XXX exit_on_forward_failure */ client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN); } } if (cctx->want_agent_fwd && options.forward_agent) { packet_send(); } client_session2_setup(id, cctx->want_tty, cctx->want_subsys, cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env); debug3("%s: sending success reply", __func__); /* prepare reply */ buffer_init(&reply); buffer_put_int(&reply, MUX_S_SESSION_OPENED); buffer_put_int(&reply, cctx->rid); buffer_put_int(&reply, c->self); done: /* Send reply */ buffer_put_string(&cc->output, buffer_ptr(&reply), buffer_len(&reply)); buffer_free(&reply); if (cc->mux_pause <= 0) fatal("%s: mux_pause %d", __func__, cc->mux_pause); cc->mux_pause = 0; /* start processing messages again */ c->open_confirm_ctx = NULL; buffer_free(&cctx->cmd); free(cctx->term); if (cctx->env != NULL) { for (i = 0; cctx->env[i] != NULL; i++) free(cctx->env[i]); free(cctx->env); } free(cctx); }
165,352
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); ND_PRINT((ndo," len=%d method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (1 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo,") ")); } else if(ndo->ndo_vflag && 4 < len) { if(!ike_show_somedata(ndo, authdata, ep)) goto trunc; } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data. The closest thing to a specification for the contents of the payload data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it is ever a complete ISAKMP message, so don't dissect types we don't have specific code for as a complete ISAKMP message. While we're at it, fix a comment, and clean up printing of V1 Nonce, V2 Authentication payloads, and v2 Notice payloads. This fixes an infinite loop discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-835
ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; }
167,926
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ContainerNode::parserInsertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node& nextChild) { ASSERT(newChild); ASSERT(nextChild.parentNode() == this); ASSERT(!newChild->isDocumentFragment()); ASSERT(!isHTMLTemplateElement(this)); if (nextChild.previousSibling() == newChild || &nextChild == newChild) // nothing to do return; if (!checkParserAcceptChild(*newChild)) return; RefPtrWillBeRawPtr<Node> protect(this); while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode()) parent->parserRemoveChild(*newChild); if (document() != newChild->document()) document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION); { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; treeScope().adoptIfNeeded(*newChild); insertBeforeCommon(nextChild, *newChild); newChild->updateAncestorConnectedSubframeCountForInsertion(); ChildListMutationScope(*this).childAdded(*newChild); } notifyNodeInserted(*newChild, ChildrenChangeSourceParser); } Commit Message: parserInsertBefore: Bail out if the parent no longer contains the child. nextChild may be removed from the DOM tree during the |parserRemoveChild(*newChild)| call which triggers unload events of newChild's descendant iframes. In order to maintain the integrity of the DOM tree, the insertion of newChild must be aborted in this case. This patch adds a return statement that rectifies the behavior in this edge case. BUG=519558 Review URL: https://codereview.chromium.org/1283263002 git-svn-id: svn://svn.chromium.org/blink/trunk@200690 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264
void ContainerNode::parserInsertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node& nextChild) { ASSERT(newChild); ASSERT(nextChild.parentNode() == this); ASSERT(!newChild->isDocumentFragment()); ASSERT(!isHTMLTemplateElement(this)); if (nextChild.previousSibling() == newChild || &nextChild == newChild) // nothing to do return; if (!checkParserAcceptChild(*newChild)) return; RefPtrWillBeRawPtr<Node> protect(this); while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode()) parent->parserRemoveChild(*newChild); if (nextChild.parentNode() != this) return; if (document() != newChild->document()) document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION); { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; treeScope().adoptIfNeeded(*newChild); insertBeforeCommon(nextChild, *newChild); newChild->updateAncestorConnectedSubframeCountForInsertion(); ChildListMutationScope(*this).childAdded(*newChild); } notifyNodeInserted(*newChild, ChildrenChangeSourceParser); }
171,850
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: double VideoTrack::GetFrameRate() const { return m_rate; } 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
double VideoTrack::GetFrameRate() const
174,326
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CameraSource::signalBufferReturned(MediaBuffer *buffer) { ALOGV("signalBufferReturned: %p", buffer->data()); Mutex::Autolock autoLock(mLock); for (List<sp<IMemory> >::iterator it = mFramesBeingEncoded.begin(); it != mFramesBeingEncoded.end(); ++it) { if ((*it)->pointer() == buffer->data()) { releaseOneRecordingFrame((*it)); mFramesBeingEncoded.erase(it); ++mNumFramesEncoded; buffer->setObserver(0); buffer->release(); mFrameCompleteCondition.signal(); return; } } CHECK(!"signalBufferReturned: bogus buffer"); } Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak Subtract address of a random static object from pointers being routed through app process. Bug: 28466701 Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04 CWE ID: CWE-200
void CameraSource::signalBufferReturned(MediaBuffer *buffer) { ALOGV("signalBufferReturned: %p", buffer->data()); Mutex::Autolock autoLock(mLock); for (List<sp<IMemory> >::iterator it = mFramesBeingEncoded.begin(); it != mFramesBeingEncoded.end(); ++it) { if ((*it)->pointer() == buffer->data()) { // b/28466701 adjustOutgoingANWBuffer(it->get()); releaseOneRecordingFrame((*it)); mFramesBeingEncoded.erase(it); ++mNumFramesEncoded; buffer->setObserver(0); buffer->release(); mFrameCompleteCondition.signal(); return; } } CHECK(!"signalBufferReturned: bogus buffer"); }
173,510
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_attr_unknown (struct bgp_attr_parser_args *args) { bgp_size_t total; struct transit *transit; struct attr_extra *attre; struct peer *const peer = args->peer; struct attr *const attr = args->attr; u_char *const startp = args->startp; const u_char type = args->type; const u_char flag = args->flags; const bgp_size_t length = args->length; if (BGP_DEBUG (normal, NORMAL)) zlog_debug ("%s Unknown attribute is received (type %d, length %d)", peer->host, type, length); if (BGP_DEBUG (events, EVENTS)) zlog (peer->log, LOG_DEBUG, "Unknown attribute type %d length %d is received", type, length); /* Forward read pointer of input stream. */ stream_forward_getp (peer->ibuf, length); /* If any of the mandatory well-known attributes are not recognized, then the Error Subcode is set to Unrecognized Well-known Attribute. The Data field contains the unrecognized attribute (type, length and value). */ if (!CHECK_FLAG (flag, BGP_ATTR_FLAG_OPTIONAL)) { return bgp_attr_malformed (args, BGP_NOTIFY_UPDATE_UNREC_ATTR, args->total); } /* Unrecognized non-transitive optional attributes must be quietly ignored and not passed along to other BGP peers. */ if (! CHECK_FLAG (flag, BGP_ATTR_FLAG_TRANS)) return BGP_ATTR_PARSE_PROCEED; /* If a path with recognized transitive optional attribute is accepted and passed along to other BGP peers and the Partial bit in the Attribute Flags octet is set to 1 by some previous AS, it is not set back to 0 by the current AS. */ SET_FLAG (*startp, BGP_ATTR_FLAG_PARTIAL); /* Store transitive attribute to the end of attr->transit. */ if (! ((attre = bgp_attr_extra_get(attr))->transit) ) attre->transit = XCALLOC (MTYPE_TRANSIT, sizeof (struct transit)); transit = attre->transit; if (transit->val) transit->val = XREALLOC (MTYPE_TRANSIT_VAL, transit->val, transit->length + total); else transit->val = XMALLOC (MTYPE_TRANSIT_VAL, total); memcpy (transit->val + transit->length, startp, total); transit->length += total; return BGP_ATTR_PARSE_PROCEED; } Commit Message: CWE ID:
bgp_attr_unknown (struct bgp_attr_parser_args *args) { bgp_size_t total = args->total; struct transit *transit; struct attr_extra *attre; struct peer *const peer = args->peer; struct attr *const attr = args->attr; u_char *const startp = args->startp; const u_char type = args->type; const u_char flag = args->flags; const bgp_size_t length = args->length; if (BGP_DEBUG (normal, NORMAL)) zlog_debug ("%s Unknown attribute is received (type %d, length %d)", peer->host, type, length); if (BGP_DEBUG (events, EVENTS)) zlog (peer->log, LOG_DEBUG, "Unknown attribute type %d length %d is received", type, length); /* Forward read pointer of input stream. */ stream_forward_getp (peer->ibuf, length); /* If any of the mandatory well-known attributes are not recognized, then the Error Subcode is set to Unrecognized Well-known Attribute. The Data field contains the unrecognized attribute (type, length and value). */ if (!CHECK_FLAG (flag, BGP_ATTR_FLAG_OPTIONAL)) { return bgp_attr_malformed (args, BGP_NOTIFY_UPDATE_UNREC_ATTR, args->total); } /* Unrecognized non-transitive optional attributes must be quietly ignored and not passed along to other BGP peers. */ if (! CHECK_FLAG (flag, BGP_ATTR_FLAG_TRANS)) return BGP_ATTR_PARSE_PROCEED; /* If a path with recognized transitive optional attribute is accepted and passed along to other BGP peers and the Partial bit in the Attribute Flags octet is set to 1 by some previous AS, it is not set back to 0 by the current AS. */ SET_FLAG (*startp, BGP_ATTR_FLAG_PARTIAL); /* Store transitive attribute to the end of attr->transit. */ if (! ((attre = bgp_attr_extra_get(attr))->transit) ) attre->transit = XCALLOC (MTYPE_TRANSIT, sizeof (struct transit)); transit = attre->transit; if (transit->val) transit->val = XREALLOC (MTYPE_TRANSIT_VAL, transit->val, transit->length + total); else transit->val = XMALLOC (MTYPE_TRANSIT_VAL, total); memcpy (transit->val + transit->length, startp, total); transit->length += total; return BGP_ATTR_PARSE_PROCEED; }
164,575
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MediaControlTimelineElement::defaultEventHandler(Event* event) { if (event->isMouseEvent() && toMouseEvent(event)->button() != static_cast<short>(WebPointerProperties::Button::Left)) return; if (!isConnected() || !document().isActive()) return; if (event->type() == EventTypeNames::mousedown) { Platform::current()->recordAction( UserMetricsAction("Media.Controls.ScrubbingBegin")); mediaControls().beginScrubbing(); } if (event->type() == EventTypeNames::mouseup) { Platform::current()->recordAction( UserMetricsAction("Media.Controls.ScrubbingEnd")); mediaControls().endScrubbing(); } MediaControlInputElement::defaultEventHandler(event); if (event->type() == EventTypeNames::mouseover || event->type() == EventTypeNames::mouseout || event->type() == EventTypeNames::mousemove) return; double time = value().toDouble(); if (event->type() == EventTypeNames::input) { if (mediaElement().seekable()->contain(time)) mediaElement().setCurrentTime(time); } LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject())); if (!slider.isNull() && slider.inDragMode()) mediaControls().updateCurrentTimeDisplay(); } Commit Message: Fixed volume slider element event handling MediaControlVolumeSliderElement::defaultEventHandler has making redundant calls to setVolume() & setMuted() on mouse activity. E.g. if a mouse click changed the slider position, the above calls were made 4 times, once for each of these events: mousedown, input, mouseup, DOMActive, click. This crack got exposed when PointerEvents are enabled by default on M55, adding pointermove, pointerdown & pointerup to the list. This CL fixes the code to trigger the calls to setVolume() & setMuted() only when the slider position is changed. Also added pointer events to certain lists of mouse events in the code. BUG=677900 Review-Url: https://codereview.chromium.org/2622273003 Cr-Commit-Position: refs/heads/master@{#446032} CWE ID: CWE-119
void MediaControlTimelineElement::defaultEventHandler(Event* event) { if (event->isMouseEvent() && toMouseEvent(event)->button() != static_cast<short>(WebPointerProperties::Button::Left)) return; if (!isConnected() || !document().isActive()) return; if (event->type() == EventTypeNames::mousedown) { Platform::current()->recordAction( UserMetricsAction("Media.Controls.ScrubbingBegin")); mediaControls().beginScrubbing(); } if (event->type() == EventTypeNames::mouseup) { Platform::current()->recordAction( UserMetricsAction("Media.Controls.ScrubbingEnd")); mediaControls().endScrubbing(); } MediaControlInputElement::defaultEventHandler(event); if (event->type() != EventTypeNames::input) return; double time = value().toDouble(); // FIXME: This will need to take the timeline offset into consideration // once that concept is supported, see https://crbug.com/312699 if (mediaElement().seekable()->contain(time)) mediaElement().setCurrentTime(time); LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject())); if (!slider.isNull() && slider.inDragMode()) mediaControls().updateCurrentTimeDisplay(); }
171,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c); switch (type) { case EVP_CTRL_INIT: cctx->key_set = 0; cctx->iv_set = 0; cctx->L = 8; cctx->M = 12; cctx->tag_set = 0; cctx->len_set = 0; cctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); cctx->tls_aad_len = arg; { uint16_t len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) len -= cctx->M; EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return cctx->M; case EVP_CTRL_CCM_SET_IV_FIXED: /* Sanity check length */ if (arg != EVP_CCM_TLS_FIXED_IV_LEN) return 0; /* Just copy to first part of IV */ memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg); return 1; case EVP_CTRL_AEAD_SET_IVLEN: arg = 15 - arg; case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; cctx->L = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if ((arg & 1) || arg < 4 || arg > 16) return 0; if (EVP_CIPHER_CTX_encrypting(c) && ptr) return 0; if (ptr) { cctx->tag_set = 1; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); } cctx->M = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set) return 0; if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg)) return 0; cctx->tag_set = 0; cctx->iv_set = 0; cctx->len_set = 0; return 1; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out); if (cctx->ccm.key) { if (cctx->ccm.key != &cctx->ks) return 0; cctx_out->ccm.key = &cctx_out->ks; } return 1; } default: return -1; } } Commit Message: crypto/evp: harden AEAD ciphers. Originally a crash in 32-bit build was reported CHACHA20-POLY1305 cipher. The crash is triggered by truncated packet and is result of excessive hashing to the edge of accessible memory. Since hash operation is read-only it is not considered to be exploitable beyond a DoS condition. Other ciphers were hardened. Thanks to Robert Święcki for report. CVE-2017-3731 Reviewed-by: Rich Salz <rsalz@openssl.org> CWE ID: CWE-125
static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c); switch (type) { case EVP_CTRL_INIT: cctx->key_set = 0; cctx->iv_set = 0; cctx->L = 8; cctx->M = 12; cctx->tag_set = 0; cctx->len_set = 0; cctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); cctx->tls_aad_len = arg; { uint16_t len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ if (len < EVP_CCM_TLS_EXPLICIT_IV_LEN) return 0; len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) { if (len < cctx->M) return 0; len -= cctx->M; } EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return cctx->M; case EVP_CTRL_CCM_SET_IV_FIXED: /* Sanity check length */ if (arg != EVP_CCM_TLS_FIXED_IV_LEN) return 0; /* Just copy to first part of IV */ memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg); return 1; case EVP_CTRL_AEAD_SET_IVLEN: arg = 15 - arg; case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; cctx->L = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if ((arg & 1) || arg < 4 || arg > 16) return 0; if (EVP_CIPHER_CTX_encrypting(c) && ptr) return 0; if (ptr) { cctx->tag_set = 1; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); } cctx->M = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set) return 0; if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg)) return 0; cctx->tag_set = 0; cctx->iv_set = 0; cctx->len_set = 0; return 1; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out); if (cctx->ccm.key) { if (cctx->ccm.key != &cctx->ks) return 0; cctx_out->ccm.key = &cctx_out->ks; } return 1; } default: return -1; } }
168,430
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintMsg_Print_Params::Reset() { page_size = gfx::Size(); content_size = gfx::Size(); printable_area = gfx::Rect(); margin_top = 0; margin_left = 0; dpi = 0; scale_factor = 1.0f; rasterize_pdf = false; document_cookie = 0; selection_only = false; supports_alpha_blend = false; preview_ui_id = -1; preview_request_id = 0; is_first_request = false; print_scaling_option = blink::kWebPrintScalingOptionSourceSize; print_to_pdf = false; display_header_footer = false; title = base::string16(); url = base::string16(); should_print_backgrounds = false; printed_doc_type = printing::SkiaDocumentType::PDF; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Reviewed-by: Tom Sepez <tsepez@chromium.org> Reviewed-by: Jianzhou Feng <jzfeng@chromium.org> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20
void PrintMsg_Print_Params::Reset() { page_size = gfx::Size(); content_size = gfx::Size(); printable_area = gfx::Rect(); margin_top = 0; margin_left = 0; dpi = 0; scale_factor = 1.0f; rasterize_pdf = false; document_cookie = 0; selection_only = false; supports_alpha_blend = false; preview_ui_id = -1; preview_request_id = 0; is_first_request = false; print_scaling_option = blink::kWebPrintScalingOptionSourceSize; print_to_pdf = false; display_header_footer = false; title = base::string16(); url = base::string16(); header_template = base::string16(); footer_template = base::string16(); should_print_backgrounds = false; printed_doc_type = printing::SkiaDocumentType::PDF; }
172,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::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; } 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::CreateSimpleBlock(
174,260
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoundPool::play(int sampleID, float leftVolume, float rightVolume, int priority, int loop, float rate) { ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f", sampleID, leftVolume, rightVolume, priority, loop, rate); sp<Sample> sample; SoundChannel* channel; int channelID; Mutex::Autolock lock(&mLock); if (mQuit) { return 0; } sample = findSample(sampleID); if ((sample == 0) || (sample->state() != Sample::READY)) { ALOGW(" sample %d not READY", sampleID); return 0; } dump(); channel = allocateChannel_l(priority); if (!channel) { ALOGV("No channel allocated"); return 0; } channelID = ++mNextChannelID; ALOGV("play channel %p state = %d", channel, channel->state()); channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate); return channelID; } Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8 CWE ID: CWE-264
int SoundPool::play(int sampleID, float leftVolume, float rightVolume, int priority, int loop, float rate) { ALOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f", sampleID, leftVolume, rightVolume, priority, loop, rate); SoundChannel* channel; int channelID; Mutex::Autolock lock(&mLock); if (mQuit) { return 0; } sp<Sample> sample(findSample_l(sampleID)); if ((sample == 0) || (sample->state() != Sample::READY)) { ALOGW(" sample %d not READY", sampleID); return 0; } dump(); channel = allocateChannel_l(priority); if (!channel) { ALOGV("No channel allocated"); return 0; } channelID = ++mNextChannelID; ALOGV("play channel %p state = %d", channel, channel->state()); channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate); return channelID; }
173,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: UNCURL_EXPORT int32_t uncurl_ws_accept(struct uncurl_conn *ucc, char **origins, int32_t n_origins) { int32_t e; e = uncurl_read_header(ucc); if (e != UNCURL_OK) return e; uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); char *origin = NULL; e = uncurl_get_header_str(ucc, "Origin", &origin); if (e != UNCURL_OK) return e; bool origin_ok = false; for (int32_t x = 0; x < n_origins; x++) if (strstr(origin, origins[x])) {origin_ok = true; break;} if (!origin_ok) return UNCURL_WS_ERR_ORIGIN; char *sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Key", &sec_key); if (e != UNCURL_OK) return e; char *accept_key = ws_create_accept_key(sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Accept", accept_key); free(accept_key); e = uncurl_write_header(ucc, "101", "Switching Protocols", UNCURL_RESPONSE); if (e != UNCURL_OK) return e; ucc->ws_mask = 0; return UNCURL_OK; } Commit Message: origin matching must come at str end CWE ID: CWE-352
UNCURL_EXPORT int32_t uncurl_ws_accept(struct uncurl_conn *ucc, char **origins, int32_t n_origins) { int32_t e; e = uncurl_read_header(ucc); if (e != UNCURL_OK) return e; uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); char *origin = NULL; e = uncurl_get_header_str(ucc, "Origin", &origin); if (e != UNCURL_OK) return e; //the substring MUST came at the end of the origin header, thus a strstr AND a strcmp bool origin_ok = false; for (int32_t x = 0; x < n_origins; x++) { char *match = strstr(origin, origins[x]); if (match && !strcmp(match, origins[x])) {origin_ok = true; break;} } if (!origin_ok) return UNCURL_WS_ERR_ORIGIN; char *sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Key", &sec_key); if (e != UNCURL_OK) return e; char *accept_key = ws_create_accept_key(sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Accept", accept_key); free(accept_key); e = uncurl_write_header(ucc, "101", "Switching Protocols", UNCURL_RESPONSE); if (e != UNCURL_OK) return e; ucc->ws_mask = 0; return UNCURL_OK; }
169,336
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHPAPI php_stream *_php_stream_memory_open(int mode, char *buf, size_t length STREAMS_DC TSRMLS_DC) { php_stream *stream; php_stream_memory_data *ms; if ((stream = php_stream_memory_create_rel(mode)) != NULL) { ms = (php_stream_memory_data*)stream->abstract; if (mode == TEMP_STREAM_READONLY || mode == TEMP_STREAM_TAKE_BUFFER) { /* use the buffer directly */ ms->data = buf; ms->fsize = length; } else { if (length) { assert(buf != NULL); php_stream_write(stream, buf, length); } } } return stream; } Commit Message: CWE ID: CWE-20
PHPAPI php_stream *_php_stream_memory_open(int mode, char *buf, size_t length STREAMS_DC TSRMLS_DC) { php_stream *stream; php_stream_memory_data *ms; if ((stream = php_stream_memory_create_rel(mode)) != NULL) { ms = (php_stream_memory_data*)stream->abstract; if (mode == TEMP_STREAM_READONLY || mode == TEMP_STREAM_TAKE_BUFFER) { /* use the buffer directly */ ms->data = buf; ms->fsize = length; } else { if (length) { assert(buf != NULL); php_stream_write(stream, buf, length); } } } return stream; }
165,475
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, offsetUnset) { char *fname, *error; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ return; } if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } /* re-populate entry after copy on write */ entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len); } entry->is_modified = 0; entry->is_deleted = 1; /* we need to "flush" the stream to save the newly deleted file on disk */ phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } } else { RETURN_FALSE; } } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, offsetUnset) { char *fname, *error; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ return; } if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } /* re-populate entry after copy on write */ entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len); } entry->is_modified = 0; entry->is_deleted = 1; /* we need to "flush" the stream to save the newly deleted file on disk */ phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } } else { RETURN_FALSE; } }
165,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer, raptor_option option) { int result = -1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: result = TURTLE_WRITER_AUTO_INDENT(turtle_writer); break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: result = turtle_writer->indent; break; /* writer options */ case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: break; } return result; } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer, raptor_option option) { int result = -1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: result = TURTLE_WRITER_AUTO_INDENT(turtle_writer); break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: result = turtle_writer->indent; break; /* writer options */ case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: break; } return result; }
165,662
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(mb_ereg_search_init) { size_t argc = ZEND_NUM_ARGS(); zval *arg_str; char *arg_pattern = NULL, *arg_options = NULL; int arg_pattern_len = 0, arg_options_len = 0; OnigSyntaxType *syntax = NULL; OnigOptionType option; if (zend_parse_parameters(argc TSRMLS_CC, "z|ss", &arg_str, &arg_pattern, &arg_pattern_len, &arg_options, &arg_options_len) == FAILURE) { return; } if (argc > 1 && arg_pattern_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty pattern"); RETURN_FALSE; } option = MBREX(regex_default_options); syntax = MBREX(regex_default_syntax); if (argc == 3) { option = 0; _php_mb_regex_init_options(arg_options, arg_options_len, &option, &syntax, NULL); } if (argc > 1) { /* create regex pattern buffer */ if ((MBREX(search_re) = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, option, MBREX(current_mbctype), syntax TSRMLS_CC)) == NULL) { RETURN_FALSE; } } if (MBREX(search_str) != NULL) { zval_ptr_dtor(&MBREX(search_str)); MBREX(search_str) = (zval *)NULL; } MBREX(search_str) = arg_str; Z_ADDREF_P(MBREX(search_str)); SEPARATE_ZVAL_IF_NOT_REF(&MBREX(search_str)); MBREX(search_pos) = 0; if (MBREX(search_regs) != NULL) { onig_region_free(MBREX(search_regs), 1); MBREX(search_regs) = (OnigRegion *) NULL; } RETURN_TRUE; } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
PHP_FUNCTION(mb_ereg_search_init) { size_t argc = ZEND_NUM_ARGS(); zval *arg_str; char *arg_pattern = NULL, *arg_options = NULL; int arg_pattern_len = 0, arg_options_len = 0; OnigSyntaxType *syntax = NULL; OnigOptionType option; if (zend_parse_parameters(argc TSRMLS_CC, "z|ss", &arg_str, &arg_pattern, &arg_pattern_len, &arg_options, &arg_options_len) == FAILURE) { return; } if (argc > 1 && arg_pattern_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty pattern"); RETURN_FALSE; } option = MBREX(regex_default_options); syntax = MBREX(regex_default_syntax); if (argc == 3) { option = 0; _php_mb_regex_init_options(arg_options, arg_options_len, &option, &syntax, NULL); } if (argc > 1) { /* create regex pattern buffer */ if ((MBREX(search_re) = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, option, MBREX(current_mbctype), syntax TSRMLS_CC)) == NULL) { RETURN_FALSE; } } if (MBREX(search_str) != NULL) { zval_ptr_dtor(&MBREX(search_str)); MBREX(search_str) = (zval *)NULL; } MBREX(search_str) = arg_str; Z_ADDREF_P(MBREX(search_str)); SEPARATE_ZVAL_IF_NOT_REF(&MBREX(search_str)); MBREX(search_pos) = 0; if (MBREX(search_regs) != NULL) { onig_region_free(MBREX(search_regs), 1); MBREX(search_regs) = (OnigRegion *) NULL; } RETURN_TRUE; }
167,116
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id, PNG_CONST char *name) { /* Do this first so that the modifier fields are cleared even if an error * happens allocating the png_struct. No allocation is done here so no * cleanup is required. */ pm->state = modifier_start; pm->bit_depth = 0; pm->colour_type = 255; pm->pending_len = 0; pm->pending_chunk = 0; pm->flush = 0; pm->buffer_count = 0; pm->buffer_position = 0; return set_store_for_read(&pm->this, ppi, id, name); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id, const char *name) { /* Do this first so that the modifier fields are cleared even if an error * happens allocating the png_struct. No allocation is done here so no * cleanup is required. */ pm->state = modifier_start; pm->bit_depth = 0; pm->colour_type = 255; pm->pending_len = 0; pm->pending_chunk = 0; pm->flush = 0; pm->buffer_count = 0; pm->buffer_position = 0; return set_store_for_read(&pm->this, ppi, id, name); }
173,694
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const { assert(m_pos >= m_element_start); pEntry = NULL; if (index < 0) return -1; //generic error if (m_entries_count < 0) return E_BUFFER_NOT_FULL; assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (index < m_entries_count) { pEntry = m_entries[index]; assert(pEntry); return 1; //found entry } if (m_element_size < 0) //we don't know cluster end yet return E_BUFFER_NOT_FULL; //underflow const long long element_stop = m_element_start + m_element_size; if (m_pos >= element_stop) return 0; //nothing left to parse return E_BUFFER_NOT_FULL; //underflow, since more remains to be parsed } 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::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } unsigned char flags; status = pReader->Read(pos, 1, &flags);
174,314
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *hashtable_iter_at(hashtable_t *hashtable, const char *key) { pair_t *pair; size_t hash; bucket_t *bucket; hash = hash_str(key); bucket = &hashtable->buckets[hash % num_buckets(hashtable)]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(!pair) return NULL; return &pair->list; } 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
void *hashtable_iter_at(hashtable_t *hashtable, const char *key) { pair_t *pair; size_t hash; bucket_t *bucket; hash = hash_str(key); bucket = &hashtable->buckets[hash & hashmask(hashtable->order)]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(!pair) return NULL; return &pair->list; }
166,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InspectorTraceEvents::WillSendRequest( ExecutionContext*, unsigned long identifier, DocumentLoader* loader, ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo&) { LocalFrame* frame = loader ? loader->GetFrame() : nullptr; TRACE_EVENT_INSTANT1( "devtools.timeline", "ResourceSendRequest", TRACE_EVENT_SCOPE_THREAD, "data", InspectorSendRequestEvent::Data(identifier, frame, request)); probe::AsyncTaskScheduled(frame ? frame->GetDocument() : nullptr, "SendRequest", AsyncId(identifier)); } 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
void InspectorTraceEvents::WillSendRequest( ExecutionContext*, unsigned long identifier, DocumentLoader* loader, ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo&, Resource::Type) { LocalFrame* frame = loader ? loader->GetFrame() : nullptr; TRACE_EVENT_INSTANT1( "devtools.timeline", "ResourceSendRequest", TRACE_EVENT_SCOPE_THREAD, "data", InspectorSendRequestEvent::Data(identifier, frame, request)); probe::AsyncTaskScheduled(frame ? frame->GetDocument() : nullptr, "SendRequest", AsyncId(identifier)); }
172,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int vcc_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct atm_vcc *vcc; int len; if (get_user(len, optlen)) return -EFAULT; if (__SO_LEVEL_MATCH(optname, level) && len != __SO_SIZE(optname)) return -EINVAL; vcc = ATM_SD(sock); switch (optname) { case SO_ATMQOS: if (!test_bit(ATM_VF_HASQOS, &vcc->flags)) return -EINVAL; return copy_to_user(optval, &vcc->qos, sizeof(vcc->qos)) ? -EFAULT : 0; case SO_SETCLP: return put_user(vcc->atm_options & ATM_ATMOPT_CLP ? 1 : 0, (unsigned long __user *)optval) ? -EFAULT : 0; case SO_ATMPVC: { struct sockaddr_atmpvc pvc; if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags)) return -ENOTCONN; pvc.sap_family = AF_ATMPVC; pvc.sap_addr.itf = vcc->dev->number; pvc.sap_addr.vpi = vcc->vpi; pvc.sap_addr.vci = vcc->vci; return copy_to_user(optval, &pvc, sizeof(pvc)) ? -EFAULT : 0; } default: if (level == SOL_SOCKET) return -EINVAL; break; } if (!vcc->dev || !vcc->dev->ops->getsockopt) return -EINVAL; return vcc->dev->ops->getsockopt(vcc, level, optname, optval, len); } Commit Message: atm: fix info leak in getsockopt(SO_ATMPVC) The ATM code fails to initialize the two padding bytes of struct sockaddr_atmpvc inserted for alignment. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
int vcc_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct atm_vcc *vcc; int len; if (get_user(len, optlen)) return -EFAULT; if (__SO_LEVEL_MATCH(optname, level) && len != __SO_SIZE(optname)) return -EINVAL; vcc = ATM_SD(sock); switch (optname) { case SO_ATMQOS: if (!test_bit(ATM_VF_HASQOS, &vcc->flags)) return -EINVAL; return copy_to_user(optval, &vcc->qos, sizeof(vcc->qos)) ? -EFAULT : 0; case SO_SETCLP: return put_user(vcc->atm_options & ATM_ATMOPT_CLP ? 1 : 0, (unsigned long __user *)optval) ? -EFAULT : 0; case SO_ATMPVC: { struct sockaddr_atmpvc pvc; if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags)) return -ENOTCONN; memset(&pvc, 0, sizeof(pvc)); pvc.sap_family = AF_ATMPVC; pvc.sap_addr.itf = vcc->dev->number; pvc.sap_addr.vpi = vcc->vpi; pvc.sap_addr.vci = vcc->vci; return copy_to_user(optval, &pvc, sizeof(pvc)) ? -EFAULT : 0; } default: if (level == SOL_SOCKET) return -EINVAL; break; } if (!vcc->dev || !vcc->dev->ops->getsockopt) return -EINVAL; return vcc->dev->ops->getsockopt(vcc, level, optname, optval, len); }
166,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: BOOLEAN UIPC_Send(tUIPC_CH_ID ch_id, UINT16 msg_evt, UINT8 *p_buf, UINT16 msglen) { UNUSED(msg_evt); BTIF_TRACE_DEBUG("UIPC_Send : ch_id:%d %d bytes", ch_id, msglen); UIPC_LOCK(); if (write(uipc_main.ch[ch_id].fd, p_buf, msglen) < 0) { BTIF_TRACE_ERROR("failed to write (%s)", strerror(errno)); } UIPC_UNLOCK(); 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
BOOLEAN UIPC_Send(tUIPC_CH_ID ch_id, UINT16 msg_evt, UINT8 *p_buf, UINT16 msglen) { UNUSED(msg_evt); BTIF_TRACE_DEBUG("UIPC_Send : ch_id:%d %d bytes", ch_id, msglen); UIPC_LOCK(); if (TEMP_FAILURE_RETRY(write(uipc_main.ch[ch_id].fd, p_buf, msglen)) < 0) { BTIF_TRACE_ERROR("failed to write (%s)", strerror(errno)); } UIPC_UNLOCK(); return FALSE; }
173,494
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xps_begin_opacity(xps_document *doc, const fz_matrix *ctm, const fz_rect *area, char *base_uri, xps_resource *dict, char *opacity_att, fz_xml *opacity_mask_tag) { float opacity; if (!opacity_att && !opacity_mask_tag) return; opacity = 1; if (opacity_att) opacity = fz_atof(opacity_att); if (opacity_mask_tag && !strcmp(fz_xml_tag(opacity_mask_tag), "SolidColorBrush")) { char *scb_opacity_att = fz_xml_att(opacity_mask_tag, "Opacity"); char *scb_color_att = fz_xml_att(opacity_mask_tag, "Color"); if (scb_opacity_att) opacity = opacity * fz_atof(scb_opacity_att); if (scb_color_att) { fz_colorspace *colorspace; float samples[32]; xps_parse_color(doc, base_uri, scb_color_att, &colorspace, samples); opacity = opacity * samples[0]; } opacity_mask_tag = NULL; } if (doc->opacity_top + 1 < nelem(doc->opacity)) { doc->opacity[doc->opacity_top + 1] = doc->opacity[doc->opacity_top] * opacity; doc->opacity_top++; } if (opacity_mask_tag) { fz_begin_mask(doc->dev, area, 0, NULL, NULL); xps_parse_brush(doc, ctm, area, base_uri, dict, opacity_mask_tag); fz_end_mask(doc->dev); } } Commit Message: CWE ID: CWE-119
xps_begin_opacity(xps_document *doc, const fz_matrix *ctm, const fz_rect *area, char *base_uri, xps_resource *dict, char *opacity_att, fz_xml *opacity_mask_tag) { float opacity; if (!opacity_att && !opacity_mask_tag) return; opacity = 1; if (opacity_att) opacity = fz_atof(opacity_att); if (opacity_mask_tag && !strcmp(fz_xml_tag(opacity_mask_tag), "SolidColorBrush")) { char *scb_opacity_att = fz_xml_att(opacity_mask_tag, "Opacity"); char *scb_color_att = fz_xml_att(opacity_mask_tag, "Color"); if (scb_opacity_att) opacity = opacity * fz_atof(scb_opacity_att); if (scb_color_att) { fz_colorspace *colorspace; float samples[FZ_MAX_COLORS]; xps_parse_color(doc, base_uri, scb_color_att, &colorspace, samples); opacity = opacity * samples[0]; } opacity_mask_tag = NULL; } if (doc->opacity_top + 1 < nelem(doc->opacity)) { doc->opacity[doc->opacity_top + 1] = doc->opacity[doc->opacity_top] * opacity; doc->opacity_top++; } if (opacity_mask_tag) { fz_begin_mask(doc->dev, area, 0, NULL, NULL); xps_parse_brush(doc, ctm, area, base_uri, dict, opacity_mask_tag); fz_end_mask(doc->dev); } }
165,227
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ContentEncoding::GetCompressionByIndex(unsigned long idx) const { const ptrdiff_t count = compression_entries_end_ - compression_entries_; assert(count >= 0); if (idx >= static_cast<unsigned long>(count)) return NULL; return compression_entries_[idx]; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
ContentEncoding::GetCompressionByIndex(unsigned long idx) const { ContentEncoding::GetCompressionByIndex(unsigned long idx) const { const ptrdiff_t count = compression_entries_end_ - compression_entries_; assert(count >= 0); if (idx >= static_cast<unsigned long>(count)) return NULL; return compression_entries_[idx]; }
173,815
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Cluster::~Cluster() { if (m_entries_count <= 0) return; BlockEntry** i = m_entries; BlockEntry** const j = m_entries + m_entries_count; while (i != j) { BlockEntry* p = *i++; assert(p); delete p; } delete[] m_entries; } 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
Cluster::~Cluster() if (status < 0) { // error or underflow len = 1; return status; } ++pos; // consume flags byte assert(pos <= avail); if (pos >= block_stop) return E_FILE_FORMAT_INVALID; const int lacing = int(flags & 0x06) >> 1; if ((lacing != 0) && (block_stop > avail)) { len = static_cast<long>(block_stop - pos); return E_BUFFER_NOT_FULL; } pos = block_stop; // consume block-part of block group assert(pos <= payload_stop); } assert(pos == payload_stop); status = CreateBlock(0x20, // BlockGroup ID payload_start, payload_size, discard_padding); if (status != 0) return status; m_pos = payload_stop; return 0; // success }
174,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: append_utf8_value (const unsigned char *value, size_t length, struct stringbuf *sb) { unsigned char tmp[6]; const unsigned char *s; size_t n; int i, nmore; if (length && (*value == ' ' || *value == '#')) { tmp[0] = '\\'; tmp[1] = *value; put_stringbuf_mem (sb, tmp, 2); value++; length--; } if (length && value[length-1] == ' ') { tmp[0] = '\\'; tmp[1] = ' '; put_stringbuf_mem (sb, tmp, 2); length--; } /* FIXME: check that the invalid encoding handling is correct */ for (s=value, n=0;;) { for (value = s; n < length && !(*s & 0x80); n++, s++) for (value = s; n < length && !(*s & 0x80); n++, s++) ; append_quoted (sb, value, s-value, 0); if (n==length) return; /* ready */ assert ((*s & 0x80)); if ( (*s & 0xe0) == 0xc0 ) /* 110x xxxx */ nmore = 1; else if ( (*s & 0xf0) == 0xe0 ) /* 1110 xxxx */ nmore = 2; else if ( (*s & 0xf8) == 0xf0 ) /* 1111 0xxx */ nmore = 3; else if ( (*s & 0xfc) == 0xf8 ) /* 1111 10xx */ nmore = 4; else if ( (*s & 0xfe) == 0xfc ) /* 1111 110x */ nmore = 5; else /* invalid encoding */ nmore = 5; /* we will reduce the check length anyway */ if (n+nmore > length) nmore = length - n; /* oops, encoding to short */ tmp[0] = *s++; n++; for (i=1; i <= nmore; i++) { if ( (*s & 0xc0) != 0x80) break; /* invalid encoding - stop */ tmp[i] = *s++; n++; } put_stringbuf_mem (sb, tmp, i); } } Commit Message: CWE ID: CWE-119
append_utf8_value (const unsigned char *value, size_t length, struct stringbuf *sb) { unsigned char tmp[6]; const unsigned char *s; size_t n; int i, nmore; if (length && (*value == ' ' || *value == '#')) { tmp[0] = '\\'; tmp[1] = *value; put_stringbuf_mem (sb, tmp, 2); value++; length--; } if (length && value[length-1] == ' ') { tmp[0] = '\\'; tmp[1] = ' '; put_stringbuf_mem (sb, tmp, 2); length--; } for (s=value, n=0;;) { for (value = s; n < length && !(*s & 0x80); n++, s++) for (value = s; n < length && !(*s & 0x80); n++, s++) ; append_quoted (sb, value, s-value, 0); if (n==length) return; /* ready */ if (!(*s & 0x80)) nmore = 0; /* Not expected here: high bit not set. */ else if ( (*s & 0xe0) == 0xc0 ) /* 110x xxxx */ nmore = 1; else if ( (*s & 0xf0) == 0xe0 ) /* 1110 xxxx */ nmore = 2; else if ( (*s & 0xf8) == 0xf0 ) /* 1111 0xxx */ nmore = 3; else if ( (*s & 0xfc) == 0xf8 ) /* 1111 10xx */ nmore = 4; else if ( (*s & 0xfe) == 0xfc ) /* 1111 110x */ nmore = 5; else /* Invalid encoding */ nmore = 0; if (!nmore) { /* Encoding error: We quote the bad byte. */ snprintf (tmp, sizeof tmp, "\\%02X", *s); put_stringbuf_mem (sb, tmp, 3); s++; n++; } else { if (n+nmore > length) nmore = length - n; /* Oops, encoding to short */ tmp[0] = *s++; n++; for (i=1; i <= nmore; i++) { if ( (*s & 0xc0) != 0x80) break; /* Invalid encoding - let the next cycle detect this. */ tmp[i] = *s++; n++; } put_stringbuf_mem (sb, tmp, i); } } }
165,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vp8dx_receive_compressed_data(VP8D_COMP *pbi, size_t size, const uint8_t *source, int64_t time_stamp) { VP8_COMMON *cm = &pbi->common; int retcode = -1; (void)size; (void)source; pbi->common.error.error_code = VPX_CODEC_OK; retcode = check_fragments_for_errors(pbi); if(retcode <= 0) return retcode; cm->new_fb_idx = get_free_fb (cm); /* setup reference frames for vp8_decode_frame */ pbi->dec_fb_ref[INTRA_FRAME] = &cm->yv12_fb[cm->new_fb_idx]; pbi->dec_fb_ref[LAST_FRAME] = &cm->yv12_fb[cm->lst_fb_idx]; pbi->dec_fb_ref[GOLDEN_FRAME] = &cm->yv12_fb[cm->gld_fb_idx]; pbi->dec_fb_ref[ALTREF_FRAME] = &cm->yv12_fb[cm->alt_fb_idx]; if (setjmp(pbi->common.error.jmp)) { /* We do not know if the missing frame(s) was supposed to update * any of the reference buffers, but we act conservative and * mark only the last buffer as corrupted. */ cm->yv12_fb[cm->lst_fb_idx].corrupted = 1; if (cm->fb_idx_ref_cnt[cm->new_fb_idx] > 0) cm->fb_idx_ref_cnt[cm->new_fb_idx]--; goto decode_exit; } pbi->common.error.setjmp = 1; retcode = vp8_decode_frame(pbi); if (retcode < 0) { if (cm->fb_idx_ref_cnt[cm->new_fb_idx] > 0) cm->fb_idx_ref_cnt[cm->new_fb_idx]--; pbi->common.error.error_code = VPX_CODEC_ERROR; goto decode_exit; } if (swap_frame_buffers (cm)) { pbi->common.error.error_code = VPX_CODEC_ERROR; goto decode_exit; } vp8_clear_system_state(); if (cm->show_frame) { cm->current_video_frame++; cm->show_frame_mi = cm->mi; } #if CONFIG_ERROR_CONCEALMENT /* swap the mode infos to storage for future error concealment */ if (pbi->ec_enabled && pbi->common.prev_mi) { MODE_INFO* tmp = pbi->common.prev_mi; int row, col; pbi->common.prev_mi = pbi->common.mi; pbi->common.mi = tmp; /* Propagate the segment_ids to the next frame */ for (row = 0; row < pbi->common.mb_rows; ++row) { for (col = 0; col < pbi->common.mb_cols; ++col) { const int i = row*pbi->common.mode_info_stride + col; pbi->common.mi[i].mbmi.segment_id = pbi->common.prev_mi[i].mbmi.segment_id; } } } #endif pbi->ready_for_new_data = 0; pbi->last_time_stamp = time_stamp; decode_exit: pbi->common.error.setjmp = 0; vp8_clear_system_state(); return retcode; } Commit Message: vp8:fix threading issues 1 - stops de allocating before threads are closed. 2 - limits threads to mb_rows when mb_rows < partitions BUG=webm:851 Bug: 30436808 Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b (cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e) CWE ID:
int vp8dx_receive_compressed_data(VP8D_COMP *pbi, size_t size, const uint8_t *source, int64_t time_stamp) { VP8_COMMON *cm = &pbi->common; int retcode = -1; (void)size; (void)source; pbi->common.error.error_code = VPX_CODEC_OK; retcode = check_fragments_for_errors(pbi); if(retcode <= 0) return retcode; cm->new_fb_idx = get_free_fb (cm); /* setup reference frames for vp8_decode_frame */ pbi->dec_fb_ref[INTRA_FRAME] = &cm->yv12_fb[cm->new_fb_idx]; pbi->dec_fb_ref[LAST_FRAME] = &cm->yv12_fb[cm->lst_fb_idx]; pbi->dec_fb_ref[GOLDEN_FRAME] = &cm->yv12_fb[cm->gld_fb_idx]; pbi->dec_fb_ref[ALTREF_FRAME] = &cm->yv12_fb[cm->alt_fb_idx]; if (setjmp(pbi->common.error.jmp)) { /* We do not know if the missing frame(s) was supposed to update * any of the reference buffers, but we act conservative and * mark only the last buffer as corrupted. */ cm->yv12_fb[cm->lst_fb_idx].corrupted = 1; if (cm->fb_idx_ref_cnt[cm->new_fb_idx] > 0) cm->fb_idx_ref_cnt[cm->new_fb_idx]--; goto decode_exit; } pbi->common.error.setjmp = 1; retcode = vp8_decode_frame(pbi); if (retcode < 0) { if (cm->fb_idx_ref_cnt[cm->new_fb_idx] > 0) cm->fb_idx_ref_cnt[cm->new_fb_idx]--; pbi->common.error.error_code = VPX_CODEC_ERROR; goto decode_exit; } if (swap_frame_buffers (cm)) { pbi->common.error.error_code = VPX_CODEC_ERROR; goto decode_exit; } vp8_clear_system_state(); if (cm->show_frame) { cm->current_video_frame++; cm->show_frame_mi = cm->mi; } #if CONFIG_ERROR_CONCEALMENT /* swap the mode infos to storage for future error concealment */ if (pbi->ec_enabled && pbi->common.prev_mi) { MODE_INFO* tmp = pbi->common.prev_mi; int row, col; pbi->common.prev_mi = pbi->common.mi; pbi->common.mi = tmp; /* Propagate the segment_ids to the next frame */ for (row = 0; row < pbi->common.mb_rows; ++row) { for (col = 0; col < pbi->common.mb_cols; ++col) { const int i = row*pbi->common.mode_info_stride + col; pbi->common.mi[i].mbmi.segment_id = pbi->common.prev_mi[i].mbmi.segment_id; } } } #endif pbi->ready_for_new_data = 0; pbi->last_time_stamp = time_stamp; decode_exit: pbi->common.error.setjmp = 0; vp8_clear_system_state(); return retcode; }
174,066
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: wb_prep(netdissect_options *ndo, const struct pkt_prep *prep, u_int len) { int n; const struct pgstate *ps; const u_char *ep = ndo->ndo_snapend; ND_PRINT((ndo, " wb-prep:")); if (len < sizeof(*prep)) { return (-1); } n = EXTRACT_32BITS(&prep->pp_n); ps = (const struct pgstate *)(prep + 1); while (--n >= 0 && ND_TTEST(*ps)) { const struct id_off *io, *ie; char c = '<'; ND_PRINT((ndo, " %u/%s:%u", EXTRACT_32BITS(&ps->slot), ipaddr_string(ndo, &ps->page.p_sid), EXTRACT_32BITS(&ps->page.p_uid))); io = (const struct id_off *)(ps + 1); for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } ND_PRINT((ndo, ">")); ps = (const struct pgstate *)io; } return ((const u_char *)ps <= ep? 0 : -1); } Commit Message: CVE-2017-13014/White Board: Do more bounds checks. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). While we're at it, print a truncation error if the packets are truncated, rather than just, in effect, ignoring the result of the routines that print particular packet types. CWE ID: CWE-125
wb_prep(netdissect_options *ndo, const struct pkt_prep *prep, u_int len) { int n; const struct pgstate *ps; const u_char *ep = ndo->ndo_snapend; ND_PRINT((ndo, " wb-prep:")); if (len < sizeof(*prep) || !ND_TTEST(*prep)) return (-1); n = EXTRACT_32BITS(&prep->pp_n); ps = (const struct pgstate *)(prep + 1); while (--n >= 0 && ND_TTEST(*ps)) { const struct id_off *io, *ie; char c = '<'; ND_PRINT((ndo, " %u/%s:%u", EXTRACT_32BITS(&ps->slot), ipaddr_string(ndo, &ps->page.p_sid), EXTRACT_32BITS(&ps->page.p_uid))); io = (const struct id_off *)(ps + 1); for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } ND_PRINT((ndo, ">")); ps = (const struct pgstate *)io; } return ((const u_char *)ps <= ep? 0 : -1); }
167,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dtls1_clear_queues(SSL *s) { pitem *item = NULL; hm_fragment *frag = NULL; DTLS1_RECORD_DATA *rdata; while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } } Commit Message: Free up s->d1->buffered_app_data.q properly. PR#3286 CWE ID: CWE-119
static void dtls1_clear_queues(SSL *s) { pitem *item = NULL; hm_fragment *frag = NULL; DTLS1_RECORD_DATA *rdata; while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } }
166,794
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf, size_t nbytes) { union { int32_t l; char c[sizeof (int32_t)]; } u; int clazz; int swap; struct stat st; off_t fsize; int flags = 0; Elf32_Ehdr elf32hdr; Elf64_Ehdr elf64hdr; uint16_t type, phnum, shnum; if (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) return 0; /* * ELF executables have multiple section headers in arbitrary * file locations and thus file(1) cannot determine it from easily. * Instead we traverse thru all section headers until a symbol table * one is found or else the binary is stripped. * Return immediately if it's not ELF (so we avoid pipe2file unless needed). */ if (buf[EI_MAG0] != ELFMAG0 || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1) || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3) return 0; /* * If we cannot seek, it must be a pipe, socket or fifo. */ if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE)) fd = file_pipe2file(ms, fd, buf, nbytes); if (fstat(fd, &st) == -1) { file_badread(ms); return -1; } if (S_ISREG(st.st_mode) || st.st_size != 0) fsize = st.st_size; else fsize = SIZE_UNKNOWN; clazz = buf[EI_CLASS]; switch (clazz) { case ELFCLASS32: #undef elf_getu #define elf_getu(a, b) elf_getu32(a, b) #undef elfhdr #define elfhdr elf32hdr #include "elfclass.h" case ELFCLASS64: #undef elf_getu #define elf_getu(a, b) elf_getu64(a, b) #undef elfhdr #define elfhdr elf64hdr #include "elfclass.h" default: if (file_printf(ms, ", unknown class %d", clazz) == -1) return -1; break; } return 0; } Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind. CWE ID: CWE-399
file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf, size_t nbytes) { union { int32_t l; char c[sizeof (int32_t)]; } u; int clazz; int swap; struct stat st; off_t fsize; int flags = 0; Elf32_Ehdr elf32hdr; Elf64_Ehdr elf64hdr; uint16_t type, phnum, shnum, notecount; if (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) return 0; /* * ELF executables have multiple section headers in arbitrary * file locations and thus file(1) cannot determine it from easily. * Instead we traverse thru all section headers until a symbol table * one is found or else the binary is stripped. * Return immediately if it's not ELF (so we avoid pipe2file unless needed). */ if (buf[EI_MAG0] != ELFMAG0 || (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1) || buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3) return 0; /* * If we cannot seek, it must be a pipe, socket or fifo. */ if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE)) fd = file_pipe2file(ms, fd, buf, nbytes); if (fstat(fd, &st) == -1) { file_badread(ms); return -1; } if (S_ISREG(st.st_mode) || st.st_size != 0) fsize = st.st_size; else fsize = SIZE_UNKNOWN; clazz = buf[EI_CLASS]; switch (clazz) { case ELFCLASS32: #undef elf_getu #define elf_getu(a, b) elf_getu32(a, b) #undef elfhdr #define elfhdr elf32hdr #include "elfclass.h" case ELFCLASS64: #undef elf_getu #define elf_getu(a, b) elf_getu64(a, b) #undef elfhdr #define elfhdr elf64hdr #include "elfclass.h" default: if (file_printf(ms, ", unknown class %d", clazz) == -1) return -1; break; } return 0; }
166,780
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); } Commit Message: (for 4.9.3) CVE-2018-14881/BGP: Fix BGP_CAPCODE_RESTART. Add a bounds check and a comment to bgp_capabilities_print(). This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
bgp_capabilities_print(netdissect_options *ndo, const u_char *opt, int caps_len) { int cap_type, cap_len, tcap_len, cap_offset; int i = 0; while (i < caps_len) { ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); cap_type=opt[i]; cap_len=opt[i+1]; tcap_len=cap_len; ND_PRINT((ndo, "\n\t %s (%u), length: %u", tok2str(bgp_capcode_values, "Unknown", cap_type), cap_type, cap_len)); ND_TCHECK2(opt[i+2], cap_len); switch (cap_type) { case BGP_CAPCODE_MP: ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)", tok2str(af_values, "Unknown", EXTRACT_16BITS(opt+i+2)), EXTRACT_16BITS(opt+i+2), tok2str(bgp_safi_values, "Unknown", opt[i+5]), opt[i+5])); break; case BGP_CAPCODE_RESTART: /* Restart Flags (4 bits), Restart Time in seconds (12 bits) */ ND_TCHECK_16BITS(opt + i + 2); ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us", ((opt[i+2])&0x80) ? "R" : "none", EXTRACT_16BITS(opt+i+2)&0xfff)); tcap_len-=2; cap_offset=4; while(tcap_len>=4) { ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s", tok2str(af_values,"Unknown", EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown", opt[i+cap_offset+2]), opt[i+cap_offset+2], ((opt[i+cap_offset+3])&0x80) ? "yes" : "no" )); tcap_len-=4; cap_offset+=4; } break; case BGP_CAPCODE_RR: case BGP_CAPCODE_RR_CISCO: break; case BGP_CAPCODE_AS_NEW: /* * Extract the 4 byte AS number encoded. */ if (cap_len == 4) { ND_PRINT((ndo, "\n\t\t 4 Byte AS %s", as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(opt + i + 2)))); } break; case BGP_CAPCODE_ADD_PATH: cap_offset=2; if (tcap_len == 0) { ND_PRINT((ndo, " (bogus)")); /* length */ break; } while (tcap_len > 0) { if (tcap_len < 4) { ND_PRINT((ndo, "\n\t\t(invalid)")); break; } ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s", tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)), EXTRACT_16BITS(opt+i+cap_offset), tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]), opt[i+cap_offset+2], tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3]) )); tcap_len-=4; cap_offset+=4; } break; default: ND_PRINT((ndo, "\n\t\tno decoder for Capability %u", cap_type)); if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); break; } if (ndo->ndo_vflag > 1 && cap_len > 0) { print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len); } i += BGP_CAP_HEADER_SIZE + cap_len; } return; trunc: ND_PRINT((ndo, "[|BGP]")); }
169,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root */ if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) jsvAddName(execInfo.root, lhs); } jspReplaceWith(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; } Commit Message: Fix bug if using an undefined member of an object for for..in (fix #1437) CWE ID: CWE-125
NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { jspReplaceWithOrAddToRoot(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; }
169,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: call_bind_status(struct rpc_task *task) { int status = -EIO; if (task->tk_status >= 0) { dprint_status(task); task->tk_status = 0; task->tk_action = call_connect; return; } switch (task->tk_status) { case -ENOMEM: dprintk("RPC: %5u rpcbind out of memory\n", task->tk_pid); rpc_delay(task, HZ >> 2); goto retry_timeout; case -EACCES: dprintk("RPC: %5u remote rpcbind: RPC program/version " "unavailable\n", task->tk_pid); /* fail immediately if this is an RPC ping */ if (task->tk_msg.rpc_proc->p_proc == 0) { status = -EOPNOTSUPP; break; } rpc_delay(task, 3*HZ); goto retry_timeout; case -ETIMEDOUT: dprintk("RPC: %5u rpcbind request timed out\n", task->tk_pid); goto retry_timeout; case -EPFNOSUPPORT: /* server doesn't support any rpcbind version we know of */ dprintk("RPC: %5u unrecognized remote rpcbind service\n", task->tk_pid); break; case -EPROTONOSUPPORT: dprintk("RPC: %5u remote rpcbind version unavailable, retrying\n", task->tk_pid); task->tk_status = 0; task->tk_action = call_bind; return; case -ECONNREFUSED: /* connection problems */ case -ECONNRESET: case -ENOTCONN: case -EHOSTDOWN: case -EHOSTUNREACH: case -ENETUNREACH: case -EPIPE: dprintk("RPC: %5u remote rpcbind unreachable: %d\n", task->tk_pid, task->tk_status); if (!RPC_IS_SOFTCONN(task)) { rpc_delay(task, 5*HZ); goto retry_timeout; } status = task->tk_status; break; default: dprintk("RPC: %5u unrecognized rpcbind error (%d)\n", task->tk_pid, -task->tk_status); } rpc_exit(task, status); return; retry_timeout: task->tk_action = call_timeout; } 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
call_bind_status(struct rpc_task *task) { int status = -EIO; if (task->tk_status >= 0) { dprint_status(task); task->tk_status = 0; task->tk_action = call_connect; return; } switch (task->tk_status) { case -ENOMEM: dprintk("RPC: %5u rpcbind out of memory\n", task->tk_pid); rpc_delay(task, HZ >> 2); goto retry_timeout; case -EACCES: dprintk("RPC: %5u remote rpcbind: RPC program/version " "unavailable\n", task->tk_pid); /* fail immediately if this is an RPC ping */ if (task->tk_msg.rpc_proc->p_proc == 0) { status = -EOPNOTSUPP; break; } if (task->tk_rebind_retry == 0) break; task->tk_rebind_retry--; rpc_delay(task, 3*HZ); goto retry_timeout; case -ETIMEDOUT: dprintk("RPC: %5u rpcbind request timed out\n", task->tk_pid); goto retry_timeout; case -EPFNOSUPPORT: /* server doesn't support any rpcbind version we know of */ dprintk("RPC: %5u unrecognized remote rpcbind service\n", task->tk_pid); break; case -EPROTONOSUPPORT: dprintk("RPC: %5u remote rpcbind version unavailable, retrying\n", task->tk_pid); task->tk_status = 0; task->tk_action = call_bind; return; case -ECONNREFUSED: /* connection problems */ case -ECONNRESET: case -ENOTCONN: case -EHOSTDOWN: case -EHOSTUNREACH: case -ENETUNREACH: case -EPIPE: dprintk("RPC: %5u remote rpcbind unreachable: %d\n", task->tk_pid, task->tk_status); if (!RPC_IS_SOFTCONN(task)) { rpc_delay(task, 5*HZ); goto retry_timeout; } status = task->tk_status; break; default: dprintk("RPC: %5u unrecognized rpcbind error (%d)\n", task->tk_pid, -task->tk_status); } rpc_exit(task, status); return; retry_timeout: task->tk_action = call_timeout; }
166,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet) { char tmp[256]; struct dpc_ctx *ctx = c; switch (rr) { case RR_A: if (len != 4) return -1; ctx->addrs[ctx->cnt].scopeid = 0; memcpy(ctx->addrs[ctx->cnt++].addr, data, 4); break; case RR_AAAA: if (len != 16) return -1; ctx->addrs[ctx->cnt].family = AF_INET6; ctx->addrs[ctx->cnt].scopeid = 0; memcpy(ctx->addrs[ctx->cnt++].addr, data, 16); break; case RR_CNAME: if (__dn_expand(packet, (const unsigned char *)packet + 512, data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp)) strcpy(ctx->canon, tmp); break; } return 0; } Commit Message: CWE ID: CWE-119
static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet) { char tmp[256]; struct dpc_ctx *ctx = c; if (ctx->cnt >= MAXADDRS) return -1; switch (rr) { case RR_A: if (len != 4) return -1; ctx->addrs[ctx->cnt].scopeid = 0; memcpy(ctx->addrs[ctx->cnt++].addr, data, 4); break; case RR_AAAA: if (len != 16) return -1; ctx->addrs[ctx->cnt].family = AF_INET6; ctx->addrs[ctx->cnt].scopeid = 0; memcpy(ctx->addrs[ctx->cnt++].addr, data, 16); break; case RR_CNAME: if (__dn_expand(packet, (const unsigned char *)packet + 512, data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp)) strcpy(ctx->canon, tmp); break; } return 0; }
164,652
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void mk_request_free(struct session_request *sr) { if (sr->fd_file > 0) { mk_vhost_close(sr); } if (sr->headers.location) { mk_mem_free(sr->headers.location); } if (sr->uri_processed.data != sr->uri.data) { mk_ptr_free(&sr->uri_processed); } if (sr->real_path.data != sr->real_path_static) { mk_ptr_free(&sr->real_path); } } Commit Message: Request: new request session flag to mark those files opened by FDT This patch aims to fix a potential DDoS problem that can be caused in the server quering repetitive non-existent resources. When serving a static file, the core use Vhost FDT mechanism, but if it sends a static error page it does a direct open(2). When closing the resources for the same request it was just calling mk_vhost_close() which did not clear properly the file descriptor. This patch adds a new field on the struct session_request called 'fd_is_fdt', which contains MK_TRUE or MK_FALSE depending of how fd_file was opened. Thanks to Matthew Daley <mattd@bugfuzz.com> for report and troubleshoot this problem. Signed-off-by: Eduardo Silva <eduardo@monkey.io> CWE ID: CWE-20
void mk_request_free(struct session_request *sr) { if (sr->fd_file > 0) { if (sr->fd_is_fdt == MK_TRUE) { mk_vhost_close(sr); } else { close(sr->fd_file); } } if (sr->headers.location) { mk_mem_free(sr->headers.location); } if (sr->uri_processed.data != sr->uri.data) { mk_ptr_free(&sr->uri_processed); } if (sr->real_path.data != sr->real_path_static) { mk_ptr_free(&sr->real_path); } }
166,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: HRESULT WaitForLoginUIAndGetResult( CGaiaCredentialBase::UIProcessInfo* uiprocinfo, std::string* json_result, DWORD* exit_code, BSTR* status_text) { LOGFN(INFO); DCHECK(uiprocinfo); DCHECK(json_result); DCHECK(exit_code); DCHECK(status_text); const int kBufferSize = 4096; std::vector<char> output_buffer(kBufferSize, '\0'); base::ScopedClosureRunner zero_buffer_on_exit( base::BindOnce(base::IgnoreResult(&RtlSecureZeroMemory), &output_buffer[0], kBufferSize)); HRESULT hr = WaitForProcess(uiprocinfo->procinfo.process_handle(), uiprocinfo->parent_handles, exit_code, &output_buffer[0], kBufferSize); LOGFN(INFO) << "exit_code=" << exit_code; if (*exit_code == kUiecAbort) { LOGFN(ERROR) << "Aborted hr=" << putHR(hr); return E_ABORT; } else if (*exit_code != kUiecSuccess) { LOGFN(ERROR) << "Error hr=" << putHR(hr); *status_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); return E_FAIL; } *json_result = std::string(&output_buffer[0]); return S_OK; } Commit Message: [GCPW] Disallow sign in of consumer accounts when mdm is enabled. Unless the registry key "mdm_aca" is explicitly set to 1, always fail sign in of consumer accounts when mdm enrollment is enabled. Consumer accounts are defined as accounts with gmail.com or googlemail.com domain. Bug: 944049 Change-Id: Icb822f3737d90931de16a8d3317616dd2b159edd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1532903 Commit-Queue: Tien Mai <tienmai@chromium.org> Reviewed-by: Roger Tawa <rogerta@chromium.org> Cr-Commit-Position: refs/heads/master@{#646278} CWE ID: CWE-284
HRESULT WaitForLoginUIAndGetResult( CGaiaCredentialBase::UIProcessInfo* uiprocinfo, std::string* json_result, DWORD* exit_code, BSTR* status_text) { LOGFN(INFO); DCHECK(uiprocinfo); DCHECK(json_result); DCHECK(exit_code); DCHECK(status_text); const int kBufferSize = 4096; std::vector<char> output_buffer(kBufferSize, '\0'); base::ScopedClosureRunner zero_buffer_on_exit( base::BindOnce(base::IgnoreResult(&RtlSecureZeroMemory), &output_buffer[0], kBufferSize)); HRESULT hr = WaitForProcess(uiprocinfo->procinfo.process_handle(), uiprocinfo->parent_handles, exit_code, &output_buffer[0], kBufferSize); LOGFN(INFO) << "exit_code=" << *exit_code; if (*exit_code == kUiecAbort) { LOGFN(ERROR) << "Aborted hr=" << putHR(hr); return E_ABORT; } else if (*exit_code != kUiecSuccess) { LOGFN(ERROR) << "Error hr=" << putHR(hr); *status_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); return E_FAIL; } *json_result = std::string(&output_buffer[0]); return S_OK; }
172,102
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int sh_num) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = "statically"; const char *interp = ""; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = "dynamically"; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, ", invalid note alignment 0x%lx", (unsigned long)align) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } break; default: if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } /* Things we can determine when we seek */ switch (xph_type) { case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\0'; interp = (const char *)nbuf; } else interp = "*empty*"; break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, align, flags); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, ", %s linked", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, ", interpreter %s", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; return 0; } Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind. CWE ID: CWE-399
dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int sh_num, int *flags, uint16_t *notecount) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = "statically"; const char *interp = ""; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = "dynamically"; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, ", invalid note alignment 0x%lx", (unsigned long)align) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } break; default: if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } /* Things we can determine when we seek */ switch (xph_type) { case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\0'; interp = (const char *)nbuf; } else interp = "*empty*"; break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, align, flags, notecount); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, ", %s linked", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, ", interpreter %s", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; return 0; }
166,778
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jas_stream_gobble(jas_stream_t *stream, int n) { int m; m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
int jas_stream_gobble(jas_stream_t *stream, int n) { int m; if (n < 0) { jas_deprecated("negative count for jas_stream_gobble"); } m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; }
168,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_image_new(Jbig2Ctx *ctx, int width, int height) { Jbig2Image *image; int stride; int64_t check; image = jbig2_new(ctx, Jbig2Image, 1); if (image == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate image structure in jbig2_image_new"); return NULL; } stride = ((width - 1) >> 3) + 1; /* generate a byte-aligned stride */ /* check for integer multiplication overflow */ check = ((int64_t) stride) * ((int64_t) height); if (check != (int)check) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow from stride(%d)*height(%d)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } /* Add 1 to accept runs that exceed image width and clamped to width+1 */ image->data = jbig2_new(ctx, uint8_t, (int)check + 1); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate image data buffer! [stride(%d)*height(%d) bytes]", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->width = width; image->height = height; image->stride = stride; image->refcount = 1; return image; } Commit Message: CWE ID: CWE-119
jbig2_image_new(Jbig2Ctx *ctx, int width, int height) jbig2_image_new(Jbig2Ctx *ctx, uint32_t width, uint32_t height) { Jbig2Image *image; uint32_t stride; int64_t check; image = jbig2_new(ctx, Jbig2Image, 1); if (image == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate image structure in jbig2_image_new"); return NULL; } stride = ((width - 1) >> 3) + 1; /* generate a byte-aligned stride */ /* check for integer multiplication overflow */ check = ((int64_t) stride) * ((int64_t) height); if (check != (int)check) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow from stride(%d)*height(%d)", stride, height); jbig2_free(ctx->allocator, image); return NULL; } /* Add 1 to accept runs that exceed image width and clamped to width+1 */ image->data = jbig2_new(ctx, uint8_t, (int)check + 1); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not allocate image data buffer! [stride(%d)*height(%d) bytes]", stride, height); jbig2_free(ctx->allocator, image); return NULL; } image->width = width; image->height = height; image->stride = stride; image->refcount = 1; return image; }
165,491
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 OPENSSL_fork_child(void) { rand_fork(); } Commit Message: CWE ID: CWE-330
void OPENSSL_fork_child(void) { }
165,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Block::Frame& Block::GetFrame(int idx) const { assert(idx >= 0); assert(idx < m_frame_count); const Frame& f = m_frames[idx]; assert(f.pos > 0); assert(f.len > 0); return f; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Block::Frame& Block::GetFrame(int idx) const
174,324
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ixheaacd_esbr_radix4bfly(const WORD32 *w, WORD32 *x, WORD32 index1, WORD32 index) { int i; WORD32 l1, l2, h2, fft_jmp; WORD32 xt0_0, yt0_0, xt1_0, yt1_0, xt2_0, yt2_0; WORD32 xh0_0, xh1_0, xh20_0, xh21_0, xl0_0, xl1_0, xl20_0, xl21_0; WORD32 x_0, x_1, x_l1_0, x_l1_1, x_l2_0, x_l2_1; WORD32 x_h2_0, x_h2_1; WORD32 si10, si20, si30, co10, co20, co30; WORD64 mul_1, mul_2, mul_3, mul_4, mul_5, mul_6; WORD64 mul_7, mul_8, mul_9, mul_10, mul_11, mul_12; WORD32 *x_l1; WORD32 *x_l2; WORD32 *x_h2; const WORD32 *w_ptr = w; WORD32 i1; h2 = index << 1; l1 = index << 2; l2 = (index << 2) + (index << 1); x_l1 = &(x[l1]); x_l2 = &(x[l2]); x_h2 = &(x[h2]); fft_jmp = 6 * (index); for (i1 = 0; i1 < index1; i1++) { for (i = 0; i < index; i++) { si10 = (*w_ptr++); co10 = (*w_ptr++); si20 = (*w_ptr++); co20 = (*w_ptr++); si30 = (*w_ptr++); co30 = (*w_ptr++); x_0 = x[0]; x_h2_0 = x[h2]; x_l1_0 = x[l1]; x_l2_0 = x[l2]; xh0_0 = x_0 + x_l1_0; xl0_0 = x_0 - x_l1_0; xh20_0 = x_h2_0 + x_l2_0; xl20_0 = x_h2_0 - x_l2_0; x[0] = xh0_0 + xh20_0; xt0_0 = xh0_0 - xh20_0; x_1 = x[1]; x_h2_1 = x[h2 + 1]; x_l1_1 = x[l1 + 1]; x_l2_1 = x[l2 + 1]; xh1_0 = x_1 + x_l1_1; xl1_0 = x_1 - x_l1_1; xh21_0 = x_h2_1 + x_l2_1; xl21_0 = x_h2_1 - x_l2_1; x[1] = xh1_0 + xh21_0; yt0_0 = xh1_0 - xh21_0; xt1_0 = xl0_0 + xl21_0; xt2_0 = xl0_0 - xl21_0; yt2_0 = xl1_0 + xl20_0; yt1_0 = xl1_0 - xl20_0; mul_11 = ixheaacd_mult64(xt2_0, co30); mul_3 = ixheaacd_mult64(yt2_0, si30); x[l2] = (WORD32)((mul_3 + mul_11) >> 32) << RADIXSHIFT; mul_5 = ixheaacd_mult64(xt2_0, si30); mul_9 = ixheaacd_mult64(yt2_0, co30); x[l2 + 1] = (WORD32)((mul_9 - mul_5) >> 32) << RADIXSHIFT; mul_12 = ixheaacd_mult64(xt0_0, co20); mul_2 = ixheaacd_mult64(yt0_0, si20); x[l1] = (WORD32)((mul_2 + mul_12) >> 32) << RADIXSHIFT; mul_6 = ixheaacd_mult64(xt0_0, si20); mul_8 = ixheaacd_mult64(yt0_0, co20); x[l1 + 1] = (WORD32)((mul_8 - mul_6) >> 32) << RADIXSHIFT; mul_4 = ixheaacd_mult64(xt1_0, co10); mul_1 = ixheaacd_mult64(yt1_0, si10); x[h2] = (WORD32)((mul_1 + mul_4) >> 32) << RADIXSHIFT; mul_10 = ixheaacd_mult64(xt1_0, si10); mul_7 = ixheaacd_mult64(yt1_0, co10); x[h2 + 1] = (WORD32)((mul_7 - mul_10) >> 32) << RADIXSHIFT; x += 2; } x += fft_jmp; w_ptr = w_ptr - fft_jmp; } } Commit Message: Fix for stack corruption in esbr Bug: 110769924 Test: poc from bug before/after Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e (cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a) (cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50) CWE ID: CWE-787
VOID ixheaacd_esbr_radix4bfly(const WORD32 *w, WORD32 *x, WORD32 index1, WORD32 index) { int i; WORD32 l1, l2, h2, fft_jmp; WORD64 xt0_0, yt0_0, xt1_0, yt1_0, xt2_0, yt2_0; WORD64 xh0_0, xh1_0, xh20_0, xh21_0, xl0_0, xl1_0, xl20_0, xl21_0; WORD32 x_0, x_1, x_l1_0, x_l1_1, x_l2_0, x_l2_1; WORD32 x_h2_0, x_h2_1; WORD32 si10, si20, si30, co10, co20, co30; WORD64 mul_1, mul_2, mul_3, mul_4, mul_5, mul_6; WORD64 mul_7, mul_8, mul_9, mul_10, mul_11, mul_12; WORD32 *x_l1; WORD32 *x_l2; WORD32 *x_h2; const WORD32 *w_ptr = w; WORD32 i1; h2 = index << 1; l1 = index << 2; l2 = (index << 2) + (index << 1); x_l1 = &(x[l1]); x_l2 = &(x[l2]); x_h2 = &(x[h2]); fft_jmp = 6 * (index); for (i1 = 0; i1 < index1; i1++) { for (i = 0; i < index; i++) { si10 = (*w_ptr++); co10 = (*w_ptr++); si20 = (*w_ptr++); co20 = (*w_ptr++); si30 = (*w_ptr++); co30 = (*w_ptr++); x_0 = x[0]; x_h2_0 = x[h2]; x_l1_0 = x[l1]; x_l2_0 = x[l2]; xh0_0 = (WORD64)x_0 + (WORD64)x_l1_0; xl0_0 = (WORD64)x_0 - (WORD64)x_l1_0; xh20_0 = (WORD64)x_h2_0 + (WORD64)x_l2_0; xl20_0 = (WORD64)x_h2_0 - (WORD64)x_l2_0; x[0] = (WORD32)ixheaacd_add64_sat(xh0_0, xh20_0); xt0_0 = (WORD64)xh0_0 - (WORD64)xh20_0; x_1 = x[1]; x_h2_1 = x[h2 + 1]; x_l1_1 = x[l1 + 1]; x_l2_1 = x[l2 + 1]; xh1_0 = (WORD64)x_1 + (WORD64)x_l1_1; xl1_0 = (WORD64)x_1 - (WORD64)x_l1_1; xh21_0 = (WORD64)x_h2_1 + (WORD64)x_l2_1; xl21_0 = (WORD64)x_h2_1 - (WORD64)x_l2_1; x[1] = (WORD32)ixheaacd_add64_sat(xh1_0, xh21_0); yt0_0 = (WORD64)xh1_0 - (WORD64)xh21_0; xt1_0 = (WORD64)xl0_0 + (WORD64)xl21_0; xt2_0 = (WORD64)xl0_0 - (WORD64)xl21_0; yt2_0 = (WORD64)xl1_0 + (WORD64)xl20_0; yt1_0 = (WORD64)xl1_0 - (WORD64)xl20_0; mul_11 = ixheaacd_mult64(xt2_0, co30); mul_3 = ixheaacd_mult64(yt2_0, si30); x[l2] = (WORD32)((mul_3 + mul_11) >> 32) << RADIXSHIFT; mul_5 = ixheaacd_mult64(xt2_0, si30); mul_9 = ixheaacd_mult64(yt2_0, co30); x[l2 + 1] = (WORD32)((mul_9 - mul_5) >> 32) << RADIXSHIFT; mul_12 = ixheaacd_mult64(xt0_0, co20); mul_2 = ixheaacd_mult64(yt0_0, si20); x[l1] = (WORD32)((mul_2 + mul_12) >> 32) << RADIXSHIFT; mul_6 = ixheaacd_mult64(xt0_0, si20); mul_8 = ixheaacd_mult64(yt0_0, co20); x[l1 + 1] = (WORD32)((mul_8 - mul_6) >> 32) << RADIXSHIFT; mul_4 = ixheaacd_mult64(xt1_0, co10); mul_1 = ixheaacd_mult64(yt1_0, si10); x[h2] = (WORD32)((mul_1 + mul_4) >> 32) << RADIXSHIFT; mul_10 = ixheaacd_mult64(xt1_0, si10); mul_7 = ixheaacd_mult64(yt1_0, co10); x[h2 + 1] = (WORD32)((mul_7 - mul_10) >> 32) << RADIXSHIFT; x += 2; } x += fft_jmp; w_ptr = w_ptr - fft_jmp; } }
174,088
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height) { const uint8_t *frame_start = frame; const uint8_t *frame_end = frame + width * height; int mask = 0x10000, bitbuf = 0; int i, v, offset, count, segments; segments = bytestream2_get_le16(gb); while (segments--) { if (bytestream2_get_bytes_left(gb) < 2) return AVERROR_INVALIDDATA; if (mask == 0x10000) { bitbuf = bytestream2_get_le16u(gb); mask = 1; } if (bitbuf & mask) { v = bytestream2_get_le16(gb); offset = (v & 0x1FFF) << 2; count = ((v >> 13) + 2) << 1; if (frame - frame_start < offset || frame_end - frame < count*2 + width) return AVERROR_INVALIDDATA; for (i = 0; i < count; i++) { frame[0] = frame[1] = frame[width] = frame[width + 1] = frame[-offset]; frame += 2; } } else if (bitbuf & (mask << 1)) { v = bytestream2_get_le16(gb)*2; if (frame - frame_end < v) return AVERROR_INVALIDDATA; frame += v; } else { if (frame_end - frame < width + 3) return AVERROR_INVALIDDATA; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; } mask <<= 2; } return 0; } Commit Message: avcodec/dfa: Fix off by 1 error Fixes out of array access Fixes: 1345/clusterfuzz-testcase-minimized-6062963045695488 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-119
static int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height) { const uint8_t *frame_start = frame; const uint8_t *frame_end = frame + width * height; int mask = 0x10000, bitbuf = 0; int i, v, offset, count, segments; segments = bytestream2_get_le16(gb); while (segments--) { if (bytestream2_get_bytes_left(gb) < 2) return AVERROR_INVALIDDATA; if (mask == 0x10000) { bitbuf = bytestream2_get_le16u(gb); mask = 1; } if (bitbuf & mask) { v = bytestream2_get_le16(gb); offset = (v & 0x1FFF) << 2; count = ((v >> 13) + 2) << 1; if (frame - frame_start < offset || frame_end - frame < count*2 + width) return AVERROR_INVALIDDATA; for (i = 0; i < count; i++) { frame[0] = frame[1] = frame[width] = frame[width + 1] = frame[-offset]; frame += 2; } } else if (bitbuf & (mask << 1)) { v = bytestream2_get_le16(gb)*2; if (frame - frame_end < v) return AVERROR_INVALIDDATA; frame += v; } else { if (frame_end - frame < width + 4) return AVERROR_INVALIDDATA; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; frame[0] = frame[1] = frame[width] = frame[width + 1] = bytestream2_get_byte(gb); frame += 2; } mask <<= 2; } return 0; }
168,074
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 verify_source_vc(char **ret_path, const char *src_vc) { _cleanup_close_ int fd = -1; char *path; int r; fd = open_terminal(src_vc, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) return log_error_errno(fd, "Failed to open %s: %m", src_vc); r = verify_vc_device(fd); if (r < 0) return log_error_errno(r, "Device %s is not a virtual console: %m", src_vc); r = verify_vc_allocation_byfd(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not allocated: %m", src_vc); r = verify_vc_kbmode(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", src_vc); path = strdup(src_vc); if (!path) return log_oom(); *ret_path = path; return TAKE_FD(fd); } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255
static int verify_source_vc(char **ret_path, const char *src_vc) { _cleanup_close_ int fd = -1; char *path; int r; fd = open_terminal(src_vc, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) return log_error_errno(fd, "Failed to open %s: %m", src_vc); r = verify_vc_device(fd); if (r < 0) return log_error_errno(r, "Device %s is not a virtual console: %m", src_vc); r = verify_vc_allocation_byfd(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not allocated: %m", src_vc); r = vt_verify_kbmode(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", src_vc); path = strdup(src_vc); if (!path) return log_oom(); *ret_path = path; return TAKE_FD(fd); }
169,780
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MockRenderThread::MockRenderThread() : routing_id_(0), surface_id_(0), opener_id_(0) { } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
MockRenderThread::MockRenderThread() : routing_id_(0), surface_id_(0), opener_id_(0), new_window_routing_id_(0) { }
171,022
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AXLayoutObject::supportsARIADragging() const { const AtomicString& grabbed = getAttribute(aria_grabbedAttr); return equalIgnoringCase(grabbed, "true") || equalIgnoringCase(grabbed, "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 AXLayoutObject::supportsARIADragging() const { const AtomicString& grabbed = getAttribute(aria_grabbedAttr); return equalIgnoringASCIICase(grabbed, "true") || equalIgnoringASCIICase(grabbed, "false"); }
171,906
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 filter_frame(AVFilterLink *inlink, AVFrame *in) { GradFunContext *s = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int p, direct; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { direct = 0; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } for (p = 0; p < 4 && in->data[p]; p++) { int w = inlink->w; int h = inlink->h; int r = s->radius; if (p) { w = s->chroma_w; h = s->chroma_h; r = s->chroma_r; } if (FFMIN(w, h) > 2 * r) filter(s, out->data[p], in->data[p], w, h, out->linesize[p], in->linesize[p], r); else if (out->data[p] != in->data[p]) av_image_copy_plane(out->data[p], out->linesize[p], in->data[p], in->linesize[p], w, h); } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID: CWE-119
static int filter_frame(AVFilterLink *inlink, AVFrame *in) { GradFunContext *s = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int p, direct; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { direct = 0; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } for (p = 0; p < 4 && in->data[p] && in->linesize[p]; p++) { int w = inlink->w; int h = inlink->h; int r = s->radius; if (p) { w = s->chroma_w; h = s->chroma_h; r = s->chroma_r; } if (FFMIN(w, h) > 2 * r) filter(s, out->data[p], in->data[p], w, h, out->linesize[p], in->linesize[p], r); else if (out->data[p] != in->data[p]) av_image_copy_plane(out->data[p], out->linesize[p], in->data[p], in->linesize[p], w, h); } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); }
166,001
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CL_InitRef( void ) { refimport_t ri; refexport_t *ret; #ifdef USE_RENDERER_DLOPEN GetRefAPI_t GetRefAPI; char dllName[MAX_OSPATH]; #endif Com_Printf( "----- Initializing Renderer ----\n" ); #ifdef USE_RENDERER_DLOPEN cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH); Com_sprintf(dllName, sizeof(dllName), "renderer_mp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string); if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Cvar_ForceReset("cl_renderer"); Com_sprintf(dllName, sizeof(dllName), "renderer_mp_opengl1_" ARCH_STRING DLL_EXT); rendererLib = Sys_LoadDll(dllName, qfalse); } if(!rendererLib) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Com_Error(ERR_FATAL, "Failed to load renderer"); } GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI"); if(!GetRefAPI) { Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); } #endif ri.Cmd_AddCommand = Cmd_AddCommand; ri.Cmd_RemoveCommand = Cmd_RemoveCommand; ri.Cmd_Argc = Cmd_Argc; ri.Cmd_Argv = Cmd_Argv; ri.Cmd_ExecuteText = Cbuf_ExecuteText; ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.Milliseconds = CL_ScaledMilliseconds; #ifdef ZONE_DEBUG ri.Z_MallocDebug = CL_RefMallocDebug; #else ri.Z_Malloc = CL_RefMalloc; #endif ri.Free = Z_Free; ri.Tag_Free = CL_RefTagFree; ri.Hunk_Clear = Hunk_ClearToMark; #ifdef HUNK_DEBUG ri.Hunk_AllocDebug = Hunk_AllocDebug; #else ri.Hunk_Alloc = Hunk_Alloc; #endif ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.CM_ClusterPVS = CM_ClusterPVS; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; ri.FS_ReadFile = FS_ReadFile; ri.FS_FreeFile = FS_FreeFile; ri.FS_WriteFile = FS_WriteFile; ri.FS_FreeFileList = FS_FreeFileList; ri.FS_ListFiles = FS_ListFiles; ri.FS_FileIsInPAK = FS_FileIsInPAK; ri.FS_FileExists = FS_FileExists; ri.Cvar_Get = Cvar_Get; ri.Cvar_Set = Cvar_Set; ri.Cvar_SetValue = Cvar_SetValue; ri.Cvar_CheckRange = Cvar_CheckRange; ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; ri.CIN_UploadCinematic = CIN_UploadCinematic; ri.CIN_PlayCinematic = CIN_PlayCinematic; ri.CIN_RunCinematic = CIN_RunCinematic; ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; ri.IN_Init = IN_Init; ri.IN_Shutdown = IN_Shutdown; ri.IN_Restart = IN_Restart; ri.ftol = Q_ftol; ri.Sys_SetEnv = Sys_SetEnv; ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; ri.Sys_GLimpInit = Sys_GLimpInit; ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; ret = GetRefAPI( REF_API_VERSION, &ri ); if ( !ret ) { Com_Error( ERR_FATAL, "Couldn't initialize refresh" ); } re = *ret; Com_Printf( "---- Renderer Initialization Complete ----\n" ); Cvar_Set( "cl_paused", "0" ); } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
void CL_InitRef( void ) { refimport_t ri; refexport_t *ret; #ifdef USE_RENDERER_DLOPEN GetRefAPI_t GetRefAPI; char dllName[MAX_OSPATH]; #endif Com_Printf( "----- Initializing Renderer ----\n" ); #ifdef USE_RENDERER_DLOPEN cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED); Com_sprintf(dllName, sizeof(dllName), "renderer_mp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string); if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Cvar_ForceReset("cl_renderer"); Com_sprintf(dllName, sizeof(dllName), "renderer_mp_opengl1_" ARCH_STRING DLL_EXT); rendererLib = Sys_LoadDll(dllName, qfalse); } if(!rendererLib) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Com_Error(ERR_FATAL, "Failed to load renderer"); } GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI"); if(!GetRefAPI) { Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); } #endif ri.Cmd_AddCommand = Cmd_AddCommand; ri.Cmd_RemoveCommand = Cmd_RemoveCommand; ri.Cmd_Argc = Cmd_Argc; ri.Cmd_Argv = Cmd_Argv; ri.Cmd_ExecuteText = Cbuf_ExecuteText; ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.Milliseconds = CL_ScaledMilliseconds; #ifdef ZONE_DEBUG ri.Z_MallocDebug = CL_RefMallocDebug; #else ri.Z_Malloc = CL_RefMalloc; #endif ri.Free = Z_Free; ri.Tag_Free = CL_RefTagFree; ri.Hunk_Clear = Hunk_ClearToMark; #ifdef HUNK_DEBUG ri.Hunk_AllocDebug = Hunk_AllocDebug; #else ri.Hunk_Alloc = Hunk_Alloc; #endif ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.CM_ClusterPVS = CM_ClusterPVS; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; ri.FS_ReadFile = FS_ReadFile; ri.FS_FreeFile = FS_FreeFile; ri.FS_WriteFile = FS_WriteFile; ri.FS_FreeFileList = FS_FreeFileList; ri.FS_ListFiles = FS_ListFiles; ri.FS_FileIsInPAK = FS_FileIsInPAK; ri.FS_FileExists = FS_FileExists; ri.Cvar_Get = Cvar_Get; ri.Cvar_Set = Cvar_Set; ri.Cvar_SetValue = Cvar_SetValue; ri.Cvar_CheckRange = Cvar_CheckRange; ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; ri.CIN_UploadCinematic = CIN_UploadCinematic; ri.CIN_PlayCinematic = CIN_PlayCinematic; ri.CIN_RunCinematic = CIN_RunCinematic; ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; ri.IN_Init = IN_Init; ri.IN_Shutdown = IN_Shutdown; ri.IN_Restart = IN_Restart; ri.ftol = Q_ftol; ri.Sys_SetEnv = Sys_SetEnv; ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; ri.Sys_GLimpInit = Sys_GLimpInit; ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; ret = GetRefAPI( REF_API_VERSION, &ri ); if ( !ret ) { Com_Error( ERR_FATAL, "Couldn't initialize refresh" ); } re = *ret; Com_Printf( "---- Renderer Initialization Complete ----\n" ); Cvar_Set( "cl_paused", "0" ); }
170,082
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InitSkBitmapDataForTransfer(const SkBitmap& bitmap) { const SkImageInfo& info = bitmap.info(); color_type = info.colorType(); alpha_type = info.alphaType(); width = info.width(); height = info.height(); } Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices. Using memcpy() to serialize a POD struct is highly discouraged. Just use the standard IPC param traits macros for doing it. Bug: 779428 Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334 Reviewed-on: https://chromium-review.googlesource.com/899649 Reviewed-by: Tom Sepez <tsepez@chromium.org> Commit-Queue: Daniel Cheng <dcheng@chromium.org> Cr-Commit-Position: refs/heads/master@{#534562} CWE ID: CWE-125
void InitSkBitmapDataForTransfer(const SkBitmap& bitmap) {
172,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 copyMultiCh24(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i] >> 8; } } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyMultiCh24(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) static void copyMultiCh24(short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i] >> 8; } } }
174,019
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_increment_retval_error (MyObject *obj, gint32 x, GError **error) { if (x + 1 > 10) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "%s", "x is bigger than 9"); return FALSE; } return x + 1; } Commit Message: CWE ID: CWE-264
my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error)
165,107
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserMainParts::PostMainMessageLoopRun() { CompositorUtils::GetInstance()->Shutdown(); } Commit Message: CWE ID: CWE-20
void BrowserMainParts::PostMainMessageLoopRun() { WebContentsUnloader::GetInstance()->Shutdown(); BrowserContextDestroyer::Shutdown(); BrowserContext::AssertNoContextsExist(); CompositorUtils::GetInstance()->Shutdown(); }
165,423
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionTtsController::GetMatchingExtensionId( Utterance* utterance) { ExtensionService* service = utterance->profile()->GetExtensionService(); DCHECK(service); ExtensionEventRouter* event_router = utterance->profile()->GetExtensionEventRouter(); DCHECK(event_router); const ExtensionList* extensions = service->extensions(); ExtensionList::const_iterator iter; for (iter = extensions->begin(); iter != extensions->end(); ++iter) { const Extension* extension = *iter; if (!event_router->ExtensionHasEventListener( extension->id(), events::kOnSpeak) || !event_router->ExtensionHasEventListener( extension->id(), events::kOnStop)) { continue; } const std::vector<Extension::TtsVoice>& tts_voices = extension->tts_voices(); for (size_t i = 0; i < tts_voices.size(); ++i) { const Extension::TtsVoice& voice = tts_voices[i]; if (!voice.voice_name.empty() && !utterance->voice_name().empty() && voice.voice_name != utterance->voice_name()) { continue; } if (!voice.locale.empty() && !utterance->locale().empty() && voice.locale != utterance->locale()) { continue; } if (!voice.gender.empty() && !utterance->gender().empty() && voice.gender != utterance->gender()) { continue; } return extension->id(); } } return std::string(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
std::string ExtensionTtsController::GetMatchingExtensionId( double rate = 1.0; if (options->HasKey(constants::kRateKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetDouble(constants::kRateKey, &rate)); if (rate < 0.1 || rate > 10.0) { error_ = constants::kErrorInvalidRate; return false; }
170,380
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RilSapSocket::sendDisconnect() { size_t encoded_size = 0; uint32_t written_size; size_t buffer_size = 0; pb_ostream_t ostream; bool success = false; RIL_SIM_SAP_DISCONNECT_REQ disconnectReq; if ((success = pb_get_encoded_size(&encoded_size, RIL_SIM_SAP_DISCONNECT_REQ_fields, &disconnectReq)) && encoded_size <= INT32_MAX) { buffer_size = encoded_size + sizeof(uint32_t); uint8_t buffer[buffer_size]; written_size = htonl((uint32_t) encoded_size); ostream = pb_ostream_from_buffer(buffer, buffer_size); pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size)); success = pb_encode(&ostream, RIL_SIM_SAP_DISCONNECT_REQ_fields, buffer); if(success) { pb_bytes_array_t *payload = (pb_bytes_array_t *)calloc(1, sizeof(pb_bytes_array_t) + written_size); if (!payload) { RLOGE("sendDisconnect: OOM"); return; } memcpy(payload->bytes, buffer, written_size); payload->size = written_size; MsgHeader *hdr = (MsgHeader *)malloc(sizeof(MsgHeader)); if (!hdr) { RLOGE("sendDisconnect: OOM"); free(payload); return; } hdr->payload = payload; hdr->type = MsgType_REQUEST; hdr->id = MsgId_RIL_SIM_SAP_DISCONNECT; hdr->error = Error_RIL_E_SUCCESS; dispatchDisconnect(hdr); } else { RLOGE("Encode failed in send disconnect!"); } } } Commit Message: Replace variable-length arrays on stack with malloc. Bug: 30202619 Change-Id: Ib95e08a1c009d88a4b4fd8d8fdba0641c6129008 (cherry picked from commit 943905bb9f99e3caa856b42c531e2be752da8834) CWE ID: CWE-264
void RilSapSocket::sendDisconnect() { size_t encoded_size = 0; uint32_t written_size; size_t buffer_size = 0; pb_ostream_t ostream; bool success = false; RIL_SIM_SAP_DISCONNECT_REQ disconnectReq; if ((success = pb_get_encoded_size(&encoded_size, RIL_SIM_SAP_DISCONNECT_REQ_fields, &disconnectReq)) && encoded_size <= INT32_MAX) { buffer_size = encoded_size + sizeof(uint32_t); uint8_t* buffer = (uint8_t*)malloc(buffer_size); if (!buffer) { RLOGE("sendDisconnect: OOM"); return; } written_size = htonl((uint32_t) encoded_size); ostream = pb_ostream_from_buffer(buffer, buffer_size); pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size)); success = pb_encode(&ostream, RIL_SIM_SAP_DISCONNECT_REQ_fields, buffer); if(success) { pb_bytes_array_t *payload = (pb_bytes_array_t *)calloc(1, sizeof(pb_bytes_array_t) + written_size); if (!payload) { RLOGE("sendDisconnect: OOM"); return; } memcpy(payload->bytes, buffer, written_size); payload->size = written_size; MsgHeader *hdr = (MsgHeader *)malloc(sizeof(MsgHeader)); if (!hdr) { RLOGE("sendDisconnect: OOM"); free(payload); return; } hdr->payload = payload; hdr->type = MsgType_REQUEST; hdr->id = MsgId_RIL_SIM_SAP_DISCONNECT; hdr->error = Error_RIL_E_SUCCESS; dispatchDisconnect(hdr); } else { RLOGE("Encode failed in send disconnect!"); } free(buffer); } }
173,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_get_int_32(png_bytep buf) { png_int_32 i = ((png_int_32)(*buf) << 24) + ((png_int_32)(*(buf + 1)) << 16) + ((png_int_32)(*(buf + 2)) << 8) + (png_int_32)(*(buf + 3)); return (i); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_int_32(png_bytep buf) { png_int_32 i = ((png_int_32)((*(buf )) & 0xff) << 24) + ((png_int_32)((*(buf + 1)) & 0xff) << 16) + ((png_int_32)((*(buf + 2)) & 0xff) << 8) + ((png_int_32)((*(buf + 3)) & 0xff) ); return (i); }
172,173
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 filter_frame(AVFilterLink *inlink, AVFrame *in) { unsigned x, y; AVFilterContext *ctx = inlink->dst; VignetteContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); if (s->eval_mode == EVAL_MODE_FRAME) update_context(s, inlink, in); if (s->desc->flags & AV_PIX_FMT_FLAG_RGB) { uint8_t *dst = out->data[0]; const uint8_t *src = in ->data[0]; const float *fmap = s->fmap; const int dst_linesize = out->linesize[0]; const int src_linesize = in ->linesize[0]; const int fmap_linesize = s->fmap_linesize; for (y = 0; y < inlink->h; y++) { uint8_t *dstp = dst; const uint8_t *srcp = src; for (x = 0; x < inlink->w; x++, dstp += 3, srcp += 3) { const float f = fmap[x]; dstp[0] = av_clip_uint8(srcp[0] * f + get_dither_value(s)); dstp[1] = av_clip_uint8(srcp[1] * f + get_dither_value(s)); dstp[2] = av_clip_uint8(srcp[2] * f + get_dither_value(s)); } dst += dst_linesize; src += src_linesize; fmap += fmap_linesize; } } else { int plane; for (plane = 0; plane < 4 && in->data[plane]; plane++) { uint8_t *dst = out->data[plane]; const uint8_t *src = in ->data[plane]; const float *fmap = s->fmap; const int dst_linesize = out->linesize[plane]; const int src_linesize = in ->linesize[plane]; const int fmap_linesize = s->fmap_linesize; const int chroma = plane == 1 || plane == 2; const int hsub = chroma ? s->desc->log2_chroma_w : 0; const int vsub = chroma ? s->desc->log2_chroma_h : 0; const int w = FF_CEIL_RSHIFT(inlink->w, hsub); const int h = FF_CEIL_RSHIFT(inlink->h, vsub); for (y = 0; y < h; y++) { uint8_t *dstp = dst; const uint8_t *srcp = src; for (x = 0; x < w; x++) { const double dv = get_dither_value(s); if (chroma) *dstp++ = av_clip_uint8(fmap[x << hsub] * (*srcp++ - 127) + 127 + dv); else *dstp++ = av_clip_uint8(fmap[x ] * *srcp++ + dv); } dst += dst_linesize; src += src_linesize; fmap += fmap_linesize << vsub; } } } return ff_filter_frame(outlink, out); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID: CWE-119
static int filter_frame(AVFilterLink *inlink, AVFrame *in) { unsigned x, y; AVFilterContext *ctx = inlink->dst; VignetteContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); if (s->eval_mode == EVAL_MODE_FRAME) update_context(s, inlink, in); if (s->desc->flags & AV_PIX_FMT_FLAG_RGB) { uint8_t *dst = out->data[0]; const uint8_t *src = in ->data[0]; const float *fmap = s->fmap; const int dst_linesize = out->linesize[0]; const int src_linesize = in ->linesize[0]; const int fmap_linesize = s->fmap_linesize; for (y = 0; y < inlink->h; y++) { uint8_t *dstp = dst; const uint8_t *srcp = src; for (x = 0; x < inlink->w; x++, dstp += 3, srcp += 3) { const float f = fmap[x]; dstp[0] = av_clip_uint8(srcp[0] * f + get_dither_value(s)); dstp[1] = av_clip_uint8(srcp[1] * f + get_dither_value(s)); dstp[2] = av_clip_uint8(srcp[2] * f + get_dither_value(s)); } dst += dst_linesize; src += src_linesize; fmap += fmap_linesize; } } else { int plane; for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) { uint8_t *dst = out->data[plane]; const uint8_t *src = in ->data[plane]; const float *fmap = s->fmap; const int dst_linesize = out->linesize[plane]; const int src_linesize = in ->linesize[plane]; const int fmap_linesize = s->fmap_linesize; const int chroma = plane == 1 || plane == 2; const int hsub = chroma ? s->desc->log2_chroma_w : 0; const int vsub = chroma ? s->desc->log2_chroma_h : 0; const int w = FF_CEIL_RSHIFT(inlink->w, hsub); const int h = FF_CEIL_RSHIFT(inlink->h, vsub); for (y = 0; y < h; y++) { uint8_t *dstp = dst; const uint8_t *srcp = src; for (x = 0; x < w; x++) { const double dv = get_dither_value(s); if (chroma) *dstp++ = av_clip_uint8(fmap[x << hsub] * (*srcp++ - 127) + 127 + dv); else *dstp++ = av_clip_uint8(fmap[x ] * *srcp++ + dv); } dst += dst_linesize; src += src_linesize; fmap += fmap_linesize << vsub; } } } return ff_filter_frame(outlink, out); }
166,008
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssl3_ctrl(SSL *s, int cmd, long larg, void *parg) { int ret = 0; #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_RSA) if ( # ifndef OPENSSL_NO_RSA cmd == SSL_CTRL_SET_TMP_RSA || cmd == SSL_CTRL_SET_TMP_RSA_CB || # endif # ifndef OPENSSL_NO_DSA cmd == SSL_CTRL_SET_TMP_DH || cmd == SSL_CTRL_SET_TMP_DH_CB || # endif 0) { if (!ssl_cert_inst(&s->cert)) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_MALLOC_FAILURE); return (0); } } #endif switch (cmd) { case SSL_CTRL_GET_SESSION_REUSED: ret = s->hit; break; case SSL_CTRL_GET_CLIENT_CERT_REQUEST: break; case SSL_CTRL_GET_NUM_RENEGOTIATIONS: ret = s->s3->num_renegotiations; break; case SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS: ret = s->s3->num_renegotiations; s->s3->num_renegotiations = 0; break; case SSL_CTRL_GET_TOTAL_RENEGOTIATIONS: ret = s->s3->total_renegotiations; break; case SSL_CTRL_GET_FLAGS: ret = (int)(s->s3->flags); break; #ifndef OPENSSL_NO_RSA case SSL_CTRL_NEED_TMP_RSA: if ((s->cert != NULL) && (s->cert->rsa_tmp == NULL) && ((s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) || (EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) > (512 / 8)))) ret = 1; break; case SSL_CTRL_SET_TMP_RSA: { RSA *rsa = (RSA *)parg; if (rsa == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return (ret); } if ((rsa = RSAPrivateKey_dup(rsa)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_RSA_LIB); return (ret); } if (s->cert->rsa_tmp != NULL) RSA_free(s->cert->rsa_tmp); s->cert->rsa_tmp = rsa; ret = 1; } break; case SSL_CTRL_SET_TMP_RSA_CB: { SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return (ret); } break; #endif #ifndef OPENSSL_NO_DH case SSL_CTRL_SET_TMP_DH: { DH *dh = (DH *)parg; if (dh == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return (ret); } if ((dh = DHparams_dup(dh)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return (ret); } if (!(s->options & SSL_OP_SINGLE_DH_USE)) { if (!DH_generate_key(dh)) { DH_free(dh); SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return (ret); } } if (s->cert->dh_tmp != NULL) DH_free(s->cert->dh_tmp); s->cert->dh_tmp = dh; SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return (ret); } } if (s->cert->dh_tmp != NULL) DH_free(s->cert->dh_tmp); s->cert->dh_tmp = dh; ret = 1; } Commit Message: CWE ID: CWE-200
long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg) { int ret = 0; #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_RSA) if ( # ifndef OPENSSL_NO_RSA cmd == SSL_CTRL_SET_TMP_RSA || cmd == SSL_CTRL_SET_TMP_RSA_CB || # endif # ifndef OPENSSL_NO_DSA cmd == SSL_CTRL_SET_TMP_DH || cmd == SSL_CTRL_SET_TMP_DH_CB || # endif 0) { if (!ssl_cert_inst(&s->cert)) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_MALLOC_FAILURE); return (0); } } #endif switch (cmd) { case SSL_CTRL_GET_SESSION_REUSED: ret = s->hit; break; case SSL_CTRL_GET_CLIENT_CERT_REQUEST: break; case SSL_CTRL_GET_NUM_RENEGOTIATIONS: ret = s->s3->num_renegotiations; break; case SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS: ret = s->s3->num_renegotiations; s->s3->num_renegotiations = 0; break; case SSL_CTRL_GET_TOTAL_RENEGOTIATIONS: ret = s->s3->total_renegotiations; break; case SSL_CTRL_GET_FLAGS: ret = (int)(s->s3->flags); break; #ifndef OPENSSL_NO_RSA case SSL_CTRL_NEED_TMP_RSA: if ((s->cert != NULL) && (s->cert->rsa_tmp == NULL) && ((s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) || (EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) > (512 / 8)))) ret = 1; break; case SSL_CTRL_SET_TMP_RSA: { RSA *rsa = (RSA *)parg; if (rsa == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return (ret); } if ((rsa = RSAPrivateKey_dup(rsa)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_RSA_LIB); return (ret); } if (s->cert->rsa_tmp != NULL) RSA_free(s->cert->rsa_tmp); s->cert->rsa_tmp = rsa; ret = 1; } break; case SSL_CTRL_SET_TMP_RSA_CB: { SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return (ret); } break; #endif #ifndef OPENSSL_NO_DH case SSL_CTRL_SET_TMP_DH: { DH *dh = (DH *)parg; if (dh == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return (ret); } if ((dh = DHparams_dup(dh)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return (ret); } if (s->cert->dh_tmp != NULL) DH_free(s->cert->dh_tmp); s->cert->dh_tmp = dh; SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return (ret); } } if (s->cert->dh_tmp != NULL) DH_free(s->cert->dh_tmp); s->cert->dh_tmp = dh; ret = 1; }
165,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: CuePoint::CuePoint(long idx, long long pos) : m_element_start(0), m_element_size(0), m_index(idx), m_timecode(-1 * pos), m_track_positions(NULL), m_track_positions_count(0) { assert(pos > 0); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
CuePoint::CuePoint(long idx, long long pos) : CuePoint::CuePoint(long idx, long long pos) : m_element_start(0), m_element_size(0), m_index(idx), m_timecode(-1 * pos), m_track_positions(NULL), m_track_positions_count(0) { assert(pos > 0); }
174,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\0'; dest = src = a->name; if (*src == '\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') { if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path is absolute"); return (ARCHIVE_FAILED); } separator = *src++; } /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); } Commit Message: Fixes for Issue #745 and Issue #746 from Doran Moppert. CWE ID: CWE-20
cleanup_pathname(struct archive_write_disk *a) cleanup_pathname_fsobj(char *path, int *error_number, struct archive_string *error_string, int flags) { char *dest, *src; char separator = '\0'; dest = src = path; if (*src == '\0') { if (error_number) *error_number = ARCHIVE_ERRNO_MISC; if (error_string) archive_string_sprintf(error_string, "Invalid empty pathname"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') { if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { if (error_number) *error_number = ARCHIVE_ERRNO_MISC; if (error_string) archive_string_sprintf(error_string, "Path is absolute"); return (ARCHIVE_FAILED); } separator = *src++; } /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\0') { /* Conditionally warn about '..' */ if (flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { if (error_number) *error_number = ARCHIVE_ERRNO_MISC; if (error_string) archive_string_sprintf(error_string, "Path contains '..'"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\0' && *src != '/') { *dest++ = *src++; } if (*src == '\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == path) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\0'; return (ARCHIVE_OK); }
167,136
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::wstring GetSwitchValueFromCommandLine(const std::wstring& command_line, const std::wstring& switch_name) { assert(!command_line.empty()); assert(!switch_name.empty()); std::vector<std::wstring> as_array = TokenizeCommandLineToArray(command_line); std::wstring switch_with_equal = L"--" + switch_name + L"="; for (size_t i = 1; i < as_array.size(); ++i) { const std::wstring& arg = as_array[i]; if (arg.compare(0, switch_with_equal.size(), switch_with_equal) == 0) return arg.substr(switch_with_equal.size()); } return std::wstring(); } Commit Message: Ignore switches following "--" when parsing a command line. BUG=933004 R=wfh@chromium.org Change-Id: I911be4cbfc38a4d41dec85d85f7fe0f50ddca392 Reviewed-on: https://chromium-review.googlesource.com/c/1481210 Auto-Submit: Greg Thompson <grt@chromium.org> Commit-Queue: Julian Pastarmov <pastarmovj@chromium.org> Reviewed-by: Julian Pastarmov <pastarmovj@chromium.org> Cr-Commit-Position: refs/heads/master@{#634604} CWE ID: CWE-77
std::wstring GetSwitchValueFromCommandLine(const std::wstring& command_line, const std::wstring& switch_name) { static constexpr wchar_t kSwitchTerminator[] = L"--"; assert(!command_line.empty()); assert(!switch_name.empty()); std::vector<std::wstring> as_array = TokenizeCommandLineToArray(command_line); std::wstring switch_with_equal = L"--" + switch_name + L"="; auto end = std::find(as_array.cbegin(), as_array.cend(), kSwitchTerminator); for (auto scan = as_array.cbegin(); scan != end; ++scan) { const std::wstring& arg = *scan; if (arg.compare(0, switch_with_equal.size(), switch_with_equal) == 0) return arg.substr(switch_with_equal.size()); } return std::wstring(); }
173,062
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(mcrypt_get_block_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_block_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_get_block_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_block_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } }
167,104
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_write_finish_row(png_structp png_ptr) { #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif int ret; png_debug(1, "in png_write_finish_row"); /* Next row */ png_ptr->row_number++; /* See if we are done */ if (png_ptr->row_number < png_ptr->num_rows) return; #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* If interlaced, go to next pass */ if (png_ptr->interlaced) { png_ptr->row_number = 0; if (png_ptr->transformations & PNG_INTERLACE) { png_ptr->pass++; } else { /* Loop until we find a non-zero width or height pass */ do { png_ptr->pass++; if (png_ptr->pass >= 7) break; png_ptr->usr_width = (png_ptr->width + png_pass_inc[png_ptr->pass] - 1 - png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; png_ptr->num_rows = (png_ptr->height + png_pass_yinc[png_ptr->pass] - 1 - png_pass_ystart[png_ptr->pass]) / png_pass_yinc[png_ptr->pass]; if (png_ptr->transformations & PNG_INTERLACE) break; } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0); } /* Reset the row above the image for the next pass */ if (png_ptr->pass < 7) { if (png_ptr->prev_row != NULL) png_memset(png_ptr->prev_row, 0, (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels* png_ptr->usr_bit_depth, png_ptr->width)) + 1); return; } } #endif /* If we get here, we've just written the last row, so we need to flush the compressor */ do { /* Tell the compressor we are done */ ret = deflate(&png_ptr->zstream, Z_FINISH); /* Check for an error */ if (ret == Z_OK) { /* Check to see if we need more room */ if (!(png_ptr->zstream.avail_out)) { png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size); png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; } } else if (ret != Z_STREAM_END) { if (png_ptr->zstream.msg != NULL) png_error(png_ptr, png_ptr->zstream.msg); else png_error(png_ptr, "zlib error"); } } while (ret != Z_STREAM_END); /* Write any extra space */ if (png_ptr->zstream.avail_out < png_ptr->zbuf_size) { png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size - png_ptr->zstream.avail_out); } deflateReset(&png_ptr->zstream); png_ptr->zstream.data_type = Z_BINARY; } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_write_finish_row(png_structp png_ptr) { #ifdef PNG_WRITE_INTERLACING_SUPPORTED #ifndef PNG_USE_GLOBAL_ARRAYS /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; #endif #endif int ret; png_debug(1, "in png_write_finish_row"); /* Next row */ png_ptr->row_number++; /* See if we are done */ if (png_ptr->row_number < png_ptr->num_rows) return; #ifdef PNG_WRITE_INTERLACING_SUPPORTED /* If interlaced, go to next pass */ if (png_ptr->interlaced) { png_ptr->row_number = 0; if (png_ptr->transformations & PNG_INTERLACE) { png_ptr->pass++; } else { /* Loop until we find a non-zero width or height pass */ do { png_ptr->pass++; if (png_ptr->pass >= 7) break; png_ptr->usr_width = (png_ptr->width + png_pass_inc[png_ptr->pass] - 1 - png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; png_ptr->num_rows = (png_ptr->height + png_pass_yinc[png_ptr->pass] - 1 - png_pass_ystart[png_ptr->pass]) / png_pass_yinc[png_ptr->pass]; if (png_ptr->transformations & PNG_INTERLACE) break; } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0); } /* Reset the row above the image for the next pass */ if (png_ptr->pass < 7) { if (png_ptr->prev_row != NULL) png_memset(png_ptr->prev_row, 0, (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels* png_ptr->usr_bit_depth, png_ptr->width)) + 1); return; } } #endif /* If we get here, we've just written the last row, so we need to flush the compressor */ do { /* Tell the compressor we are done */ ret = deflate(&png_ptr->zstream, Z_FINISH); /* Check for an error */ if (ret == Z_OK) { /* Check to see if we need more room */ if (!(png_ptr->zstream.avail_out)) { png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size); png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; } } else if (ret != Z_STREAM_END) { if (png_ptr->zstream.msg != NULL) png_error(png_ptr, png_ptr->zstream.msg); else png_error(png_ptr, "zlib error"); } } while (ret != Z_STREAM_END); /* Write any extra space */ if (png_ptr->zstream.avail_out < png_ptr->zbuf_size) { png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size - png_ptr->zstream.avail_out); } deflateReset(&png_ptr->zstream); png_ptr->zstream.data_type = Z_BINARY; }
172,195
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_mb_regex_free_cache(php_mb_regex_t **pre) { onig_free(*pre); } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
static void php_mb_regex_free_cache(php_mb_regex_t **pre) static void php_mb_regex_free_cache(php_mb_regex_t **pre) { onig_free(*pre); }
167,122
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftVideoDecoderOMXComponent::getConfig( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexConfigCommonOutputCrop: { OMX_CONFIG_RECTTYPE *rectParams = (OMX_CONFIG_RECTTYPE *)params; if (rectParams->nPortIndex != kOutputPortIndex) { return OMX_ErrorUndefined; } rectParams->nLeft = mCropLeft; rectParams->nTop = mCropTop; rectParams->nWidth = mCropWidth; rectParams->nHeight = mCropHeight; return OMX_ErrorNone; } default: return OMX_ErrorUnsupportedIndex; } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftVideoDecoderOMXComponent::getConfig( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexConfigCommonOutputCrop: { OMX_CONFIG_RECTTYPE *rectParams = (OMX_CONFIG_RECTTYPE *)params; if (!isValidOMXParam(rectParams)) { return OMX_ErrorBadParameter; } if (rectParams->nPortIndex != kOutputPortIndex) { return OMX_ErrorUndefined; } rectParams->nLeft = mCropLeft; rectParams->nTop = mCropTop; rectParams->nWidth = mCropWidth; rectParams->nHeight = mCropHeight; return OMX_ErrorNone; } default: return OMX_ErrorUnsupportedIndex; } }
174,224
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InputMethodDescriptor previous_input_method() const { if (previous_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return previous_input_method_; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual InputMethodDescriptor previous_input_method() const { virtual input_method::InputMethodDescriptor previous_input_method() const { if (previous_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return previous_input_method_; }
170,514
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void start_daemon() { struct usb_sock_t *usb_sock; if (g_options.noprinter_mode == 0) { usb_sock = usb_open(); if (usb_sock == NULL) goto cleanup_usb; } else usb_sock = NULL; uint16_t desired_port = g_options.desired_port; struct tcp_sock_t *tcp_socket; while ((tcp_socket = tcp_open(desired_port)) == NULL && g_options.only_desired_port == 0) { desired_port ++; if (desired_port == 1 || desired_port == 0) desired_port = 49152; } if (tcp_socket == NULL) goto cleanup_tcp; uint16_t real_port = tcp_port_number_get(tcp_socket); if (desired_port != 0 && g_options.only_desired_port == 1 && desired_port != real_port) { ERR("Received port number did not match requested port number." " The requested port number may be too high."); goto cleanup_tcp; } printf("%u|", real_port); fflush(stdout); uint16_t pid; if (!g_options.nofork_mode && (pid = fork()) > 0) { printf("%u|", pid); exit(0); } if (usb_can_callback(usb_sock)) usb_register_callback(usb_sock); for (;;) { struct service_thread_param *args = calloc(1, sizeof(*args)); if (args == NULL) { ERR("Failed to alloc space for thread args"); goto cleanup_thread; } args->usb_sock = usb_sock; args->tcp = tcp_conn_accept(tcp_socket); if (args->tcp == NULL) { ERR("Failed to open tcp connection"); goto cleanup_thread; } int status = pthread_create(&args->thread_handle, NULL, &service_connection, args); if (status) { ERR("Failed to spawn thread, error %d", status); goto cleanup_thread; } continue; cleanup_thread: if (args != NULL) { if (args->tcp != NULL) tcp_conn_close(args->tcp); free(args); } break; } cleanup_tcp: if (tcp_socket!= NULL) tcp_close(tcp_socket); cleanup_usb: if (usb_sock != NULL) usb_close(usb_sock); return; } Commit Message: SECURITY FIX: Actually restrict the access to the printer to localhost Before, any machine in any network connected by any of the interfaces (as listed by "ifconfig") could access to an IPP-over-USB printer on the assigned port, allowing users on remote machines to print and to access the web configuration interface of a IPP-over-USB printer in contrary to conventional USB printers which are only accessible locally. CWE ID: CWE-264
static void start_daemon() { struct usb_sock_t *usb_sock; if (g_options.noprinter_mode == 0) { usb_sock = usb_open(); if (usb_sock == NULL) goto cleanup_usb; } else usb_sock = NULL; uint16_t desired_port = g_options.desired_port; struct tcp_sock_t *tcp_socket = NULL, *tcp6_socket = NULL; for (;;) { tcp_socket = tcp_open(desired_port); tcp6_socket = tcp6_open(desired_port); if (tcp_socket || tcp6_socket || g_options.only_desired_port) break; desired_port ++; if (desired_port == 1 || desired_port == 0) desired_port = 49152; NOTE("Access to desired port failed, trying alternative port %d", desired_port); } if (tcp_socket == NULL && tcp6_socket == NULL) goto cleanup_tcp; uint16_t real_port; if (tcp_socket) real_port = tcp_port_number_get(tcp_socket); else real_port = tcp_port_number_get(tcp6_socket); if (desired_port != 0 && g_options.only_desired_port == 1 && desired_port != real_port) { ERR("Received port number did not match requested port number." " The requested port number may be too high."); goto cleanup_tcp; } printf("%u|", real_port); fflush(stdout); NOTE("Port: %d, IPv4 %savailable, IPv6 %savailable", real_port, tcp_socket ? "" : "not ", tcp6_socket ? "" : "not "); uint16_t pid; if (!g_options.nofork_mode && (pid = fork()) > 0) { printf("%u|", pid); exit(0); } if (usb_can_callback(usb_sock)) usb_register_callback(usb_sock); for (;;) { struct service_thread_param *args = calloc(1, sizeof(*args)); if (args == NULL) { ERR("Failed to alloc space for thread args"); goto cleanup_thread; } args->usb_sock = usb_sock; // For each request/response round we use the socket (IPv4 or // IPv6) which receives data first args->tcp = tcp_conn_select(tcp_socket, tcp6_socket); if (args->tcp == NULL) { ERR("Failed to open tcp connection"); goto cleanup_thread; } int status = pthread_create(&args->thread_handle, NULL, &service_connection, args); if (status) { ERR("Failed to spawn thread, error %d", status); goto cleanup_thread; } continue; cleanup_thread: if (args != NULL) { if (args->tcp != NULL) tcp_conn_close(args->tcp); free(args); } break; } cleanup_tcp: if (tcp_socket!= NULL) tcp_close(tcp_socket); if (tcp6_socket!= NULL) tcp_close(tcp6_socket); cleanup_usb: if (usb_sock != NULL) usb_close(usb_sock); return; }
166,588
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unset_and_free_gvalue (gpointer val) { g_value_unset (val); g_free (val); } Commit Message: CWE ID: CWE-264
unset_and_free_gvalue (gpointer val)
165,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: Chapters::Edition::Edition() { } 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
Chapters::Edition::Edition() const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size; Atom* const atoms = new (std::nothrow) Atom[size]; if (atoms == NULL) return false; for (int idx = 0; idx < m_atoms_count; ++idx) { m_atoms[idx].ShallowCopy(atoms[idx]); } delete[] m_atoms; m_atoms = atoms; m_atoms_size = size; return true; }
174,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::DispatchUnloadEvents() { PluginScriptForbiddenScope forbid_plugin_destructor_scripting; if (parser_) parser_->StopParsing(); if (load_event_progress_ == kLoadEventNotRun) return; if (load_event_progress_ <= kUnloadEventInProgress) { Element* current_focused_element = FocusedElement(); if (auto* input = ToHTMLInputElementOrNull(current_focused_element)) input->EndEditing(); if (load_event_progress_ < kPageHideInProgress) { load_event_progress_ = kPageHideInProgress; if (LocalDOMWindow* window = domWindow()) { const TimeTicks pagehide_event_start = CurrentTimeTicks(); window->DispatchEvent( PageTransitionEvent::Create(EventTypeNames::pagehide, false), this); const TimeTicks pagehide_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, pagehide_histogram, ("DocumentEventTiming.PageHideDuration", 0, 10000000, 50)); pagehide_histogram.Count( (pagehide_event_end - pagehide_event_start).InMicroseconds()); } if (!frame_) return; mojom::PageVisibilityState visibility_state = GetPageVisibilityState(); load_event_progress_ = kUnloadVisibilityChangeInProgress; if (visibility_state != mojom::PageVisibilityState::kHidden) { const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks(); DispatchEvent(Event::CreateBubble(EventTypeNames::visibilitychange)); const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram, ("DocumentEventTiming.PageVibilityHiddenDuration", 0, 10000000, 50)); pagevisibility_histogram.Count((pagevisibility_hidden_event_end - pagevisibility_hidden_event_start) .InMicroseconds()); DispatchEvent( Event::CreateBubble(EventTypeNames::webkitvisibilitychange)); } if (!frame_) return; frame_->Loader().SaveScrollAnchor(); DocumentLoader* document_loader = frame_->Loader().GetProvisionalDocumentLoader(); load_event_progress_ = kUnloadEventInProgress; Event* unload_event(Event::Create(EventTypeNames::unload)); if (document_loader && document_loader->GetTiming().UnloadEventStart().is_null() && document_loader->GetTiming().UnloadEventEnd().is_null()) { DocumentLoadTiming& timing = document_loader->GetTiming(); DCHECK(!timing.NavigationStart().is_null()); const TimeTicks unload_event_start = CurrentTimeTicks(); timing.MarkUnloadEventStart(unload_event_start); frame_->DomWindow()->DispatchEvent(unload_event, this); const TimeTicks unload_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, unload_histogram, ("DocumentEventTiming.UnloadDuration", 0, 10000000, 50)); unload_histogram.Count( (unload_event_end - unload_event_start).InMicroseconds()); timing.MarkUnloadEventEnd(unload_event_end); } else { frame_->DomWindow()->DispatchEvent(unload_event, frame_->GetDocument()); } } load_event_progress_ = kUnloadEventHandled; } if (!frame_) return; bool keep_event_listeners = frame_->Loader().GetProvisionalDocumentLoader() && frame_->ShouldReuseDefaultView( frame_->Loader().GetProvisionalDocumentLoader()->Url()); if (!keep_event_listeners) RemoveAllEventListenersRecursively(); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <andypaicu@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285
void Document::DispatchUnloadEvents() { PluginScriptForbiddenScope forbid_plugin_destructor_scripting; if (parser_) parser_->StopParsing(); if (load_event_progress_ == kLoadEventNotRun) return; if (load_event_progress_ <= kUnloadEventInProgress) { Element* current_focused_element = FocusedElement(); if (auto* input = ToHTMLInputElementOrNull(current_focused_element)) input->EndEditing(); if (load_event_progress_ < kPageHideInProgress) { load_event_progress_ = kPageHideInProgress; if (LocalDOMWindow* window = domWindow()) { const TimeTicks pagehide_event_start = CurrentTimeTicks(); window->DispatchEvent( PageTransitionEvent::Create(EventTypeNames::pagehide, false), this); const TimeTicks pagehide_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, pagehide_histogram, ("DocumentEventTiming.PageHideDuration", 0, 10000000, 50)); pagehide_histogram.Count( (pagehide_event_end - pagehide_event_start).InMicroseconds()); } if (!frame_) return; mojom::PageVisibilityState visibility_state = GetPageVisibilityState(); load_event_progress_ = kUnloadVisibilityChangeInProgress; if (visibility_state != mojom::PageVisibilityState::kHidden) { const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks(); DispatchEvent(Event::CreateBubble(EventTypeNames::visibilitychange)); const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram, ("DocumentEventTiming.PageVibilityHiddenDuration", 0, 10000000, 50)); pagevisibility_histogram.Count((pagevisibility_hidden_event_end - pagevisibility_hidden_event_start) .InMicroseconds()); DispatchEvent( Event::CreateBubble(EventTypeNames::webkitvisibilitychange)); } if (!frame_) return; frame_->Loader().SaveScrollAnchor(); DocumentLoader* document_loader = frame_->Loader().GetProvisionalDocumentLoader(); load_event_progress_ = kUnloadEventInProgress; Event* unload_event(Event::Create(EventTypeNames::unload)); if (document_loader && document_loader->GetTiming().UnloadEventStart().is_null() && document_loader->GetTiming().UnloadEventEnd().is_null()) { DocumentLoadTiming& timing = document_loader->GetTiming(); DCHECK(!timing.NavigationStart().is_null()); const TimeTicks unload_event_start = CurrentTimeTicks(); timing.MarkUnloadEventStart(unload_event_start); frame_->DomWindow()->DispatchEvent(unload_event, this); const TimeTicks unload_event_end = CurrentTimeTicks(); DEFINE_STATIC_LOCAL( CustomCountHistogram, unload_histogram, ("DocumentEventTiming.UnloadDuration", 0, 10000000, 50)); unload_histogram.Count( (unload_event_end - unload_event_start).InMicroseconds()); timing.MarkUnloadEventEnd(unload_event_end); } else { frame_->DomWindow()->DispatchEvent(unload_event, frame_->GetDocument()); } } load_event_progress_ = kUnloadEventHandled; } if (!frame_) return; bool keep_event_listeners = frame_->Loader().GetProvisionalDocumentLoader() && frame_->ShouldReuseDefaultView( frame_->Loader().GetProvisionalDocumentLoader()->Url(), frame_->Loader() .GetProvisionalDocumentLoader() ->GetContentSecurityPolicy()); if (!keep_event_listeners) RemoveAllEventListenersRecursively(); }
173,195
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PluginServiceImpl::GetPluginInfo(int render_process_id, int render_view_id, ResourceContext* context, const GURL& url, const GURL& page_url, const std::string& mime_type, bool allow_wildcard, bool* is_stale, webkit::WebPluginInfo* info, std::string* actual_mime_type) { std::vector<webkit::WebPluginInfo> plugins; std::vector<std::string> mime_types; bool stale = GetPluginInfoArray( url, mime_type, allow_wildcard, &plugins, &mime_types); if (is_stale) *is_stale = stale; for (size_t i = 0; i < plugins.size(); ++i) { if (!filter_ || filter_->IsPluginEnabled(render_process_id, render_view_id, context, url, page_url, &plugins[i])) { *info = plugins[i]; if (actual_mime_type) *actual_mime_type = mime_types[i]; return true; } } return false; } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
bool PluginServiceImpl::GetPluginInfo(int render_process_id, int render_view_id, ResourceContext* context, const GURL& url, const GURL& page_url, const std::string& mime_type, bool allow_wildcard, bool* is_stale, webkit::WebPluginInfo* info, std::string* actual_mime_type) { std::vector<webkit::WebPluginInfo> plugins; std::vector<std::string> mime_types; bool stale = GetPluginInfoArray( url, mime_type, allow_wildcard, &plugins, &mime_types); if (is_stale) *is_stale = stale; for (size_t i = 0; i < plugins.size(); ++i) { if (!filter_ || filter_->IsPluginAvailable(render_process_id, render_view_id, context, url, page_url, &plugins[i])) { *info = plugins[i]; if (actual_mime_type) *actual_mime_type = mime_types[i]; return true; } } return false; }
171,475