prompt
stringlengths
1.19k
236k
output
int64
0
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int filter_frame(AVFilterLink *inlink, AVFrame *inpic) { KerndeintContext *kerndeint = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *outpic; const uint8_t *prvp; ///< Previous field's pixel line number n const uint8_t *prvpp; ///< Previous field's pixel line number (n - 1) const uint8_t *prvpn; ///< Previous field's pixel line number (n + 1) const uint8_t *prvppp; ///< Previous field's pixel line number (n - 2) const uint8_t *prvpnn; ///< Previous field's pixel line number (n + 2) const uint8_t *prvp4p; ///< Previous field's pixel line number (n - 4) const uint8_t *prvp4n; ///< Previous field's pixel line number (n + 4) const uint8_t *srcp; ///< Current field's pixel line number n const uint8_t *srcpp; ///< Current field's pixel line number (n - 1) const uint8_t *srcpn; ///< Current field's pixel line number (n + 1) const uint8_t *srcppp; ///< Current field's pixel line number (n - 2) const uint8_t *srcpnn; ///< Current field's pixel line number (n + 2) const uint8_t *srcp3p; ///< Current field's pixel line number (n - 3) const uint8_t *srcp3n; ///< Current field's pixel line number (n + 3) const uint8_t *srcp4p; ///< Current field's pixel line number (n - 4) const uint8_t *srcp4n; ///< Current field's pixel line number (n + 4) uint8_t *dstp, *dstp_saved; const uint8_t *srcp_saved; int src_linesize, psrc_linesize, dst_linesize, bwidth; int x, y, plane, val, hi, lo, g, h, n = kerndeint->frame++; double valf; const int thresh = kerndeint->thresh; const int order = kerndeint->order; const int map = kerndeint->map; const int sharp = kerndeint->sharp; const int twoway = kerndeint->twoway; const int is_packed_rgb = kerndeint->is_packed_rgb; outpic = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!outpic) { av_frame_free(&inpic); return AVERROR(ENOMEM); } av_frame_copy_props(outpic, inpic); outpic->interlaced_frame = 0; for (plane = 0; inpic->data[plane] && plane < 4; plane++) { h = plane == 0 ? inlink->h : FF_CEIL_RSHIFT(inlink->h, kerndeint->vsub); bwidth = kerndeint->tmp_bwidth[plane]; srcp = srcp_saved = inpic->data[plane]; src_linesize = inpic->linesize[plane]; psrc_linesize = kerndeint->tmp_linesize[plane]; dstp = dstp_saved = outpic->data[plane]; dst_linesize = outpic->linesize[plane]; srcp = srcp_saved + (1 - order) * src_linesize; dstp = dstp_saved + (1 - order) * dst_linesize; for (y = 0; y < h; y += 2) { memcpy(dstp, srcp, bwidth); srcp += 2 * src_linesize; dstp += 2 * dst_linesize; } memcpy(dstp_saved + order * dst_linesize, srcp_saved + (1 - order) * src_linesize, bwidth); memcpy(dstp_saved + (2 + order ) * dst_linesize, srcp_saved + (3 - order) * src_linesize, bwidth); memcpy(dstp_saved + (h - 2 + order) * dst_linesize, srcp_saved + (h - 1 - order) * src_linesize, bwidth); memcpy(dstp_saved + (h - 4 + order) * dst_linesize, srcp_saved + (h - 3 - order) * src_linesize, bwidth); /* For the other field choose adaptively between using the previous field or the interpolant from the current field. */ prvp = kerndeint->tmp_data[plane] + 5 * psrc_linesize - (1 - order) * psrc_linesize; prvpp = prvp - psrc_linesize; prvppp = prvp - 2 * psrc_linesize; prvp4p = prvp - 4 * psrc_linesize; prvpn = prvp + psrc_linesize; prvpnn = prvp + 2 * psrc_linesize; prvp4n = prvp + 4 * psrc_linesize; srcp = srcp_saved + 5 * src_linesize - (1 - order) * src_linesize; srcpp = srcp - src_linesize; srcppp = srcp - 2 * src_linesize; srcp3p = srcp - 3 * src_linesize; srcp4p = srcp - 4 * src_linesize; srcpn = srcp + src_linesize; srcpnn = srcp + 2 * src_linesize; srcp3n = srcp + 3 * src_linesize; srcp4n = srcp + 4 * src_linesize; dstp = dstp_saved + 5 * dst_linesize - (1 - order) * dst_linesize; for (y = 5 - (1 - order); y <= h - 5 - (1 - order); y += 2) { for (x = 0; x < bwidth; x++) { if (thresh == 0 || n == 0 || (abs((int)prvp[x] - (int)srcp[x]) > thresh) || (abs((int)prvpp[x] - (int)srcpp[x]) > thresh) || (abs((int)prvpn[x] - (int)srcpn[x]) > thresh)) { if (map) { g = x & ~3; if (is_packed_rgb) { AV_WB32(dstp + g, 0xffffffff); x = g + 3; } else if (inlink->format == AV_PIX_FMT_YUYV422) { AV_WB32(dstp + g, 0xeb80eb80); x = g + 3; } else { dstp[x] = plane == 0 ? 235 : 128; } } else { if (is_packed_rgb) { hi = 255; lo = 0; } else if (inlink->format == AV_PIX_FMT_YUYV422) { hi = x & 1 ? 240 : 235; lo = 16; } else { hi = plane == 0 ? 235 : 240; lo = 16; } if (sharp) { if (twoway) { valf = + 0.526 * ((int)srcpp[x] + (int)srcpn[x]) + 0.170 * ((int)srcp[x] + (int)prvp[x]) - 0.116 * ((int)srcppp[x] + (int)srcpnn[x] + (int)prvppp[x] + (int)prvpnn[x]) - 0.026 * ((int)srcp3p[x] + (int)srcp3n[x]) + 0.031 * ((int)srcp4p[x] + (int)srcp4n[x] + (int)prvp4p[x] + (int)prvp4n[x]); } else { valf = + 0.526 * ((int)srcpp[x] + (int)srcpn[x]) + 0.170 * ((int)prvp[x]) - 0.116 * ((int)prvppp[x] + (int)prvpnn[x]) - 0.026 * ((int)srcp3p[x] + (int)srcp3n[x]) + 0.031 * ((int)prvp4p[x] + (int)prvp4p[x]); } dstp[x] = av_clip(valf, lo, hi); } else { if (twoway) { val = (8 * ((int)srcpp[x] + (int)srcpn[x]) + 2 * ((int)srcp[x] + (int)prvp[x]) - (int)(srcppp[x]) - (int)(srcpnn[x]) - (int)(prvppp[x]) - (int)(prvpnn[x])) >> 4; } else { val = (8 * ((int)srcpp[x] + (int)srcpn[x]) + 2 * ((int)prvp[x]) - (int)(prvppp[x]) - (int)(prvpnn[x])) >> 4; } dstp[x] = av_clip(val, lo, hi); } } } else { dstp[x] = srcp[x]; } } prvp += 2 * psrc_linesize; prvpp += 2 * psrc_linesize; prvppp += 2 * psrc_linesize; prvpn += 2 * psrc_linesize; prvpnn += 2 * psrc_linesize; prvp4p += 2 * psrc_linesize; prvp4n += 2 * psrc_linesize; srcp += 2 * src_linesize; srcpp += 2 * src_linesize; srcppp += 2 * src_linesize; srcp3p += 2 * src_linesize; srcp4p += 2 * src_linesize; srcpn += 2 * src_linesize; srcpnn += 2 * src_linesize; srcp3n += 2 * src_linesize; srcp4n += 2 * src_linesize; dstp += 2 * dst_linesize; } srcp = inpic->data[plane]; dstp = kerndeint->tmp_data[plane]; av_image_copy_plane(dstp, psrc_linesize, srcp, src_linesize, bwidth, h); } av_frame_free(&inpic); return ff_filter_frame(outlink, outpic); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int ath_txstatus_setup(struct ath_softc *sc, int size) { struct ath_descdma *dd = &sc->txsdma; u8 txs_len = sc->sc_ah->caps.txs_len; dd->dd_desc_len = size * txs_len; dd->dd_desc = dmam_alloc_coherent(sc->dev, dd->dd_desc_len, &dd->dd_desc_paddr, GFP_KERNEL); if (!dd->dd_desc) return -ENOMEM; return 0; } Commit Message: ath9k: protect tid->sched check We check tid->sched without a lock taken on ath_tx_aggr_sleep(). That is race condition which can result of doing list_del(&tid->list) twice (second time with poisoned list node) and cause crash like shown below: [424271.637220] BUG: unable to handle kernel paging request at 00100104 [424271.637328] IP: [<f90fc072>] ath_tx_aggr_sleep+0x62/0xe0 [ath9k] ... [424271.639953] Call Trace: [424271.639998] [<f90f6900>] ? ath9k_get_survey+0x110/0x110 [ath9k] [424271.640083] [<f90f6942>] ath9k_sta_notify+0x42/0x50 [ath9k] [424271.640177] [<f809cfef>] sta_ps_start+0x8f/0x1c0 [mac80211] [424271.640258] [<c10f730e>] ? free_compound_page+0x2e/0x40 [424271.640346] [<f809e915>] ieee80211_rx_handlers+0x9d5/0x2340 [mac80211] [424271.640437] [<c112f048>] ? kmem_cache_free+0x1d8/0x1f0 [424271.640510] [<c1345a84>] ? kfree_skbmem+0x34/0x90 [424271.640578] [<c10fc23c>] ? put_page+0x2c/0x40 [424271.640640] [<c1345a84>] ? kfree_skbmem+0x34/0x90 [424271.640706] [<c1345a84>] ? kfree_skbmem+0x34/0x90 [424271.640787] [<f809dde3>] ? ieee80211_rx_handlers_result+0x73/0x1d0 [mac80211] [424271.640897] [<f80a07a0>] ieee80211_prepare_and_rx_handle+0x520/0xad0 [mac80211] [424271.641009] [<f809e22d>] ? ieee80211_rx_handlers+0x2ed/0x2340 [mac80211] [424271.641104] [<c13846ce>] ? ip_output+0x7e/0xd0 [424271.641182] [<f80a1057>] ieee80211_rx+0x307/0x7c0 [mac80211] [424271.641266] [<f90fa6ee>] ath_rx_tasklet+0x88e/0xf70 [ath9k] [424271.641358] [<f80a0f2c>] ? ieee80211_rx+0x1dc/0x7c0 [mac80211] [424271.641445] [<f90f82db>] ath9k_tasklet+0xcb/0x130 [ath9k] Bug report: https://bugzilla.kernel.org/show_bug.cgi?id=70551 Reported-and-tested-by: Max Sydorenko <[email protected]> Cc: [email protected] Signed-off-by: Stanislaw Gruszka <[email protected]> Signed-off-by: John W. Linville <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline hb_script_t ICUScriptToHBScript(UScriptCode script) { if (UNLIKELY(script == USCRIPT_INVALID_CODE)) return HB_SCRIPT_INVALID; return hb_script_from_string(uscript_getShortName(script), -1); } Commit Message: Always initialize |m_totalWidth| in HarfBuzzShaper::shape. [email protected] BUG=476647 Review URL: https://codereview.chromium.org/1108663003 git-svn-id: svn://svn.chromium.org/blink/trunk@194541 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int FFmpegVideoDecoder::GetVideoBuffer(AVCodecContext* codec_context, AVFrame* frame) { VideoFrame::Format format = PixelFormatToVideoFormat(codec_context->pix_fmt); if (format == VideoFrame::UNKNOWN) return AVERROR(EINVAL); DCHECK(format == VideoFrame::YV12 || format == VideoFrame::YV16 || format == VideoFrame::YV12J); gfx::Size size(codec_context->width, codec_context->height); int ret; if ((ret = av_image_check_size(size.width(), size.height(), 0, NULL)) < 0) return ret; gfx::Size natural_size; if (codec_context->sample_aspect_ratio.num > 0) { natural_size = GetNaturalSize(size, codec_context->sample_aspect_ratio.num, codec_context->sample_aspect_ratio.den); } else { natural_size = config_.natural_size(); } if (!VideoFrame::IsValidConfig(format, size, gfx::Rect(size), natural_size)) return AVERROR(EINVAL); scoped_refptr<VideoFrame> video_frame = frame_pool_.CreateFrame(format, size, gfx::Rect(size), natural_size, kNoTimestamp()); for (int i = 0; i < 3; i++) { frame->base[i] = video_frame->data(i); frame->data[i] = video_frame->data(i); frame->linesize[i] = video_frame->stride(i); } frame->opaque = NULL; video_frame.swap(reinterpret_cast<VideoFrame**>(&frame->opaque)); frame->type = FF_BUFFER_TYPE_USER; frame->width = codec_context->width; frame->height = codec_context->height; frame->format = codec_context->pix_fmt; return 0; } Commit Message: Replicate FFmpeg's video frame allocation strategy. This should avoid accidental overreads and overwrites due to our VideoFrame's not being as large as FFmpeg expects. BUG=368980 TEST=new regression test Review URL: https://codereview.chromium.org/270193002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268831 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static void udp_v4_rehash(struct sock *sk) { u16 new_hash = udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, inet_sk(sk)->inet_num); udp_lib_rehash(sk, new_hash); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: scoped_ptr<cc::CompositorFrame> TestSynchronousCompositor::DemandDrawHw( gfx::Size surface_size, const gfx::Transform& transform, gfx::Rect viewport, gfx::Rect clip, gfx::Rect viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) { return hardware_frame_.Pass(); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: NO_INLINE JsVar *jspeFactor() { if (lex->tk==LEX_ID) { JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex)); JSP_ASSERT_MATCH(LEX_ID); #ifndef SAVE_ON_FLASH if (lex->tk==LEX_TEMPLATE_LITERAL) jsExceptionHere(JSET_SYNTAXERROR, "Tagged template literals not supported"); else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) { JsVar *funcVar = jspeArrowFunction(0,a); jsvUnLock(a); a=funcVar; } #endif return a; } else if (lex->tk==LEX_INT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_INT); return v; } else if (lex->tk==LEX_FLOAT) { JsVar *v = 0; if (JSP_SHOULD_EXECUTE) { v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex))); } JSP_ASSERT_MATCH(LEX_FLOAT); return v; } else if (lex->tk=='(') { JSP_ASSERT_MATCH('('); if (!jspCheckStackPosition()) return 0; #ifdef SAVE_ON_FLASH JsVar *a = jspeExpression(); if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a); return a; #else return jspeExpressionOrArrowFunction(); #endif } else if (lex->tk==LEX_R_TRUE) { JSP_ASSERT_MATCH(LEX_R_TRUE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0; } else if (lex->tk==LEX_R_FALSE) { JSP_ASSERT_MATCH(LEX_R_FALSE); return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0; } else if (lex->tk==LEX_R_NULL) { JSP_ASSERT_MATCH(LEX_R_NULL); return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0; } else if (lex->tk==LEX_R_UNDEFINED) { JSP_ASSERT_MATCH(LEX_R_UNDEFINED); return 0; } else if (lex->tk==LEX_STR) { JsVar *a = 0; if (JSP_SHOULD_EXECUTE) a = jslGetTokenValueAsVar(lex); JSP_ASSERT_MATCH(LEX_STR); return a; #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_TEMPLATE_LITERAL) { return jspeTemplateLiteral(); #endif } else if (lex->tk==LEX_REGEX) { JsVar *a = 0; #ifdef SAVE_ON_FLASH jsExceptionHere(JSET_SYNTAXERROR, "RegEx are not supported in this version of Espruino\n"); #else JsVar *regex = jslGetTokenValueAsVar(lex); size_t regexEnd = 0, regexLen = 0; JsvStringIterator it; jsvStringIteratorNew(&it, regex, 0); while (jsvStringIteratorHasChar(&it)) { regexLen++; if (jsvStringIteratorGetChar(&it)=='/') regexEnd = regexLen; jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); JsVar *flags = 0; if (regexEnd < regexLen) flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH); JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2); a = jswrap_regexp_constructor(regexSource, flags); jsvUnLock3(regex, flags, regexSource); #endif JSP_ASSERT_MATCH(LEX_REGEX); return a; } else if (lex->tk=='{') { if (!jspCheckStackPosition()) return 0; return jspeFactorObject(); } else if (lex->tk=='[') { if (!jspCheckStackPosition()) return 0; return jspeFactorArray(); } else if (lex->tk==LEX_R_FUNCTION) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_FUNCTION); return jspeFunctionDefinition(true); #ifndef SAVE_ON_FLASH } else if (lex->tk==LEX_R_CLASS) { if (!jspCheckStackPosition()) return 0; JSP_ASSERT_MATCH(LEX_R_CLASS); return jspeClassDefinition(true); } else if (lex->tk==LEX_R_SUPER) { JSP_ASSERT_MATCH(LEX_R_SUPER); /* This is kind of nasty, since super appears to do three different things. * In the constructor it references the extended class's constructor * in a method it references the constructor's prototype. * in a static method it references the extended class's constructor (but this is different) */ if (jsvIsObject(execInfo.thisVar)) { JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__ jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } if (lex->tk=='(') return proto2; // eg. used in a constructor JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0; jsvUnLock(proto2); return proto3; } else if (jsvIsFunction(execInfo.thisVar)) { JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0); JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; jsvUnLock(proto1); if (!proto2) { jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; } return proto2; } jsExceptionHere(JSET_SYNTAXERROR, "Calling 'super' outside of class"); return 0; #endif } else if (lex->tk==LEX_R_THIS) { JSP_ASSERT_MATCH(LEX_R_THIS); return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root ); } else if (lex->tk==LEX_R_DELETE) { if (!jspCheckStackPosition()) return 0; return jspeFactorDelete(); } else if (lex->tk==LEX_R_TYPEOF) { if (!jspCheckStackPosition()) return 0; return jspeFactorTypeOf(); } else if (lex->tk==LEX_R_VOID) { JSP_ASSERT_MATCH(LEX_R_VOID); jsvUnLock(jspeUnaryExpression()); return 0; } JSP_MATCH(LEX_EOF); jsExceptionHere(JSET_SYNTAXERROR, "Unexpected end of Input\n"); return 0; } NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) { while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number) JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); jspReplaceWith(a, res); jsvUnLock(res); jsvUnLock(a); a = oldValue; } } return a; } NO_INLINE JsVar *jspePostfixExpression() { JsVar *a; if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { int op = lex->tk; JSP_ASSERT_MATCH(op); a = jspePostfixExpression(); if (JSP_SHOULD_EXECUTE) { JsVar *one = jsvNewFromInteger(1); JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-'); jsvUnLock(one); jspReplaceWith(a, res); jsvUnLock(res); } } else a = jspeFactorFunctionCall(); return __jspePostfixExpression(a); } NO_INLINE JsVar *jspeUnaryExpression() { if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') { short tk = lex->tk; JSP_ASSERT_MATCH(tk); if (!JSP_SHOULD_EXECUTE) { return jspeUnaryExpression(); } if (tk=='!') { // logical not return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='~') { // bitwise not return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); } else if (tk=='-') { // unary minus return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped } else if (tk=='+') { // unary plus (convert to number) JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression()); JsVar *r = jsvAsNumber(v); // names already skipped jsvUnLock(v); return r; } assert(0); return 0; } else return jspePostfixExpression(); } unsigned int jspeGetBinaryExpressionPrecedence(int op) { switch (op) { case LEX_OROR: return 1; break; case LEX_ANDAND: return 2; break; case '|' : return 3; break; case '^' : return 4; break; case '&' : return 5; break; case LEX_EQUAL: case LEX_NEQUAL: case LEX_TYPEEQUAL: case LEX_NTYPEEQUAL: return 6; case LEX_LEQUAL: case LEX_GEQUAL: case '<': case '>': case LEX_R_INSTANCEOF: return 7; case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7; case LEX_LSHIFT: case LEX_RSHIFT: case LEX_RSHIFTUNSIGNED: return 8; case '+': case '-': return 9; case '*': case '/': case '%': return 10; default: return 0; } } NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) { /* This one's a bit strange. Basically all the ops have their own precedence, it's not * like & and | share the same precedence. We don't want to recurse for each one, * so instead we do this. * * We deal with an expression in recursion ONLY if it's of higher precedence * than the current one, otherwise we stick in the while loop. */ unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk); while (precedence && precedence>lastPrecedence) { int op = lex->tk; JSP_ASSERT_MATCH(op); if (op==LEX_ANDAND || op==LEX_OROR) { bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a)); if ((!aValue && op==LEX_ANDAND) || (aValue && op==LEX_OROR)) { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence)); JSP_RESTORE_EXECUTE(); } else { jsvUnLock(a); a = __jspeBinaryExpression(jspeUnaryExpression(),precedence); } } else { // else it's a more 'normal' logical expression - just use Maths JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence); if (JSP_SHOULD_EXECUTE) { if (op==LEX_R_IN) { JsVar *av = jsvSkipName(a); // needle JsVar *bv = jsvSkipName(b); // haystack if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values av = jsvAsArrayIndexAndUnLock(av); JsVar *varFound = jspGetVarNamedField( bv, av, true); jsvUnLock(a); a = jsvNewFromBool(varFound!=0); jsvUnLock(varFound); } else {// else it will be undefined jsExceptionHere(JSET_ERROR, "Cannot use 'in' operator to search a %t", bv); jsvUnLock(a); a = 0; } jsvUnLock2(av, bv); } else if (op==LEX_R_INSTANCEOF) { bool inst = false; JsVar *av = jsvSkipName(a); JsVar *bv = jsvSkipName(b); if (!jsvIsFunction(bv)) { jsExceptionHere(JSET_ERROR, "Expecting a function on RHS in instanceof check, got %t", bv); } else { if (jsvIsObject(av) || jsvIsFunction(av)) { JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false); JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0); while (proto) { if (proto == bproto) inst=true; JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0); jsvUnLock(proto); proto = childProto; } if (jspIsConstructor(bv, "Object")) inst = true; jsvUnLock(bproto); } if (!inst) { const char *name = jswGetBasicObjectName(av); if (name) { inst = jspIsConstructor(bv, name); } if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) && jspIsConstructor(bv, "Object")) inst = true; } } jsvUnLock3(av, bv, a); a = jsvNewFromBool(inst); } else { // --------------------------------------------- NORMAL JsVar *res = jsvMathsOpSkipNames(a, b, op); jsvUnLock(a); a = res; } } jsvUnLock(b); } precedence = jspeGetBinaryExpressionPrecedence(lex->tk); } return a; } JsVar *jspeBinaryExpression() { return __jspeBinaryExpression(jspeUnaryExpression(),0); } NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) { if (lex->tk=='?') { JSP_ASSERT_MATCH('?'); if (!JSP_SHOULD_EXECUTE) { jsvUnLock(jspeAssignmentExpression()); JSP_MATCH(':'); jsvUnLock(jspeAssignmentExpression()); } else { bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs)); jsvUnLock(lhs); if (first) { lhs = jspeAssignmentExpression(); JSP_MATCH(':'); JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); } else { JSP_SAVE_EXECUTE(); jspSetNoExecute(); jsvUnLock(jspeAssignmentExpression()); JSP_RESTORE_EXECUTE(); JSP_MATCH(':'); lhs = jspeAssignmentExpression(); } } } return lhs; } JsVar *jspeConditionalExpression() { return __jspeConditionalExpression(jspeBinaryExpression()); } 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; } JsVar *jspeAssignmentExpression() { return __jspeAssignmentExpression(jspeConditionalExpression()); } NO_INLINE JsVar *jspeExpression() { while (!JSP_SHOULDNT_PARSE) { JsVar *a = jspeAssignmentExpression(); if (lex->tk!=',') return a; jsvUnLock(a); JSP_ASSERT_MATCH(','); } return 0; } /** Parse a block `{ ... }` but assume brackets are already parsed */ NO_INLINE void jspeBlockNoBrackets() { if (JSP_SHOULD_EXECUTE) { while (lex->tk && lex->tk!='}') { jsvUnLock(jspeStatement()); if (JSP_HAS_ERROR) { if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) { execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED); JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); if (stackTrace) { jsvAppendPrintf(stackTrace, "at "); jspAppendStackTrace(stackTrace); jsvUnLock(stackTrace); } } } if (JSP_SHOULDNT_PARSE) return; } } else { int brackets = 0; while (lex->tk && (brackets || lex->tk != '}')) { if (lex->tk == '{') brackets++; if (lex->tk == '}') brackets--; JSP_ASSERT_MATCH(lex->tk); } } Commit Message: Fix stack overflow if void void void... is repeated many times (fix #1434) CWE ID: CWE-119 Target: 1 Example 2: Code: const char *security_get_initial_sid_context(u32 sid) { if (unlikely(sid > SECINITSID_NUM)) return NULL; return initial_sid_to_string[sid]; } Commit Message: SELinux: Fix kernel BUG on empty security contexts. Setting an empty security context (length=0) on a file will lead to incorrectly dereferencing the type and other fields of the security context structure, yielding a kernel BUG. As a zero-length security context is never valid, just reject all such security contexts whether coming from userspace via setxattr or coming from the filesystem upon a getxattr request by SELinux. Setting a security context value (empty or otherwise) unknown to SELinux in the first place is only possible for a root process (CAP_MAC_ADMIN), and, if running SELinux in enforcing mode, only if the corresponding SELinux mac_admin permission is also granted to the domain by policy. In Fedora policies, this is only allowed for specific domains such as livecd for setting down security contexts that are not defined in the build host policy. Reproducer: su setenforce 0 touch foo setfattr -n security.selinux foo Caveat: Relabeling or removing foo after doing the above may not be possible without booting with SELinux disabled. Any subsequent access to foo after doing the above will also trigger the BUG. BUG output from Matthew Thode: [ 473.893141] ------------[ cut here ]------------ [ 473.962110] kernel BUG at security/selinux/ss/services.c:654! [ 473.995314] invalid opcode: 0000 [#6] SMP [ 474.027196] Modules linked in: [ 474.058118] CPU: 0 PID: 8138 Comm: ls Tainted: G D I 3.13.0-grsec #1 [ 474.116637] Hardware name: Supermicro X8ST3/X8ST3, BIOS 2.0 07/29/10 [ 474.149768] task: ffff8805f50cd010 ti: ffff8805f50cd488 task.ti: ffff8805f50cd488 [ 474.183707] RIP: 0010:[<ffffffff814681c7>] [<ffffffff814681c7>] context_struct_compute_av+0xce/0x308 [ 474.219954] RSP: 0018:ffff8805c0ac3c38 EFLAGS: 00010246 [ 474.252253] RAX: 0000000000000000 RBX: ffff8805c0ac3d94 RCX: 0000000000000100 [ 474.287018] RDX: ffff8805e8aac000 RSI: 00000000ffffffff RDI: ffff8805e8aaa000 [ 474.321199] RBP: ffff8805c0ac3cb8 R08: 0000000000000010 R09: 0000000000000006 [ 474.357446] R10: 0000000000000000 R11: ffff8805c567a000 R12: 0000000000000006 [ 474.419191] R13: ffff8805c2b74e88 R14: 00000000000001da R15: 0000000000000000 [ 474.453816] FS: 00007f2e75220800(0000) GS:ffff88061fc00000(0000) knlGS:0000000000000000 [ 474.489254] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 474.522215] CR2: 00007f2e74716090 CR3: 00000005c085e000 CR4: 00000000000207f0 [ 474.556058] Stack: [ 474.584325] ffff8805c0ac3c98 ffffffff811b549b ffff8805c0ac3c98 ffff8805f1190a40 [ 474.618913] ffff8805a6202f08 ffff8805c2b74e88 00068800d0464990 ffff8805e8aac860 [ 474.653955] ffff8805c0ac3cb8 000700068113833a ffff880606c75060 ffff8805c0ac3d94 [ 474.690461] Call Trace: [ 474.723779] [<ffffffff811b549b>] ? lookup_fast+0x1cd/0x22a [ 474.778049] [<ffffffff81468824>] security_compute_av+0xf4/0x20b [ 474.811398] [<ffffffff8196f419>] avc_compute_av+0x2a/0x179 [ 474.843813] [<ffffffff8145727b>] avc_has_perm+0x45/0xf4 [ 474.875694] [<ffffffff81457d0e>] inode_has_perm+0x2a/0x31 [ 474.907370] [<ffffffff81457e76>] selinux_inode_getattr+0x3c/0x3e [ 474.938726] [<ffffffff81455cf6>] security_inode_getattr+0x1b/0x22 [ 474.970036] [<ffffffff811b057d>] vfs_getattr+0x19/0x2d [ 475.000618] [<ffffffff811b05e5>] vfs_fstatat+0x54/0x91 [ 475.030402] [<ffffffff811b063b>] vfs_lstat+0x19/0x1b [ 475.061097] [<ffffffff811b077e>] SyS_newlstat+0x15/0x30 [ 475.094595] [<ffffffff8113c5c1>] ? __audit_syscall_entry+0xa1/0xc3 [ 475.148405] [<ffffffff8197791e>] system_call_fastpath+0x16/0x1b [ 475.179201] Code: 00 48 85 c0 48 89 45 b8 75 02 0f 0b 48 8b 45 a0 48 8b 3d 45 d0 b6 00 8b 40 08 89 c6 ff ce e8 d1 b0 06 00 48 85 c0 49 89 c7 75 02 <0f> 0b 48 8b 45 b8 4c 8b 28 eb 1e 49 8d 7d 08 be 80 01 00 00 e8 [ 475.255884] RIP [<ffffffff814681c7>] context_struct_compute_av+0xce/0x308 [ 475.296120] RSP <ffff8805c0ac3c38> [ 475.328734] ---[ end trace f076482e9d754adc ]--- Reported-by: Matthew Thode <[email protected]> Signed-off-by: Stephen Smalley <[email protected]> Cc: [email protected] Signed-off-by: Paul Moore <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static enum hrtimer_restart posix_timer_fn(struct hrtimer *timer) { struct k_itimer *timr; unsigned long flags; int si_private = 0; enum hrtimer_restart ret = HRTIMER_NORESTART; timr = container_of(timer, struct k_itimer, it.real.timer); spin_lock_irqsave(&timr->it_lock, flags); timr->it_active = 0; if (timr->it_interval != 0) si_private = ++timr->it_requeue_pending; if (posix_timer_event(timr, si_private)) { /* * signal was not sent because of sig_ignor * we will not get a call back to restart it AND * it should be restarted. */ if (timr->it_interval != 0) { ktime_t now = hrtimer_cb_get_time(timer); /* * FIXME: What we really want, is to stop this * timer completely and restart it in case the * SIG_IGN is removed. This is a non trivial * change which involves sighand locking * (sigh !), which we don't want to do late in * the release cycle. * * For now we just let timers with an interval * less than a jiffie expire every jiffie to * avoid softirq starvation in case of SIG_IGN * and a very small interval, which would put * the timer right back on the softirq pending * list. By moving now ahead of time we trick * hrtimer_forward() to expire the timer * later, while we still maintain the overrun * accuracy, but have some inconsistency in * the timer_gettime() case. This is at least * better than a starved softirq. A more * complex fix which solves also another related * inconsistency is already in the pipeline. */ #ifdef CONFIG_HIGH_RES_TIMERS { ktime_t kj = NSEC_PER_SEC / HZ; if (timr->it_interval < kj) now = ktime_add(now, kj); } #endif timr->it_overrun += (unsigned int) hrtimer_forward(timer, now, timr->it_interval); ret = HRTIMER_RESTART; ++timr->it_requeue_pending; timr->it_active = 1; } } unlock_timer(timr, flags); return ret; } Commit Message: posix-timers: Sanitize overrun handling The posix timer overrun handling is broken because the forwarding functions can return a huge number of overruns which does not fit in an int. As a consequence timer_getoverrun(2) and siginfo::si_overrun can turn into random number generators. The k_clock::timer_forward() callbacks return a 64 bit value now. Make k_itimer::ti_overrun[_last] 64bit as well, so the kernel internal accounting is correct. 3Remove the temporary (int) casts. Add a helper function which clamps the overrun value returned to user space via timer_getoverrun(2) or siginfo::si_overrun limited to a positive value between 0 and INT_MAX. INT_MAX is an indicator for user space that the overrun value has been clamped. Reported-by: Team OWL337 <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Acked-by: John Stultz <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Michael Kerrisk <[email protected]> Link: https://lkml.kernel.org/r/[email protected] CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CuePoint::TrackPosition::Parse( IMkvReader* pReader, long long start_, long long size_) { const long long stop = start_ + size_; long long pos = start_; m_track = -1; m_pos = -1; m_block = 1; //default while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); //TODO assert((pos + len) <= stop); pos += len; //consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; //consume Size field assert((pos + size) <= stop); if (id == 0x77) //CueTrack ID m_track = UnserializeUInt(pReader, pos, size); else if (id == 0x71) //CueClusterPos ID m_pos = UnserializeUInt(pReader, pos, size); else if (id == 0x1378) //CueBlockNumber m_block = UnserializeUInt(pReader, pos, size); pos += size; //consume payload assert(pos <= stop); } assert(m_pos >= 0); assert(m_track > 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 Target: 1 Example 2: Code: ReadUserLogFileState::~ReadUserLogFileState( void ) { } Commit Message: CWE ID: CWE-134 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: struct sock *tcp_v4_syn_recv_sock(struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst) { struct inet_request_sock *ireq; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif if (sk_acceptq_is_full(sk)) goto exit_overflow; if (!dst && (dst = inet_csk_route_req(sk, req)) == NULL) goto exit; newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto exit_nonewsk; newsk->sk_gso_type = SKB_GSO_TCPV4; sk_setup_caps(newsk, dst); newtp = tcp_sk(newsk); newinet = inet_sk(newsk); ireq = inet_rsk(req); newinet->inet_daddr = ireq->rmt_addr; newinet->inet_rcv_saddr = ireq->loc_addr; newinet->inet_saddr = ireq->loc_addr; newinet->opt = ireq->opt; ireq->opt = NULL; newinet->mc_index = inet_iif(skb); newinet->mc_ttl = ip_hdr(skb)->ttl; inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newinet->opt) inet_csk(newsk)->icsk_ext_hdr_len = newinet->opt->optlen; newinet->inet_id = newtp->write_seq ^ jiffies; tcp_mtup_init(newsk); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = dst_metric_advmss(dst); if (tcp_sk(sk)->rx_opt.user_mss && tcp_sk(sk)->rx_opt.user_mss < newtp->advmss) newtp->advmss = tcp_sk(sk)->rx_opt.user_mss; tcp_initialize_rcv_mss(newsk); #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v4_md5_do_lookup(sk, newinet->inet_daddr); if (key != NULL) { /* * We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ char *newkey = kmemdup(key->key, key->keylen, GFP_ATOMIC); if (newkey != NULL) tcp_v4_md5_do_add(newsk, newinet->inet_daddr, newkey, key->keylen); sk_nocaps_add(newsk, NETIF_F_GSO_MASK); } #endif if (__inet_inherit_port(sk, newsk) < 0) { sock_put(newsk); goto exit; } __inet_hash_nolisten(newsk, NULL); return newsk; exit_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); exit_nonewsk: dst_release(dst); exit: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: sp<MediaSource> MPEG4Extractor::getTrack(size_t index) { status_t err; if ((err = readMetaData()) != OK) { return NULL; } Track *track = mFirstTrack; while (index > 0) { if (track == NULL) { return NULL; } track = track->next; --index; } if (track == NULL) { return NULL; } Trex *trex = NULL; int32_t trackId; if (track->meta->findInt32(kKeyTrackID, &trackId)) { for (size_t i = 0; i < mTrex.size(); i++) { Trex *t = &mTrex.editItemAt(index); if (t->track_ID == (uint32_t) trackId) { trex = t; break; } } } ALOGV("getTrack called, pssh: %zu", mPssh.size()); return new MPEG4Source(this, track->meta, mDataSource, track->timescale, track->sampleTable, mSidxEntries, trex, mMoofOffset); } Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track. GenericSource: return error when no track exists. SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor. Bug: 21657957 Bug: 23705695 Bug: 22802344 Bug: 28799341 Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04 (cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13) CWE ID: CWE-119 Target: 1 Example 2: Code: GF_Err mdhd_Read(GF_Box *s, GF_BitStream *bs) { GF_MediaHeaderBox *ptr = (GF_MediaHeaderBox *)s; if (ptr->version == 1) { ptr->creationTime = gf_bs_read_u64(bs); ptr->modificationTime = gf_bs_read_u64(bs); ptr->timeScale = gf_bs_read_u32(bs); ptr->duration = gf_bs_read_u64(bs); } else { ptr->creationTime = gf_bs_read_u32(bs); ptr->modificationTime = gf_bs_read_u32(bs); ptr->timeScale = gf_bs_read_u32(bs); ptr->duration = gf_bs_read_u32(bs); } if (!ptr->timeScale) { GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Media header timescale is 0 - defaulting to 90000\n" )); ptr->timeScale = 90000; } ptr->original_duration = ptr->duration; gf_bs_read_int(bs, 1); ptr->packedLanguage[0] = gf_bs_read_int(bs, 5); ptr->packedLanguage[1] = gf_bs_read_int(bs, 5); ptr->packedLanguage[2] = gf_bs_read_int(bs, 5); if (ptr->packedLanguage[0] || ptr->packedLanguage[1] || ptr->packedLanguage[2]) { ptr->packedLanguage[0] += 0x60; ptr->packedLanguage[1] += 0x60; ptr->packedLanguage[2] += 0x60; } else { ptr->packedLanguage[0] = 'u'; ptr->packedLanguage[1] = 'n'; ptr->packedLanguage[2] = 'd'; } ptr->reserved = gf_bs_read_u16(bs); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DevToolsDomainHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) {} Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } Commit Message: issue #28, do not overwrite heap on corrupt DSDIFF file CWE ID: CWE-125 Target: 1 Example 2: Code: bool MojoJpegDecodeAccelerator::IsSupported() { return true; } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderBlock::addOverflowFromChildren() { if (!hasColumns()) { if (childrenInline()) toRenderBlockFlow(this)->addOverflowFromInlineChildren(); else addOverflowFromBlockChildren(); } else { ColumnInfo* colInfo = columnInfo(); if (columnCount(colInfo)) { LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1); addLayoutOverflow(lastRect); addContentsVisualOverflow(lastRect); } } } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. [email protected], [email protected], [email protected] Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WarmupURLFetcher::FetchWarmupURLNow( const DataReductionProxyServer& proxy_server) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); UMA_HISTOGRAM_EXACT_LINEAR("DataReductionProxy.WarmupURL.FetchInitiated", 1, 2); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("data_reduction_proxy_warmup", R"( semantics { sender: "Data Reduction Proxy" description: "Sends a request to the Data Reduction Proxy server to warm up " "the connection to the proxy." trigger: "A network change while the data reduction proxy is enabled will " "trigger this request." data: "A specific URL, not related to user data." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can control Data Saver on Android via the 'Data Saver' " "setting. Data Saver is not available on iOS, and on desktop it " "is enabled by installing the Data Saver extension." policy_exception_justification: "Not implemented." })"); GURL warmup_url_with_query_params; GetWarmupURLWithQueryParam(&warmup_url_with_query_params); url_loader_.reset(); fetch_timeout_timer_.Stop(); is_fetch_in_flight_ = true; auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = warmup_url_with_query_params; resource_request->load_flags = net::LOAD_BYPASS_CACHE; resource_request->render_frame_id = MSG_ROUTING_CONTROL; url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); static const int kMaxRetries = 5; url_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE); url_loader_->SetAllowHttpErrorResults(true); fetch_timeout_timer_.Start(FROM_HERE, GetFetchTimeout(), this, &WarmupURLFetcher::OnFetchTimeout); url_loader_->SetOnResponseStartedCallback(base::BindOnce( &WarmupURLFetcher::OnURLLoadResponseStarted, base::Unretained(this))); url_loader_->SetOnRedirectCallback(base::BindRepeating( &WarmupURLFetcher::OnURLLoaderRedirect, base::Unretained(this))); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( GetNetworkServiceURLLoaderFactory(proxy_server), base::BindOnce(&WarmupURLFetcher::OnURLLoadComplete, base::Unretained(this))); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416 Target: 1 Example 2: Code: renderbufferStorageMultisampleCHROMIUM( WGC3Denum target, WGC3Dsizei samples, WGC3Denum internalformat, WGC3Dsizei width, WGC3Dsizei height) { gl_->RenderbufferStorageMultisampleEXT( target, samples, internalformat, width, height); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PlatformSensorAccelerometerMac::PlatformSensorAccelerometerMac( mojo::ScopedSharedBufferMapping mapping, PlatformSensorProvider* provider) : PlatformSensor(SensorType::ACCELEROMETER, std::move(mapping), provider), sudden_motion_sensor_(SuddenMotionSensor::Create()) {} Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: image_transform_png_set_scale_16_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth > 8; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_MODERATELY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet(icu::UnicodeString("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; transliterator_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d; ӏ > l; [кĸκ] > k; п > n;"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Disallow Arabic/Hebrew NSMs to come after an unrelated base char. Arabic NSM(non-spacing mark)s and Hebrew NSMs are allowed to mix with Latin with the current 'moderately restrictive script mixing policy'. They're not blocked by BiDi check either because both LTR and RTL labels can have an NSM. Block them from coming after an unrelated script (e.g. Latin + Arabic NSM). Bug: chromium:729979 Test: components_unittests --gtest_filter=*IDNToUni* Change-Id: I5b93fbcf76d17121bf1baaa480ef3624424b3317 Reviewed-on: https://chromium-review.googlesource.com/528348 Reviewed-by: Peter Kasting <[email protected]> Commit-Queue: Jungshik Shin <[email protected]> Cr-Commit-Position: refs/heads/master@{#478205} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: incremental_gc(mrb_state *mrb, mrb_gc *gc, size_t limit) { switch (gc->state) { case MRB_GC_STATE_ROOT: root_scan_phase(mrb, gc); gc->state = MRB_GC_STATE_MARK; flip_white_part(gc); return 0; case MRB_GC_STATE_MARK: if (gc->gray_list) { return incremental_marking_phase(mrb, gc, limit); } else { final_marking_phase(mrb, gc); prepare_incremental_sweep(mrb, gc); return 0; } case MRB_GC_STATE_SWEEP: { size_t tried_sweep = 0; tried_sweep = incremental_sweep_phase(mrb, gc, limit); if (tried_sweep == 0) gc->state = MRB_GC_STATE_ROOT; return tried_sweep; } default: /* unknown state */ mrb_assert(0); return 0; } } Commit Message: Clear unused stack region that may refer freed objects; fix #3596 CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WARN_UNUSED_RESULT bool VerifyRecordedSamplesForHistogram( const size_t num_samples, const std::string& histogram_name) const { return num_samples == histogram_tester_.GetAllSamples(histogram_name).size(); } Commit Message: Revert "Add explicit flag for compositor scrollbar injected gestures" This reverts commit d9a56afcbdf9850bc39bb3edb56d07d11a1eb2b2. Reason for revert: Findit (https://goo.gl/kROfz5) identified CL at revision 669086 as the culprit for flakes in the build cycles as shown on: https://analysis.chromium.org/p/chromium/flake-portal/analysis/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyQwsSDEZsYWtlQ3VscHJpdCIxY2hyb21pdW0vZDlhNTZhZmNiZGY5ODUwYmMzOWJiM2VkYjU2ZDA3ZDExYTFlYjJiMgw Sample Failed Build: https://ci.chromium.org/buildbot/chromium.chromiumos/linux-chromeos-rel/25818 Sample Failed Step: content_browsertests on Ubuntu-16.04 Sample Flaky Test: ScrollLatencyScrollbarBrowserTest.ScrollbarThumbDragLatency Original change's description: > Add explicit flag for compositor scrollbar injected gestures > > The original change to enable scrollbar latency for the composited > scrollbars incorrectly used an existing member to try and determine > whether a GestureScrollUpdate was the first one in an injected sequence > or not. is_first_gesture_scroll_update_ was incorrect because it is only > updated when input is actually dispatched to InputHandlerProxy, and the > flag is cleared for all GSUs before the location where it was being > read. > > This bug was missed because of incorrect tests. The > VerifyRecordedSamplesForHistogram method doesn't actually assert or > expect anything - the return value must be inspected. > > As part of fixing up the tests, I made a few other changes to get them > passing consistently across all platforms: > - turn on main thread scrollbar injection feature (in case it's ever > turned off we don't want the tests to start failing) > - enable mock scrollbars > - disable smooth scrolling > - don't run scrollbar tests on Android > > The composited scrollbar button test is disabled due to a bug in how > the mock theme reports its button sizes, which throws off the region > detection in ScrollbarLayerImplBase::IdentifyScrollbarPart (filed > crbug.com/974063 for this issue). > > Change-Id: Ie1a762a5f6ecc264d22f0256db68f141fc76b950 > > Bug: 954007 > Change-Id: Ib258e08e083e79da90ba2e4e4216e4879cf00cf7 > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1652741 > Commit-Queue: Daniel Libby <[email protected]> > Reviewed-by: David Bokan <[email protected]> > Cr-Commit-Position: refs/heads/master@{#669086} Change-Id: Icc743e48fa740fe27f0cb0cfa21b209a696f518c No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 954007 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1660114 Cr-Commit-Position: refs/heads/master@{#669150} CWE ID: CWE-281 Target: 1 Example 2: Code: virDomainMigrateVersion2(virDomainPtr domain, virConnectPtr dconn, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { virDomainPtr ddomain = NULL; char *uri_out = NULL; char *cookie = NULL; char *dom_xml = NULL; int cookielen = 0, ret; virDomainInfo info; virErrorPtr orig_err = NULL; unsigned int getxml_flags = 0; int cancelled; unsigned long destflags; VIR_DOMAIN_DEBUG(domain, "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu", dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth); /* Prepare the migration. * * The destination host may return a cookie, or leave cookie as * NULL. * * The destination host MUST set uri_out if uri_in is NULL. * * If uri_in is non-NULL, then the destination host may modify * the URI by setting uri_out. If it does not wish to modify * the URI, it should leave uri_out as NULL. */ /* In version 2 of the protocol, the prepare step is slightly * different. We fetch the domain XML of the source domain * and pass it to Prepare2. */ if (!domain->conn->driver->domainGetXMLDesc) { virReportUnsupportedError(); return NULL; } if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_XML_MIGRATABLE)) { getxml_flags |= VIR_DOMAIN_XML_MIGRATABLE; } else { getxml_flags |= VIR_DOMAIN_XML_SECURE | VIR_DOMAIN_XML_UPDATE_CPU; } dom_xml = domain->conn->driver->domainGetXMLDesc(domain, getxml_flags); if (!dom_xml) return NULL; ret = virDomainGetInfo(domain, &info); if (ret == 0 && info.state == VIR_DOMAIN_PAUSED) flags |= VIR_MIGRATE_PAUSED; destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR | VIR_MIGRATE_AUTO_CONVERGE); VIR_DEBUG("Prepare2 %p flags=%lx", dconn, destflags); ret = dconn->driver->domainMigratePrepare2 (dconn, &cookie, &cookielen, uri, &uri_out, destflags, dname, bandwidth, dom_xml); VIR_FREE(dom_xml); if (ret == -1) goto done; if (uri == NULL && uri_out == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("domainMigratePrepare2 did not set uri")); cancelled = 1; /* Make sure Finish doesn't overwrite the error */ orig_err = virSaveLastError(); goto finish; } if (uri_out) uri = uri_out; /* Did domainMigratePrepare2 change URI? */ /* Perform the migration. The driver isn't supposed to return * until the migration is complete. */ VIR_DEBUG("Perform %p", domain->conn); ret = domain->conn->driver->domainMigratePerform (domain, cookie, cookielen, uri, flags, dname, bandwidth); /* Perform failed. Make sure Finish doesn't overwrite the error */ if (ret < 0) orig_err = virSaveLastError(); /* If Perform returns < 0, then we need to cancel the VM * startup on the destination */ cancelled = ret < 0 ? 1 : 0; finish: /* In version 2 of the migration protocol, we pass the * status code from the sender to the destination host, * so it can do any cleanup if the migration failed. */ dname = dname ? dname : domain->name; VIR_DEBUG("Finish2 %p ret=%d", dconn, ret); ddomain = dconn->driver->domainMigrateFinish2 (dconn, dname, cookie, cookielen, uri, destflags, cancelled); if (cancelled && ddomain) VIR_ERROR(_("finish step ignored that migration was cancelled")); done: if (orig_err) { virSetError(orig_err); virFreeError(orig_err); } VIR_FREE(uri_out); VIR_FREE(cookie); return ddomain; } Commit Message: virDomainGetTime: Deny on RO connections We have a policy that if API may end up talking to a guest agent it should require RW connection. We don't obey the rule in virDomainGetTime(). Signed-off-by: Michal Privoznik <[email protected]> CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) { const xmlChar *ptr; xmlChar cur; xmlChar *name; xmlEntityPtr entity = NULL; if ((str == NULL) || (*str == NULL)) return(NULL); ptr = *str; cur = *ptr; if (cur != '%') return(NULL); ptr++; name = xmlParseStringName(ctxt, &ptr); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseStringPEReference: no name\n"); *str = ptr; return(NULL); } cur = *ptr; if (cur != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); xmlFree(name); *str = ptr; return(NULL); } ptr++; /* * 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) { xmlFree(name); return(NULL); } 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; } xmlParserEntityCheck(ctxt, 0, NULL, 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, "%%%s; is not a parameter entity\n", name, NULL); } } ctxt->hasPErefs = 1; xmlFree(name); *str = ptr; return(entity); } Commit Message: DO NOT MERGE: Add validation for eternal enities https://bugzilla.gnome.org/show_bug.cgi?id=780691 Bug: 36556310 Change-Id: I9450743e167c3c73af5e4071f3fc85e81d061648 (cherry picked from commit bef9af3d89d241bcb518c20cba6da2a2fd9ba049) CWE ID: CWE-611 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host, const base::string16& message, const base::string16& default_prompt, const GURL& frame_url, JavaScriptDialogType dialog_type, IPC::Message* reply_msg) { bool suppress_this_message = ShowingInterstitialPage() || !delegate_ || delegate_->ShouldSuppressDialogs(this) || !delegate_->GetJavaScriptDialogManager(this); if (!suppress_this_message) { is_showing_javascript_dialog_ = true; dialog_manager_ = delegate_->GetJavaScriptDialogManager(this); dialog_manager_->RunJavaScriptDialog( this, frame_url, dialog_type, message, default_prompt, base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this), render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, false), &suppress_this_message); } if (suppress_this_message) { OnDialogClosed(render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID(), reply_msg, true, false, base::string16()); } } Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884} CWE ID: CWE-20 Target: 1 Example 2: Code: void RenderWidgetHostViewAura::SetCompositionText( const ui::CompositionText& composition) { if (!host_) return; COMPILE_ASSERT(sizeof(ui::CompositionUnderline) == sizeof(WebKit::WebCompositionUnderline), ui_CompositionUnderline__WebKit_WebCompositionUnderline_diff); const std::vector<WebKit::WebCompositionUnderline>& underlines = reinterpret_cast<const std::vector<WebKit::WebCompositionUnderline>&>( composition.underlines); host_->ImeSetComposition(composition.text, underlines, composition.selection.end(), composition.selection.end()); has_composition_text_ = !composition.text.empty(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void LoopSyncShare() { bool should_loop = false; int loop_iterations = 0; do { ASSERT_LT(++loop_iterations, 100) << "infinite loop detected. please fix"; should_loop = SyncShareNudge(); } while (should_loop); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline long decode_twos_comp(ulong c, int prec) { long result; assert(prec >= 2); jas_eprintf("warning: support for signed data is untested\n"); result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1))); return result; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Target: 1 Example 2: Code: void InputHandler::cancelSelection() { if (!isActiveTextEdit()) return; ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame()); int selectionStartPosition = selectionStart(); ProcessingChangeGuard guard(this); setCursorPosition(selectionStartPosition); } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: size_t GLES2DecoderPassthroughImpl::GetSavedBackTextureCountForTest() { return in_use_color_textures_.size() + available_color_textures_.size(); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SerializerMarkupAccumulator::appendText(StringBuilder& result, Text* text) { Element* parent = text->parentElement(); if (parent && !shouldIgnoreElement(parent)) MarkupAccumulator::appendText(result, text); } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > [email protected] > > Review URL: https://codereview.chromium.org/68613003 [email protected] Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: static int iucv_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); struct iucv_message txmsg; int err = 0; how++; if ((how & ~SHUTDOWN_MASK) || !how) return -EINVAL; lock_sock(sk); switch (sk->sk_state) { case IUCV_LISTEN: case IUCV_DISCONN: case IUCV_CLOSING: case IUCV_CLOSED: err = -ENOTCONN; goto fail; default: break; } if (how == SEND_SHUTDOWN || how == SHUTDOWN_MASK) { if (iucv->transport == AF_IUCV_TRANS_IUCV) { txmsg.class = 0; txmsg.tag = 0; err = pr_iucv->message_send(iucv->path, &txmsg, IUCV_IPRMDATA, 0, (void *) iprm_shutdown, 8); if (err) { switch (err) { case 1: err = -ENOTCONN; break; case 2: err = -ECONNRESET; break; default: err = -ENOTCONN; break; } } } else iucv_send_ctrl(sk, AF_IUCV_FLAG_SHT); } sk->sk_shutdown |= how; if (how == RCV_SHUTDOWN || how == SHUTDOWN_MASK) { if (iucv->transport == AF_IUCV_TRANS_IUCV) { err = pr_iucv->path_quiesce(iucv->path, NULL); if (err) err = -ENOTCONN; /* skb_queue_purge(&sk->sk_receive_queue); */ } skb_queue_purge(&sk->sk_receive_queue); } /* Wake up anyone sleeping in poll */ sk->sk_state_change(sk); fail: release_sock(sk); return err; } Commit Message: iucv: Fix missing msg_namelen update in iucv_sock_recvmsg() The current code does not fill the msg_name member in case it is set. It also does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that by simply setting msg_namelen to 0 as obviously nobody cared about iucv_sock_recvmsg() not filling the msg_name in case it was set. Cc: Ursula Braun <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PasswordAutofillAgent::DidFinishDocumentLoad() { SendPasswordForms(false); } Commit Message: [Android][TouchToFill] Use FindPasswordInfoForElement for triggering Use for TouchToFill the same triggering logic that is used for regular suggestions. Bug: 1010233 Change-Id: I111d4eac4ce94dd94b86097b6b6c98e08875e11a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1834230 Commit-Queue: Boris Sazonov <[email protected]> Reviewed-by: Vadym Doroshenko <[email protected]> Cr-Commit-Position: refs/heads/master@{#702058} CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: gss_get_mic_iov_length(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_wrap_iov_args(minor_status, context_handle, 0, qop_req, NULL, iov, iov_count); if (status != GSS_S_COMPLETE) return status; /* Select the approprate underlying mechanism routine and call it. */ ctx = (gss_union_ctx_id_t)context_handle; mech = gssint_get_mechanism(ctx->mech_type); if (mech == NULL) return GSS_S_BAD_MECH; if (mech->gss_get_mic_iov_length == NULL) return GSS_S_UNAVAILABLE; status = mech->gss_get_mic_iov_length(minor_status, ctx->internal_ctx_id, qop_req, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); return status; } Commit Message: Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-415 Target: 1 Example 2: Code: static int __hw_addr_sync(struct netdev_hw_addr_list *to_list, struct netdev_hw_addr_list *from_list, int addr_len) { int err = 0; struct netdev_hw_addr *ha, *tmp; list_for_each_entry_safe(ha, tmp, &from_list->list, list) { if (!ha->synced) { err = __hw_addr_add(to_list, ha->addr, addr_len, ha->type); if (err) break; ha->synced = true; ha->refcount++; } else if (ha->refcount == 1) { __hw_addr_del(to_list, ha->addr, addr_len, ha->type); __hw_addr_del(from_list, ha->addr, addr_len, ha->type); } } return err; } Commit Message: veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual status_t getExtensionIndex( node_id node, const char *parameter_name, OMX_INDEXTYPE *index) { Parcel data, reply; data.writeInterfaceToken(IOMX::getInterfaceDescriptor()); data.writeInt32((int32_t)node); data.writeCString(parameter_name); remote()->transact(GET_EXTENSION_INDEX, data, &reply); status_t err = reply.readInt32(); if (err == OK) { *index = static_cast<OMX_INDEXTYPE>(reply.readInt32()); } else { *index = OMX_IndexComponentStartUnused; } return err; } Commit Message: Fix size check for OMX_IndexParamConsumerUsageBits since it doesn't follow the OMX convention. And remove support for the kClientNeedsFrameBuffer flag. Bug: 27207275 Change-Id: Ia2c119e2456ebf9e2f4e1de5104ef9032a212255 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void NavigatorImpl::DidFailProvisionalLoadWithError( RenderFrameHostImpl* render_frame_host, const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) { VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec() << ", error_code: " << params.error_code << ", error_description: " << params.error_description << ", showing_repost_interstitial: " << params.showing_repost_interstitial << ", frame_id: " << render_frame_host->GetRoutingID(); GURL validated_url(params.url); RenderProcessHost* render_process_host = render_frame_host->GetProcess(); render_process_host->FilterURL(false, &validated_url); if (net::ERR_ABORTED == params.error_code) { FrameTreeNode* root = render_frame_host->frame_tree_node()->frame_tree()->root(); if (root->render_manager()->interstitial_page() != NULL) { LOG(WARNING) << "Discarding message during interstitial."; return; } } int expected_pending_entry_id = render_frame_host->navigation_handle() ? render_frame_host->navigation_handle()->pending_nav_entry_id() : 0; DiscardPendingEntryIfNeeded(expected_pending_entry_id); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20 Target: 1 Example 2: Code: IOThread::IOThread( PrefService* local_state, policy::PolicyService* policy_service, ChromeNetLog* net_log, extensions::EventRouterForwarder* extension_event_router_forwarder) : net_log_(net_log), extension_event_router_forwarder_(extension_event_router_forwarder), globals_(NULL), sdch_manager_(NULL), is_spdy_disabled_by_policy_(false), weak_factory_(this) { #if !defined(OS_IOS) && !defined(OS_ANDROID) #if defined(OS_WIN) if (!win8::IsSingleWindowMetroMode()) net::ProxyResolverV8::RememberDefaultIsolate(); else net::ProxyResolverV8::CreateIsolate(); #else net::ProxyResolverV8::RememberDefaultIsolate(); #endif #endif auth_schemes_ = local_state->GetString(prefs::kAuthSchemes); negotiate_disable_cname_lookup_ = local_state->GetBoolean( prefs::kDisableAuthNegotiateCnameLookup); negotiate_enable_port_ = local_state->GetBoolean( prefs::kEnableAuthNegotiatePort); auth_server_whitelist_ = local_state->GetString(prefs::kAuthServerWhitelist); auth_delegate_whitelist_ = local_state->GetString( prefs::kAuthNegotiateDelegateWhitelist); gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName); pref_proxy_config_tracker_.reset( ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState( local_state)); ChromeNetworkDelegate::InitializePrefsOnUIThread( &system_enable_referrers_, NULL, NULL, local_state); ssl_config_service_manager_.reset( SSLConfigServiceManager::CreateDefaultManager(local_state)); base::Value* dns_client_enabled_default = new base::FundamentalValue( chrome_browser_net::ConfigureAsyncDnsFieldTrial()); local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled, dns_client_enabled_default); dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled, local_state, base::Bind(&IOThread::UpdateDnsClientEnabled, base::Unretained(this))); dns_client_enabled_.MoveToThread( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)); #if defined(ENABLE_CONFIGURATION_POLICY) is_spdy_disabled_by_policy_ = policy_service->GetPolicies( policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())).Get( policy::key::kDisableSpdy) != NULL; #endif // ENABLE_CONFIGURATION_POLICY BrowserThread::SetDelegate(BrowserThread::IO, this); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void Ins_ALIGNRP( INS_ARG ) { Int point; TT_F26Dot6 distance; (void)args; if ( CUR.top < CUR.GS.loop ) { CUR.error = TT_Err_Invalid_Reference; return; } while ( CUR.GS.loop > 0 ) { CUR.args--; point = (Int)CUR.stack[CUR.args]; if ( BOUNDS( point, CUR.zp1.n_points ) ) { CUR.error = TT_Err_Invalid_Reference; return; } distance = CUR_Func_project( CUR.zp1.cur_x[point] - CUR.zp0.cur_x[CUR.GS.rp0], CUR.zp1.cur_y[point] - CUR.zp0.cur_y[CUR.GS.rp0] ); CUR_Func_move( &CUR.zp1, point, -distance ); CUR.GS.loop--; } CUR.GS.loop = 1; CUR.new_top = CUR.args; } Commit Message: CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> strictFunctionCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.strictFunction"); if (args.Length() < 3) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); ExceptionCode ec = 0; { STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); EXCEPTION_BLOCK(float, a, static_cast<float>(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)->NumberValue())); EXCEPTION_BLOCK(int, b, V8int::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8int::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); RefPtr<bool> result = imp->strictFunction(str, a, b, ec); if (UNLIKELY(ec)) goto fail; return toV8(result.release(), args.GetIsolate()); } fail: V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: Guint JBIG2MMRDecoder::get24Bits() { while (bufLen < 24) { buf = (buf << 8) | (str->getChar() & 0xff); bufLen += 8; ++nBytesRead; } return (buf >> (bufLen - 24)) & 0xffffff; } Commit Message: CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void vfree_work(struct work_struct *work) { struct mem_cgroup *memcg; memcg = container_of(work, struct mem_cgroup, work_freeing); vfree(memcg); } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool MultibufferDataSource::DidGetOpaqueResponseViaServiceWorker() const { return url_data()->has_opaque_data(); } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Target: 1 Example 2: Code: std::unique_ptr<AXProperty> createRelatedNodeListProperty( const String& key, AXObject::AXObjectVector& nodes, const QualifiedName& attr, AXObject& axObject) { std::unique_ptr<AXValue> nodeListValue = createRelatedNodeListValue(nodes); const AtomicString& attrValue = axObject.getAttribute(attr); nodeListValue->setValue(protocol::StringValue::create(attrValue)); return createProperty(key, std::move(nodeListValue)); } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: idna_strerror (Idna_rc rc) { const char *p; bindtextdomain (PACKAGE, LOCALEDIR); switch (rc) { case IDNA_SUCCESS: p = _("Success"); break; case IDNA_STRINGPREP_ERROR: p = _("String preparation failed"); break; case IDNA_PUNYCODE_ERROR: p = _("Punycode failed"); break; case IDNA_CONTAINS_NON_LDH: p = _("Non-digit/letter/hyphen in input"); break; case IDNA_CONTAINS_MINUS: p = _("Forbidden leading or trailing minus sign (`-')"); break; case IDNA_INVALID_LENGTH: p = _("Output would be too large or too small"); break; case IDNA_NO_ACE_PREFIX: p = _("Input does not start with ACE prefix (`xn--')"); break; case IDNA_ROUNDTRIP_VERIFY_ERROR: p = _("String not idempotent under ToASCII"); break; case IDNA_CONTAINS_ACE_PREFIX: p = _("Input already contain ACE prefix (`xn--')"); break; case IDNA_ICONV_ERROR: p = _("System iconv failed"); break; case IDNA_MALLOC_ERROR: p = _("Cannot allocate memory"); break; case IDNA_DLOPEN_ERROR: p = _("System dlopen failed"); break; default: p = _("Unknown error"); break; } return p; } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SYSCALL_DEFINE3(shmctl, int, shmid, int, cmd, struct shmid_ds __user *, buf) { struct shmid_kernel *shp; int err, version; struct ipc_namespace *ns; if (cmd < 0 || shmid < 0) return -EINVAL; version = ipc_parse_version(&cmd); ns = current->nsproxy->ipc_ns; switch (cmd) { case IPC_INFO: case SHM_INFO: case SHM_STAT: case IPC_STAT: return shmctl_nolock(ns, shmid, cmd, version, buf); case IPC_RMID: case IPC_SET: return shmctl_down(ns, shmid, cmd, buf, version); case SHM_LOCK: case SHM_UNLOCK: { struct file *shm_file; rcu_read_lock(); shp = shm_obtain_object_check(ns, shmid); if (IS_ERR(shp)) { err = PTR_ERR(shp); goto out_unlock1; } audit_ipc_obj(&(shp->shm_perm)); err = security_shm_shmctl(shp, cmd); if (err) goto out_unlock1; ipc_lock_object(&shp->shm_perm); if (!ns_capable(ns->user_ns, CAP_IPC_LOCK)) { kuid_t euid = current_euid(); err = -EPERM; if (!uid_eq(euid, shp->shm_perm.uid) && !uid_eq(euid, shp->shm_perm.cuid)) goto out_unlock0; if (cmd == SHM_LOCK && !rlimit(RLIMIT_MEMLOCK)) goto out_unlock0; } shm_file = shp->shm_file; if (is_file_hugepages(shm_file)) goto out_unlock0; if (cmd == SHM_LOCK) { struct user_struct *user = current_user(); err = shmem_lock(shm_file, 1, user); if (!err && !(shp->shm_perm.mode & SHM_LOCKED)) { shp->shm_perm.mode |= SHM_LOCKED; shp->mlock_user = user; } goto out_unlock0; } /* SHM_UNLOCK */ if (!(shp->shm_perm.mode & SHM_LOCKED)) goto out_unlock0; shmem_lock(shm_file, 0, shp->mlock_user); shp->shm_perm.mode &= ~SHM_LOCKED; shp->mlock_user = NULL; get_file(shm_file); ipc_unlock_object(&shp->shm_perm); rcu_read_unlock(); shmem_unlock_mapping(shm_file->f_mapping); fput(shm_file); return err; } default: return -EINVAL; } out_unlock0: ipc_unlock_object(&shp->shm_perm); out_unlock1: rcu_read_unlock(); return err; } Commit Message: ipc,shm: fix shm_file deletion races When IPC_RMID races with other shm operations there's potential for use-after-free of the shm object's associated file (shm_file). Here's the race before this patch: TASK 1 TASK 2 ------ ------ shm_rmid() ipc_lock_object() shmctl() shp = shm_obtain_object_check() shm_destroy() shum_unlock() fput(shp->shm_file) ipc_lock_object() shmem_lock(shp->shm_file) <OOPS> The oops is caused because shm_destroy() calls fput() after dropping the ipc_lock. fput() clears the file's f_inode, f_path.dentry, and f_path.mnt, which causes various NULL pointer references in task 2. I reliably see the oops in task 2 if with shmlock, shmu This patch fixes the races by: 1) set shm_file=NULL in shm_destroy() while holding ipc_object_lock(). 2) modify at risk operations to check shm_file while holding ipc_object_lock(). Example workloads, which each trigger oops... Workload 1: while true; do id=$(shmget 1 4096) shm_rmid $id & shmlock $id & wait done The oops stack shows accessing NULL f_inode due to racing fput: _raw_spin_lock shmem_lock SyS_shmctl Workload 2: while true; do id=$(shmget 1 4096) shmat $id 4096 & shm_rmid $id & wait done The oops stack is similar to workload 1 due to NULL f_inode: touch_atime shmem_mmap shm_mmap mmap_region do_mmap_pgoff do_shmat SyS_shmat Workload 3: while true; do id=$(shmget 1 4096) shmlock $id shm_rmid $id & shmunlock $id & wait done The oops stack shows second fput tripping on an NULL f_inode. The first fput() completed via from shm_destroy(), but a racing thread did a get_file() and queued this fput(): locks_remove_flock __fput ____fput task_work_run do_notify_resume int_signal Fixes: c2c737a0461e ("ipc,shm: shorten critical region for shmat") Fixes: 2caacaa82a51 ("ipc,shm: shorten critical region for shmctl") Signed-off-by: Greg Thelen <[email protected]> Cc: Davidlohr Bueso <[email protected]> Cc: Rik van Riel <[email protected]> Cc: Manfred Spraul <[email protected]> Cc: <[email protected]> # 3.10.17+ 3.11.6+ Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: static inline int __sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { int err = security_socket_recvmsg(sock, msg, size, flags); return err ?: __sock_recvmsg_nosec(iocb, sock, msg, size, flags); } Commit Message: Fix order of arguments to compat_put_time[spec|val] Commit 644595f89620 ("compat: Handle COMPAT_USE_64BIT_TIME in net/socket.c") introduced a bug where the helper functions to take either a 64-bit or compat time[spec|val] got the arguments in the wrong order, passing the kernel stack pointer off as a user pointer (and vice versa). Because of the user address range check, that in turn then causes an EFAULT due to the user pointer range checking failing for the kernel address. Incorrectly resuling in a failed system call for 32-bit processes with a 64-bit kernel. On odder architectures like HP-PA (with separate user/kernel address spaces), it can be used read kernel memory. Signed-off-by: Mikulas Patocka <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PasswordInputType::EnableSecureTextInput() { LocalFrame* frame = GetElement().GetDocument().GetFrame(); if (!frame) return; frame->Selection().SetUseSecureKeyboardEntryWhenActive(true); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id) { struct snd_msnd *chip = dev_id; void *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF; /* Send ack to DSP */ /* inb(chip->io + HP_RXL); */ /* Evaluate queued DSP messages */ while (readw(chip->DSPQ + JQS_wTail) != readw(chip->DSPQ + JQS_wHead)) { u16 wTmp; snd_msnd_eval_dsp_msg(chip, readw(pwDSPQData + 2 * readw(chip->DSPQ + JQS_wHead))); wTmp = readw(chip->DSPQ + JQS_wHead) + 1; if (wTmp > readw(chip->DSPQ + JQS_wSize)) writew(0, chip->DSPQ + JQS_wHead); else writew(wTmp, chip->DSPQ + JQS_wHead); } /* Send ack to DSP */ inb(chip->io + HP_RXL); return IRQ_HANDLED; } Commit Message: ALSA: msnd: Optimize / harden DSP and MIDI loops The ISA msnd drivers have loops fetching the ring-buffer head, tail and size values inside the loops. Such codes are inefficient and fragile. This patch optimizes it, and also adds the sanity check to avoid the endless loops. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196131 Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196133 Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: void WaitUntilStable() { uint32_t current_frame_number = view_->RendererFrameNumber(); uint32_t previous_frame_number; do { base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), delta_); run_loop.Run(); previous_frame_number = current_frame_number; current_frame_number = view_->RendererFrameNumber(); } while (current_frame_number != previous_frame_number); } Commit Message: Add a check for disallowing remote frame navigations to local resources. Previously, RemoteFrame navigations did not perform any renderer-side checks and relied solely on the browser-side logic to block disallowed navigations via mechanisms like FilterURL. This means that blocked remote frame navigations were silently navigated to about:blank without any console error message. This CL adds a CanDisplay check to the remote navigation path to match an equivalent check done for local frame navigations. This way, the renderer can consistently block disallowed navigations in both cases and output an error message. Bug: 894399 Change-Id: I172f68f77c1676f6ca0172d2a6c78f7edc0e3b7a Reviewed-on: https://chromium-review.googlesource.com/c/1282390 Reviewed-by: Charlie Reis <[email protected]> Reviewed-by: Nate Chapin <[email protected]> Commit-Queue: Alex Moshchuk <[email protected]> Cr-Commit-Position: refs/heads/master@{#601022} CWE ID: CWE-732 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Bignum ssh1_pkt_getmp(struct Packet *pkt) { int j; Bignum b; j = ssh1_read_bignum(pkt->body + pkt->savedpos, pkt->length - pkt->savedpos, &b); if (j < 0) return NULL; pkt->savedpos += j; return b; } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Cues::PreloadCuePoint(long& cue_points_size, long long pos) const { assert(m_count == 0); if (m_preload_count >= cue_points_size) { const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size; CuePoint** const qq = new CuePoint* [n]; CuePoint** q = qq; // beginning of target CuePoint** p = m_cue_points; // beginning of source CuePoint** const pp = p + m_preload_count; // end of source while (p != pp) *q++ = *p++; delete[] m_cue_points; m_cue_points = qq; cue_points_size = n; } CuePoint* const pCP = new CuePoint(m_preload_count, pos); m_cue_points[m_preload_count++] = pCP; } 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 Target: 1 Example 2: Code: void RenderLayerScrollableArea::updateResizerStyle() { if (!m_resizer && !box().canResize()) return; RenderObject* actualRenderer = rendererForScrollbar(box()); RefPtr<RenderStyle> resizer = box().hasOverflowClip() ? actualRenderer->getUncachedPseudoStyle(PseudoStyleRequest(RESIZER), actualRenderer->style()) : PassRefPtr<RenderStyle>(nullptr); if (resizer) { if (!m_resizer) { m_resizer = RenderScrollbarPart::createAnonymous(&box().document()); m_resizer->setParent(&box()); } m_resizer->setStyle(resizer.release()); } else if (m_resizer) { m_resizer->destroy(); m_resizer = nullptr; } } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 [email protected] Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BoundingBox "BoundingBox:" #define BeginDocument "BeginDocument:" #define BeginXMPPacket "<?xpacket begin=" #define EndXMPPacket "<?xpacket end=" #define ICCProfile "BeginICCProfile:" #define CMYKCustomColor "CMYKCustomColor:" #define CMYKProcessColor "CMYKProcessColor:" #define DocumentMedia "DocumentMedia:" #define DocumentCustomColors "DocumentCustomColors:" #define DocumentProcessColors "DocumentProcessColors:" #define EndDocument "EndDocument:" #define HiResBoundingBox "HiResBoundingBox:" #define ImageData "ImageData:" #define PageBoundingBox "PageBoundingBox:" #define LanguageLevel "LanguageLevel:" #define PageMedia "PageMedia:" #define Pages "Pages:" #define PhotoshopProfile "BeginPhotoshop:" #define PostscriptLevel "!PS-" #define RenderPostscriptText " Rendering Postscript... " #define SpotColor "+ " char command[MaxTextExtent], *density, filename[MaxTextExtent], geometry[MaxTextExtent], input_filename[MaxTextExtent], message[MaxTextExtent], *options, postscript_filename[MaxTextExtent]; const char *option; const DelegateInfo *delegate_info; GeometryInfo geometry_info; Image *image, *next, *postscript_image; ImageInfo *read_info; int c, file; MagickBooleanType cmyk, fitPage, skip, status; MagickStatusType flags; PointInfo delta, resolution; RectangleInfo page; register char *p; register ssize_t i; SegmentInfo bounds, hires_bounds; short int hex_digits[256]; size_t length, priority; ssize_t count; StringInfo *profile; unsigned long columns, extent, language_level, pages, rows, scene, spotcolor; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Initialize hex values. */ (void) ResetMagickMemory(hex_digits,0,sizeof(hex_digits)); hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); resolution.x=image->x_resolution; resolution.y=image->y_resolution; page.width=(size_t) ceil((double) (page.width*resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) (page.height*resolution.y/delta.y)-0.5); /* Determine page geometry from the Postscript bounding box. */ (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); (void) ResetMagickMemory(command,0,sizeof(command)); cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; (void) ResetMagickMemory(&hires_bounds,0,sizeof(hires_bounds)); priority=0; columns=0; rows=0; extent=0; spotcolor=0; language_level=1; skip=MagickFalse; pages=(~0UL); p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0) { (void) SetImageProperty(image,"ps:Level",command+4); if (GlobExpression(command,"*EPSF-*",MagickTrue) != MagickFalse) pages=1; } if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0) (void) sscanf(command,LanguageLevel " %lu",&language_level); if (LocaleNCompare(Pages,command,strlen(Pages)) == 0) (void) sscanf(command,Pages " %lu",&pages); if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0) (void) sscanf(command,ImageData " %lu %lu",&columns,&rows); if (LocaleNCompare(ICCProfile,command,strlen(ICCProfile)) == 0) { unsigned char *datum; /* Read ICC profile. */ profile=AcquireStringInfo(MaxTextExtent); datum=GetStringInfoDatum(profile); for (i=0; (c=ProfileInteger(image,hex_digits)) != EOF; i++) { if (i >= (ssize_t) GetStringInfoLength(profile)) { SetStringInfoLength(profile,(size_t) i << 1); datum=GetStringInfoDatum(profile); } datum[i]=(unsigned char) c; } SetStringInfoLength(profile,(size_t) i+1); (void) SetImageProfile(image,"icc",profile); profile=DestroyStringInfo(profile); continue; } if (LocaleNCompare(PhotoshopProfile,command,strlen(PhotoshopProfile)) == 0) { unsigned char *p; /* Read Photoshop profile. */ count=(ssize_t) sscanf(command,PhotoshopProfile " %lu",&extent); if (count != 1) continue; length=extent; profile=BlobToStringInfo((const void *) NULL,length); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) *p++=(unsigned char) ProfileInteger(image,hex_digits); (void) SetImageProfile(image,"8bim",profile); profile=DestroyStringInfo(profile); } continue; } if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0) { register size_t i; /* Read XMP profile. */ p=command; profile=StringToStringInfo(command); for (i=GetStringInfoLength(profile)-1; c != EOF; i++) { SetStringInfoLength(profile,i+1); c=ReadBlobByte(image); GetStringInfoDatum(profile)[i]=(unsigned char) c; *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\0'; p=command; if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0) break; } SetStringInfoLength(profile,i); (void) SetImageProfile(image,"xmp",profile); profile=DestroyStringInfo(profile); continue; } /* Is this a CMYK document? */ length=strlen(DocumentProcessColors); if (LocaleNCompare(DocumentProcessColors,command,length) == 0) { if ((GlobExpression(command,"*Cyan*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Magenta*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Yellow*",MagickTrue) != MagickFalse)) cmyk=MagickTrue; } if (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; length=strlen(DocumentCustomColors); if ((LocaleNCompare(DocumentCustomColors,command,length) == 0) || (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) || (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)) { char property[MaxTextExtent], *value; register char *p; /* Note spot names. */ (void) FormatLocaleString(property,MaxTextExtent,"ps:SpotColor-%.20g", (double) (spotcolor++)); for (p=command; *p != '\0'; p++) if (isspace((int) (unsigned char) *p) != 0) break; value=AcquireString(p); (void) SubstituteString(&value,"(",""); (void) SubstituteString(&value,")",""); (void) StripString(value); (void) SetImageProperty(image,property,value); value=DestroyString(value); continue; } if (image_info->page != (char *) NULL) continue; /* Note region defined by bounding box. */ count=0; i=0; if (LocaleNCompare(BoundingBox,command,strlen(BoundingBox)) == 0) { count=(ssize_t) sscanf(command,BoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=2; } if (LocaleNCompare(DocumentMedia,command,strlen(DocumentMedia)) == 0) { count=(ssize_t) sscanf(command,DocumentMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(HiResBoundingBox,command,strlen(HiResBoundingBox)) == 0) { count=(ssize_t) sscanf(command,HiResBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=3; } if (LocaleNCompare(PageBoundingBox,command,strlen(PageBoundingBox)) == 0) { count=(ssize_t) sscanf(command,PageBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(PageMedia,command,strlen(PageMedia)) == 0) { count=(ssize_t) sscanf(command,PageMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if ((count != 4) || (i < (ssize_t) priority)) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) if (i == (ssize_t) priority) continue; hires_bounds=bounds; priority=i; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set Postscript render geometry. */ (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+.15g%+.15g", hires_bounds.x2-hires_bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,"ps:HiResBoundingBox",geometry); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* resolution.y/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,"eps:fit-page"); if (option != (char *) NULL) { char *geometry; MagickStatusType flags; geometry=GetPageGeometry(option); flags=ParseMetaGeometry(geometry,&page.x,&page.y,&page.width,&page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",option); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->y_resolution/ delta.y) -0.5); geometry=DestroyString(geometry); fitPage=MagickTrue; } (void) CloseBlob(image); if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(command,"/setpagedevice {pop} bind 1 index where {" "dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\n" "<</UseCIEColor true>>setpagedevice\n",MaxTextExtent); count=write(file,command,(unsigned int) strlen(command)); if (image_info->page == (char *) NULL) { char translate_geometry[MaxTextExtent]; (void) FormatLocaleString(translate_geometry,MaxTextExtent, "%g %g translate\n",-hires_bounds.x1,-hires_bounds.y1); count=write(file,translate_geometry,(unsigned int) strlen(translate_geometry)); } file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImageList(image); return((Image *) NULL); } density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MaxTextExtent,"%gx%g",resolution.x, resolution.y); (void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { char pages[MaxTextExtent]; (void) FormatLocaleString(pages,MaxTextExtent,"-dFirstPage=%.20g " "-dLastPage=%.20g ",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MaxTextExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } if (*image_info->magick == 'E') { option=GetImageOption(image_info,"eps:use-cropbox"); if ((option == (const char *) NULL) || (IsStringTrue(option) != MagickFalse)) (void) ConcatenateMagickString(options,"-dEPSCrop ",MaxTextExtent); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,"-dEPSFitPage ",MaxTextExtent); } (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,"%d",MaxTextExtent); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\0'; status=InvokePostscriptDelegate(read_info->verbose,command,message,exception); (void) InterpretImageFilename(image_info,image,filename,1, read_info->filename); if ((status == MagickFalse) || (IsPostscriptRendered(read_info->filename) == MagickFalse)) { (void) ConcatenateMagickString(command," -c showpage",MaxTextExtent); status=InvokePostscriptDelegate(read_info->verbose,command,message, exception); } (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); postscript_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&postscript_image,next); } (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (postscript_image == (Image *) NULL) { if (*message != '\0') (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, "PostscriptDelegateFailed","`%s'",message); image=DestroyImageList(image); return((Image *) NULL); } if (LocaleCompare(postscript_image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(postscript_image,exception); if (cmyk_image != (Image *) NULL) { postscript_image=DestroyImageList(postscript_image); postscript_image=cmyk_image; } } if (image_info->number_scenes != 0) { Image *clone_image; register ssize_t i; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&postscript_image,clone_image); } } do { (void) CopyMagickString(postscript_image->filename,filename,MaxTextExtent); (void) CopyMagickString(postscript_image->magick,image->magick, MaxTextExtent); if (columns != 0) postscript_image->magick_columns=columns; if (rows != 0) postscript_image->magick_rows=rows; postscript_image->page=page; (void) CloneImageProfiles(postscript_image,image); (void) CloneImageProperties(postscript_image,image); next=SyncNextImageInList(postscript_image); if (next != (Image *) NULL) postscript_image=next; } while (next != (Image *) NULL); image=DestroyImageList(image); scene=0; for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(postscript_image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/715 CWE ID: CWE-834 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ChromeRenderProcessObserver::OnControlMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver, message) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess, OnSetIsIncognitoProcess) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetCacheCapacities, OnSetCacheCapacities) IPC_MESSAGE_HANDLER(ChromeViewMsg_ClearCache, OnClearCache) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup, OnSetFieldTrialGroup) #if defined(USE_TCMALLOC) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetTcmallocHeapProfiling, OnSetTcmallocHeapProfiling) IPC_MESSAGE_HANDLER(ChromeViewMsg_WriteTcmallocHeapProfile, OnWriteTcmallocHeapProfile) #endif IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats, OnGetV8HeapStats) IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats, OnGetCacheResourceStats) IPC_MESSAGE_HANDLER(ChromeViewMsg_PurgeMemory, OnPurgeMemory) IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules, OnSetContentSettingRules) IPC_MESSAGE_HANDLER(ChromeViewMsg_ToggleWebKitSharedTimer, OnToggleWebKitSharedTimer) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Disable tcmalloc profile files. BUG=154983 [email protected] NOTRY=true Review URL: https://chromiumcodereview.appspot.com/11087041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static int crc32c_cra_init(struct crypto_tfm *tfm) { struct chksum_ctx *mctx = crypto_tfm_ctx(tfm); mctx->key = ~0; return 0; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderProcessHostImpl::SetIsUsed() { is_unused_ = false; } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to, int tolen) { struct pathComponent *pc; int elen = 0; int comp_len; unsigned char *p = to; /* Reserve one byte for terminating \0 */ tolen--; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) break; /* Fall through */ case 2: if (tolen == 0) return -ENAMETOOLONG; p = to; *p++ = '/'; tolen--; break; case 3: if (tolen < 3) return -ENAMETOOLONG; memcpy(p, "../", 3); p += 3; tolen -= 3; break; case 4: if (tolen < 2) return -ENAMETOOLONG; memcpy(p, "./", 2); p += 2; tolen -= 2; /* that would be . - just ignore */ break; case 5: comp_len = udf_get_filename(sb, pc->componentIdent, pc->lengthComponentIdent, p, tolen); p += comp_len; tolen -= comp_len; if (tolen == 0) return -ENAMETOOLONG; *p++ = '/'; tolen--; break; } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; return 0; } Commit Message: udf: Check component length before reading it Check that length specified in a component of a symlink fits in the input buffer we are reading. Also properly ignore component length for component types that do not use it. Otherwise we read memory after end of buffer for corrupted udf image. Reported-by: Carl Henrik Lunde <[email protected]> CC: [email protected] Signed-off-by: Jan Kara <[email protected]> CWE ID: Target: 1 Example 2: Code: process_ts_set_error_info_pdu(STREAM s, uint32 * ext_disc_reason) { in_uint32_le(s, *ext_disc_reason); logger(Protocol, Debug, "process_ts_set_error_info_pdu(), error info = %d", *ext_disc_reason); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool WebContentsImpl::IsHidden() { return capturer_count_ == 0 && !should_normally_be_visible_; } Commit Message: Cancel JavaScript dialogs when an interstitial appears. BUG=295695 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/24360011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ExtensionScriptAndCaptureVisibleTest() : http_url("http://www.google.com"), http_url_with_path("http://www.google.com/index.html"), https_url("https://www.google.com"), example_com("https://example.com"), test_example_com("https://test.example.com"), sample_example_com("https://sample.example.com"), file_url("file:///foo/bar"), favicon_url("chrome://favicon/http://www.google.com"), extension_url("chrome-extension://" + crx_file::id_util::GenerateIdForPath( base::FilePath(FILE_PATH_LITERAL("foo")))), settings_url("chrome://settings"), about_url("about:flags") { urls_.insert(http_url); urls_.insert(http_url_with_path); urls_.insert(https_url); urls_.insert(example_com); urls_.insert(test_example_com); urls_.insert(sample_example_com); urls_.insert(file_url); urls_.insert(favicon_url); urls_.insert(extension_url); urls_.insert(settings_url); urls_.insert(about_url); PermissionsData::SetPolicyDelegate(NULL); } Commit Message: [Extensions] Restrict tabs.captureVisibleTab() Modify the permissions for tabs.captureVisibleTab(). Instead of just checking for <all_urls> and assuming its safe, do the following: - If the page is a "normal" web page (e.g., http/https), allow the capture if the extension has activeTab granted or <all_urls>. - If the page is a file page (file:///), allow the capture if the extension has file access *and* either of the <all_urls> or activeTab permissions. - If the page is a chrome:// page, allow the capture only if the extension has activeTab granted. Bug: 810220 Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304 Reviewed-on: https://chromium-review.googlesource.com/981195 Commit-Queue: Devlin <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Cr-Commit-Position: refs/heads/master@{#548891} CWE ID: CWE-20 Target: 1 Example 2: Code: BrowserContextIOData::GetTemporarySavedPermissionContext() const { return temporary_saved_permission_context_.get(); } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: LayerTreeHostImpl::~LayerTreeHostImpl() { DCHECK(task_runner_provider_->IsImplThread()); TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()"); TRACE_EVENT_OBJECT_DELETED_WITH_ID(TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_); DCHECK(!compositor_frame_sink_); DCHECK(!resource_provider_); DCHECK(!resource_pool_); DCHECK(!single_thread_synchronous_task_graph_runner_); DCHECK(!image_decode_cache_); if (input_handler_client_) { input_handler_client_->WillShutdown(); input_handler_client_ = NULL; } if (scroll_elasticity_helper_) scroll_elasticity_helper_.reset(); if (recycle_tree_) recycle_tree_->Shutdown(); if (pending_tree_) pending_tree_->Shutdown(); active_tree_->Shutdown(); recycle_tree_ = nullptr; pending_tree_ = nullptr; active_tree_ = nullptr; mutator_host_->ClearMutators(); mutator_host_->SetMutatorHostClient(nullptr); } Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 [email protected], [email protected] CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954} CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PixelBufferRasterWorkerPool::CheckForCompletedRasterTasks() { TRACE_EVENT0( "cc", "PixelBufferRasterWorkerPool::CheckForCompletedRasterTasks"); DCHECK(should_notify_client_if_no_tasks_are_pending_); check_for_completed_raster_tasks_callback_.Cancel(); check_for_completed_raster_tasks_pending_ = false; CheckForCompletedWorkerTasks(); CheckForCompletedUploads(); FlushUploads(); bool will_notify_client_that_no_tasks_required_for_activation_are_pending = (should_notify_client_if_no_tasks_required_for_activation_are_pending_ && !HasPendingTasksRequiredForActivation()); bool will_notify_client_that_no_tasks_are_pending = (should_notify_client_if_no_tasks_are_pending_ && !HasPendingTasks()); should_notify_client_if_no_tasks_required_for_activation_are_pending_ &= !will_notify_client_that_no_tasks_required_for_activation_are_pending; should_notify_client_if_no_tasks_are_pending_ &= !will_notify_client_that_no_tasks_are_pending; scheduled_raster_task_count_ = 0; if (PendingRasterTaskCount()) ScheduleMoreTasks(); TRACE_EVENT_ASYNC_STEP_INTO1( "cc", "ScheduledTasks", this, StateName(), "state", TracedValue::FromValue(StateAsValue().release())); if (HasPendingTasks()) ScheduleCheckForCompletedRasterTasks(); if (will_notify_client_that_no_tasks_required_for_activation_are_pending) { DCHECK(std::find_if(raster_tasks_required_for_activation().begin(), raster_tasks_required_for_activation().end(), WasCanceled) == raster_tasks_required_for_activation().end()); client()->DidFinishRunningTasksRequiredForActivation(); } if (will_notify_client_that_no_tasks_are_pending) { TRACE_EVENT_ASYNC_END0("cc", "ScheduledTasks", this); DCHECK(!HasPendingTasksRequiredForActivation()); client()->DidFinishRunningTasks(); } } Commit Message: cc: Simplify raster task completion notification logic (Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/) Previously the pixel buffer raster worker pool used a combination of polling and explicit notifications from the raster worker pool to decide when to tell the client about the completion of 1) all tasks or 2) the subset of tasks required for activation. This patch simplifies the logic by only triggering the notification based on the OnRasterTasksFinished and OnRasterTasksRequiredForActivationFinished calls from the worker pool. BUG=307841,331534 Review URL: https://codereview.chromium.org/99873007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: void Element::setRegionOversetState(RegionOversetState state) { ensureElementRareData()->setRegionOversetState(state); } Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void napi_complete_done(struct napi_struct *n, int work_done) { unsigned long flags; /* * don't let napi dequeue from the cpu poll list * just in case its running on a different cpu */ if (unlikely(test_bit(NAPI_STATE_NPSVC, &n->state))) return; if (n->gro_list) { unsigned long timeout = 0; if (work_done) timeout = n->dev->gro_flush_timeout; if (timeout) hrtimer_start(&n->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED); else napi_gro_flush(n, false); } if (likely(list_empty(&n->poll_list))) { WARN_ON_ONCE(!test_and_clear_bit(NAPI_STATE_SCHED, &n->state)); } else { /* If n->poll_list is not empty, we need to mask irqs */ local_irq_save(flags); __napi_complete(n); local_irq_restore(flags); } } Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation. When drivers express support for TSO of encapsulated packets, they only mean that they can do it for one layer of encapsulation. Supporting additional levels would mean updating, at a minimum, more IP length fields and they are unaware of this. No encapsulation device expresses support for handling offloaded encapsulated packets, so we won't generate these types of frames in the transmit path. However, GRO doesn't have a check for multiple levels of encapsulation and will attempt to build them. UDP tunnel GRO actually does prevent this situation but it only handles multiple UDP tunnels stacked on top of each other. This generalizes that solution to prevent any kind of tunnel stacking that would cause problems. Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack") Signed-off-by: Jesse Gross <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-400 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool TradQT_Manager::ParseCachedBoxes ( const MOOV_Manager & moovMgr ) { MOOV_Manager::BoxInfo udtaInfo; MOOV_Manager::BoxRef udtaRef = moovMgr.GetBox ( "moov/udta", &udtaInfo ); if ( udtaRef == 0 ) return false; for ( XMP_Uns32 i = 0; i < udtaInfo.childCount; ++i ) { MOOV_Manager::BoxInfo currInfo; MOOV_Manager::BoxRef currRef = moovMgr.GetNthChild ( udtaRef, i, &currInfo ); if ( currRef == 0 ) break; // Sanity check, should not happen. if ( (currInfo.boxType >> 24) != 0xA9 ) continue; if ( currInfo.contentSize < 2+2+1 ) continue; // Want enough for a non-empty value. InfoMapPos newInfo = this->parsedBoxes.insert ( this->parsedBoxes.end(), InfoMap::value_type ( currInfo.boxType, ParsedBoxInfo ( currInfo.boxType ) ) ); std::vector<ValueInfo> * newValues = &newInfo->second.values; XMP_Uns8 * boxPtr = (XMP_Uns8*) currInfo.content; XMP_Uns8 * boxEnd = boxPtr + currInfo.contentSize; XMP_Uns16 miniLen, macLang; for ( ; boxPtr < boxEnd-4; boxPtr += miniLen ) { miniLen = 4 + GetUns16BE ( boxPtr ); // ! Include header in local miniLen. macLang = GetUns16BE ( boxPtr+2); if ( (miniLen <= 4) || (miniLen > (boxEnd - boxPtr)) ) continue; // Ignore bad or empty values. XMP_StringPtr valuePtr = (char*)(boxPtr+4); size_t valueLen = miniLen - 4; newValues->push_back ( ValueInfo() ); ValueInfo * newValue = &newValues->back(); newValue->macLang = macLang; if ( IsMacLangKnown ( macLang ) ) newValue->xmpLang = GetXMPLang ( macLang ); newValue->macValue.assign ( valuePtr, valueLen ); } } return (! this->parsedBoxes.empty()); } // TradQT_Manager::ParseCachedBoxes Commit Message: CWE ID: CWE-835 Target: 1 Example 2: Code: static int sha224_init(struct shash_desc *desc) { struct s390_sha_ctx *sctx = shash_desc_ctx(desc); sctx->state[0] = SHA224_H0; sctx->state[1] = SHA224_H1; sctx->state[2] = SHA224_H2; sctx->state[3] = SHA224_H3; sctx->state[4] = SHA224_H4; sctx->state[5] = SHA224_H5; sctx->state[6] = SHA224_H6; sctx->state[7] = SHA224_H7; sctx->count = 0; sctx->func = KIMD_SHA_256; return 0; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void impeg2d_get_frm_buf(yuv_buf_t *ps_frm_buf,UWORD8 *pu1_frm,UWORD32 u4_width,UWORD32 u4_height) { UWORD32 u4_luma_size = u4_width * u4_height; UWORD32 u4_chroma_size = (u4_width * u4_height)>>2; ps_frm_buf->pu1_y = pu1_frm; ps_frm_buf->pu1_u = pu1_frm + u4_luma_size; ps_frm_buf->pu1_v = pu1_frm + u4_luma_size + u4_chroma_size; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ExternalProtocolHandler::LaunchUrlWithDelegate( const GURL& url, int render_process_host_id, int render_view_routing_id, ui::PageTransition page_transition, bool has_user_gesture, Delegate* delegate) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string escaped_url_string = net::EscapeExternalHandlerValue(url.spec()); GURL escaped_url(escaped_url_string); content::WebContents* web_contents = tab_util::GetWebContentsByID( render_process_host_id, render_view_routing_id); Profile* profile = nullptr; if (web_contents) // Maybe NULL during testing. profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); BlockState block_state = GetBlockStateWithDelegate(escaped_url.scheme(), delegate, profile); if (block_state == BLOCK) { if (delegate) delegate->BlockRequest(); return; } g_accept_requests = false; shell_integration::DefaultWebClientWorkerCallback callback = base::Bind( &OnDefaultProtocolClientWorkerFinished, url, render_process_host_id, render_view_routing_id, block_state == UNKNOWN, page_transition, has_user_gesture, delegate); CreateShellWorker(callback, escaped_url.scheme(), delegate) ->StartCheckIsDefault(); } Commit Message: Reland "Launching an external protocol handler now escapes the URL." This is a reland of 2401e58572884b3561e4348d64f11ac74667ef02 Original change's description: > Launching an external protocol handler now escapes the URL. > > Fixes bug introduced in r102449. > > Bug: 785809 > Change-Id: I9e6dd1031dd7e7b8d378b138ab151daefdc0c6dc > Reviewed-on: https://chromium-review.googlesource.com/778747 > Commit-Queue: Matt Giuca <[email protected]> > Reviewed-by: Eric Lawrence <[email protected]> > Reviewed-by: Ben Wells <[email protected]> > Cr-Commit-Position: refs/heads/master@{#518848} Bug: 785809 Change-Id: Ib8954584004ff5681654398db76d48cdf4437df7 Reviewed-on: https://chromium-review.googlesource.com/788551 Reviewed-by: Ben Wells <[email protected]> Commit-Queue: Matt Giuca <[email protected]> Cr-Commit-Position: refs/heads/master@{#519203} CWE ID: CWE-20 Target: 1 Example 2: Code: static int ModuleInfoCompare(const void *x,const void *y) { const ModuleInfo **p, **q; p=(const ModuleInfo **) x, q=(const ModuleInfo **) y; if (LocaleCompare((*p)->path,(*q)->path) == 0) return(LocaleCompare((*p)->tag,(*q)->tag)); return(LocaleCompare((*p)->path,(*q)->path)); } Commit Message: Coder path traversal is not authorized, bug report provided by Masaaki Chida CWE ID: CWE-22 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int alloc_bts_buffer(int cpu) { struct debug_store *ds = per_cpu(cpu_hw_events, cpu).ds; int node = cpu_to_node(cpu); int max, thresh; void *buffer; if (!x86_pmu.bts) return 0; buffer = kmalloc_node(BTS_BUFFER_SIZE, GFP_KERNEL | __GFP_ZERO, node); if (unlikely(!buffer)) return -ENOMEM; max = BTS_BUFFER_SIZE / BTS_RECORD_SIZE; thresh = max / 16; ds->bts_buffer_base = (u64)(unsigned long)buffer; ds->bts_index = ds->bts_buffer_base; ds->bts_absolute_maximum = ds->bts_buffer_base + max * BTS_RECORD_SIZE; ds->bts_interrupt_threshold = ds->bts_absolute_maximum - thresh * BTS_RECORD_SIZE; return 0; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: modifier_init(png_modifier *pm) { memset(pm, 0, sizeof *pm); store_init(&pm->this); pm->modifications = NULL; pm->state = modifier_start; pm->sbitlow = 1U; pm->ngammas = 0; pm->ngamma_tests = 0; pm->gammas = 0; pm->current_gamma = 0; pm->encodings = 0; pm->nencodings = 0; pm->current_encoding = 0; pm->encoding_counter = 0; pm->encoding_ignored = 0; pm->repeat = 0; pm->test_uses_encoding = 0; pm->maxout8 = pm->maxpc8 = pm->maxabs8 = pm->maxcalc8 = 0; pm->maxout16 = pm->maxpc16 = pm->maxabs16 = pm->maxcalc16 = 0; pm->maxcalcG = 0; pm->limit = 4E-3; pm->log8 = pm->log16 = 0; /* Means 'off' */ pm->error_gray_2 = pm->error_gray_4 = pm->error_gray_8 = 0; pm->error_gray_16 = pm->error_color_8 = pm->error_color_16 = 0; pm->error_indexed = 0; pm->use_update_info = 0; pm->interlace_type = PNG_INTERLACE_NONE; pm->test_standard = 0; pm->test_size = 0; pm->test_transform = 0; pm->use_input_precision = 0; pm->use_input_precision_sbit = 0; pm->use_input_precision_16to8 = 0; pm->calculations_use_input_precision = 0; pm->assume_16_bit_calculations = 0; pm->test_gamma_threshold = 0; pm->test_gamma_transform = 0; pm->test_gamma_sbit = 0; pm->test_gamma_scale16 = 0; pm->test_gamma_background = 0; pm->test_gamma_alpha_mode = 0; pm->test_gamma_expand16 = 0; pm->test_exhaustive = 0; pm->log = 0; /* Rely on the memset for all the other fields - there are no pointers */ } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: ofproto_bundle_register(struct ofproto *ofproto, void *aux, const struct ofproto_bundle_settings *s) { return (ofproto->ofproto_class->bundle_set ? ofproto->ofproto_class->bundle_set(ofproto, aux, s) : EOPNOTSUPP); } Commit Message: ofproto: Fix OVS crash when reverting old flows in bundle commit During bundle commit flows which are added in bundle are applied to ofproto in-order. In case if a flow cannot be added (e.g. flow action is go-to group id which does not exist), OVS tries to revert back all previous flows which were successfully applied from the same bundle. This is possible since OVS maintains list of old flows which were replaced by flows from the bundle. While reinserting old flows ovs asserts due to check on rule state != RULE_INITIALIZED. This will work only for new flows, but for old flow the rule state will be RULE_REMOVED. This is causing an assert and OVS crash. The ovs assert check should be modified to != RULE_INSERTED to prevent any existing rule being re-inserted and allow new rules and old rules (in case of revert) to get inserted. Here is an example to trigger the assert: $ ovs-vsctl add-br br-test -- set Bridge br-test datapath_type=netdev $ cat flows.txt flow add table=1,priority=0,in_port=2,actions=NORMAL flow add table=1,priority=0,in_port=3,actions=NORMAL $ ovs-ofctl dump-flows -OOpenflow13 br-test cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=2 actions=NORMAL cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=3 actions=NORMAL $ cat flow-modify.txt flow modify table=1,priority=0,in_port=2,actions=drop flow modify table=1,priority=0,in_port=3,actions=group:10 $ ovs-ofctl bundle br-test flow-modify.txt -OOpenflow13 First flow rule will be modified since it is a valid rule. However second rule is invalid since no group with id 10 exists. Bundle commit tries to revert (insert) the first rule to old flow which results in ovs_assert at ofproto_rule_insert__() since old rule->state = RULE_REMOVED. Signed-off-by: Vishal Deep Ajmera <[email protected]> Signed-off-by: Ben Pfaff <[email protected]> CWE ID: CWE-617 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info,exception); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); if (Frames == 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); quantum_info=DestroyQuantumInfo(quantum_info); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } } RelinquishMagickMemory(BImgBuff); END_OF_READING: clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/362 CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if (layer_info->channel_info[channel].type < -1) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); mask->matte=MagickFalse; channel_image=mask; } offset=TellBlob(image); status=MagickTrue; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } Commit Message: Added missing null check. CWE ID: CWE-476 Target: 1 Example 2: Code: static int arcmsr_hbaB_handle_isr(struct AdapterControlBlock *acb) { uint32_t outbound_doorbell; struct MessageUnit_B *reg = acb->pmuB; outbound_doorbell = readl(reg->iop2drv_doorbell) & acb->outbound_int_enable; if (!outbound_doorbell) return IRQ_NONE; do { writel(~outbound_doorbell, reg->iop2drv_doorbell); writel(ARCMSR_DRV2IOP_END_OF_INTERRUPT, reg->drv2iop_doorbell); if (outbound_doorbell & ARCMSR_IOP2DRV_DATA_WRITE_OK) arcmsr_iop2drv_data_wrote_handle(acb); if (outbound_doorbell & ARCMSR_IOP2DRV_DATA_READ_OK) arcmsr_iop2drv_data_read_handle(acb); if (outbound_doorbell & ARCMSR_IOP2DRV_CDB_DONE) arcmsr_hbaB_postqueue_isr(acb); if (outbound_doorbell & ARCMSR_IOP2DRV_MESSAGE_CMD_DONE) arcmsr_hbaB_message_isr(acb); outbound_doorbell = readl(reg->iop2drv_doorbell) & acb->outbound_int_enable; } while (outbound_doorbell & (ARCMSR_IOP2DRV_DATA_WRITE_OK | ARCMSR_IOP2DRV_DATA_READ_OK | ARCMSR_IOP2DRV_CDB_DONE | ARCMSR_IOP2DRV_MESSAGE_CMD_DONE)); return IRQ_HANDLED; } Commit Message: scsi: arcmsr: Buffer overflow in arcmsr_iop_message_xfer() We need to put an upper bound on "user_len" so the memcpy() doesn't overflow. Cc: <[email protected]> Reported-by: Marco Grassi <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Tomas Henzl <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int platform_irq_count(struct platform_device *dev) { int ret, nr = 0; while ((ret = platform_get_irq(dev, nr)) >= 0) nr++; if (ret == -EPROBE_DEFER) return ret; return nr; } Commit Message: driver core: platform: fix race condition with driver_override The driver_override implementation is susceptible to race condition when different threads are reading vs storing a different driver override. Add locking to avoid race condition. Fixes: 3d713e0e382e ("driver core: platform: add device binding path 'driver_override'") Cc: [email protected] Signed-off-by: Adrian Salido <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: uint32 ResourceTracker::GetLiveObjectsForInstance( PP_Instance instance) const { InstanceMap::const_iterator found = instance_map_.find(instance); if (found == instance_map_.end()) return 0; return static_cast<uint32>(found->second->resources.size() + found->second->object_vars.size()); } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: check_sparse_region (struct tar_sparse_file *file, off_t beg, off_t end) { if (!lseek_or_error (file, beg)) return false; while (beg < end) { size_t bytes_read; size_t rdsize = BLOCKSIZE < end - beg ? BLOCKSIZE : end - beg; char diff_buffer[BLOCKSIZE]; bytes_read = safe_read (file->fd, diff_buffer, rdsize); if (bytes_read == SAFE_READ_ERROR) { read_diag_details (file->stat_info->orig_file_name, beg, rdsize); return false; } if (!zero_block_p (diff_buffer, bytes_read)) { char begbuf[INT_BUFSIZE_BOUND (off_t)]; report_difference (file->stat_info, _("File fragment at %s is not a hole"), offtostr (beg, begbuf)); return false; } beg += bytes_read; } return true; } Commit Message: CWE ID: CWE-835 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret = proc_dointvec(table, write, buffer, lenp, ppos); if (ret || !write) return ret; if (sysctl_perf_cpu_time_max_percent == 100 || sysctl_perf_cpu_time_max_percent == 0) { printk(KERN_WARNING "perf: Dynamic interrupt throttling disabled, can hang your system!\n"); WRITE_ONCE(perf_sample_allowed_ns, 0); } else { update_perf_cpu_limits(); } return 0; } Commit Message: perf/core: Fix the perf_cpu_time_max_percent check Use "proc_dointvec_minmax" instead of "proc_dointvec" to check the input value from user-space. If not, we can set a big value and some vars will overflow like "sysctl_perf_event_sample_rate" which will cause a lot of unexpected problems. Signed-off-by: Tan Xiaojun <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: <[email protected]> Cc: <[email protected]> Cc: Alexander Shishkin <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: hash_foreach_mangle_dict_of_strings (gpointer key, gpointer val, gpointer user_data) { GHashTable *out = (GHashTable*) user_data; GHashTable *in_dict = (GHashTable *) val; HashAndString *data = g_new0 (HashAndString, 1); data->string = (gchar*) key; data->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); g_hash_table_foreach (in_dict, hash_foreach_prepend_string, data); g_hash_table_insert(out, g_strdup ((gchar*) key), data->hash); } Commit Message: CWE ID: CWE-264 Target: 1 Example 2: Code: static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data, int *datalen) { struct rdpkt2_state_tag *st = &ssh->rdpkt2_state; crBegin(ssh->ssh2_rdpkt_crstate); st->pktin = ssh_new_packet(); st->pktin->type = 0; st->pktin->length = 0; if (ssh->sccipher) st->cipherblk = ssh->sccipher->blksize; else st->cipherblk = 8; if (st->cipherblk < 8) st->cipherblk = 8; st->maclen = ssh->scmac ? ssh->scmac->len : 0; if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) && ssh->scmac && !ssh->scmac_etm) { /* * When dealing with a CBC-mode cipher, we want to avoid the * possibility of an attacker's tweaking the ciphertext stream * so as to cause us to feed the same block to the block * cipher more than once and thus leak information * (VU#958563). The way we do this is not to take any * decisions on the basis of anything we've decrypted until * we've verified it with a MAC. That includes the packet * length, so we just read data and check the MAC repeatedly, * and when the MAC passes, see if the length we've got is * plausible. * * This defence is unnecessary in OpenSSH ETM mode, because * the whole point of ETM mode is that the attacker can't * tweak the ciphertext stream at all without the MAC * detecting it before we decrypt anything. */ /* May as well allocate the whole lot now. */ st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA, unsigned char); /* Read an amount corresponding to the MAC. */ for (st->i = 0; st->i < st->maclen; st->i++) { while ((*datalen) == 0) crReturn(NULL); st->pktin->data[st->i] = *(*data)++; (*datalen)--; } st->packetlen = 0; { unsigned char seq[4]; ssh->scmac->start(ssh->sc_mac_ctx); PUT_32BIT(seq, st->incoming_sequence); ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4); } for (;;) { /* Once around this loop per cipher block. */ /* Read another cipher-block's worth, and tack it onto the end. */ for (st->i = 0; st->i < st->cipherblk; st->i++) { while ((*datalen) == 0) crReturn(NULL); st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++; (*datalen)--; } /* Decrypt one more block (a little further back in the stream). */ ssh->sccipher->decrypt(ssh->sc_cipher_ctx, st->pktin->data + st->packetlen, st->cipherblk); /* Feed that block to the MAC. */ ssh->scmac->bytes(ssh->sc_mac_ctx, st->pktin->data + st->packetlen, st->cipherblk); st->packetlen += st->cipherblk; /* See if that gives us a valid packet. */ if (ssh->scmac->verresult(ssh->sc_mac_ctx, st->pktin->data + st->packetlen) && ((st->len = toint(GET_32BIT(st->pktin->data))) == st->packetlen-4)) break; if (st->packetlen >= OUR_V2_PACKETLIMIT) { bombout(("No valid incoming packet found")); ssh_free_packet(st->pktin); crStop(NULL); } } st->pktin->maxlen = st->packetlen + st->maclen; st->pktin->data = sresize(st->pktin->data, st->pktin->maxlen + APIEXTRA, unsigned char); } else if (ssh->scmac && ssh->scmac_etm) { st->pktin->data = snewn(4 + APIEXTRA, unsigned char); /* * OpenSSH encrypt-then-MAC mode: the packet length is * unencrypted, unless the cipher supports length encryption. */ for (st->i = st->len = 0; st->i < 4; st->i++) { while ((*datalen) == 0) crReturn(NULL); st->pktin->data[st->i] = *(*data)++; (*datalen)--; } /* Cipher supports length decryption, so do it */ if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) { /* Keep the packet the same though, so the MAC passes */ unsigned char len[4]; memcpy(len, st->pktin->data, 4); ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence); st->len = toint(GET_32BIT(len)); } else { st->len = toint(GET_32BIT(st->pktin->data)); } /* * _Completely_ silly lengths should be stomped on before they * do us any more damage. */ if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT || st->len % st->cipherblk != 0) { bombout(("Incoming packet length field was garbled")); ssh_free_packet(st->pktin); crStop(NULL); } /* * So now we can work out the total packet length. */ st->packetlen = st->len + 4; /* * Allocate memory for the rest of the packet. */ st->pktin->maxlen = st->packetlen + st->maclen; st->pktin->data = sresize(st->pktin->data, st->pktin->maxlen + APIEXTRA, unsigned char); /* * Read the remainder of the packet. */ for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) { while ((*datalen) == 0) crReturn(NULL); st->pktin->data[st->i] = *(*data)++; (*datalen)--; } /* * Check the MAC. */ if (ssh->scmac && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4, st->incoming_sequence)) { bombout(("Incorrect MAC received on packet")); ssh_free_packet(st->pktin); crStop(NULL); } /* Decrypt everything between the length field and the MAC. */ if (ssh->sccipher) ssh->sccipher->decrypt(ssh->sc_cipher_ctx, st->pktin->data + 4, st->packetlen - 4); } else { st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char); /* * Acquire and decrypt the first block of the packet. This will * contain the length and padding details. */ for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) { while ((*datalen) == 0) crReturn(NULL); st->pktin->data[st->i] = *(*data)++; (*datalen)--; } if (ssh->sccipher) ssh->sccipher->decrypt(ssh->sc_cipher_ctx, st->pktin->data, st->cipherblk); /* * Now get the length figure. */ st->len = toint(GET_32BIT(st->pktin->data)); /* * _Completely_ silly lengths should be stomped on before they * do us any more damage. */ if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT || (st->len + 4) % st->cipherblk != 0) { bombout(("Incoming packet was garbled on decryption")); ssh_free_packet(st->pktin); crStop(NULL); } /* * So now we can work out the total packet length. */ st->packetlen = st->len + 4; /* * Allocate memory for the rest of the packet. */ st->pktin->maxlen = st->packetlen + st->maclen; st->pktin->data = sresize(st->pktin->data, st->pktin->maxlen + APIEXTRA, unsigned char); /* * Read and decrypt the remainder of the packet. */ for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen; st->i++) { while ((*datalen) == 0) crReturn(NULL); st->pktin->data[st->i] = *(*data)++; (*datalen)--; } /* Decrypt everything _except_ the MAC. */ if (ssh->sccipher) ssh->sccipher->decrypt(ssh->sc_cipher_ctx, st->pktin->data + st->cipherblk, st->packetlen - st->cipherblk); /* * Check the MAC. */ if (ssh->scmac && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data, st->len + 4, st->incoming_sequence)) { bombout(("Incorrect MAC received on packet")); ssh_free_packet(st->pktin); crStop(NULL); } } /* Get and sanity-check the amount of random padding. */ st->pad = st->pktin->data[4]; if (st->pad < 4 || st->len - st->pad < 1) { bombout(("Invalid padding length on received packet")); ssh_free_packet(st->pktin); crStop(NULL); } /* * This enables us to deduce the payload length. */ st->payload = st->len - st->pad - 1; st->pktin->length = st->payload + 5; st->pktin->encrypted_len = st->packetlen; st->pktin->sequence = st->incoming_sequence++; st->pktin->length = st->packetlen - st->pad; assert(st->pktin->length >= 0); /* * Decompress packet payload. */ { unsigned char *newpayload; int newlen; if (ssh->sccomp && ssh->sccomp->decompress(ssh->sc_comp_ctx, st->pktin->data + 5, st->pktin->length - 5, &newpayload, &newlen)) { if (st->pktin->maxlen < newlen + 5) { st->pktin->maxlen = newlen + 5; st->pktin->data = sresize(st->pktin->data, st->pktin->maxlen + APIEXTRA, unsigned char); } st->pktin->length = 5 + newlen; memcpy(st->pktin->data + 5, newpayload, newlen); sfree(newpayload); } } /* * RFC 4253 doesn't explicitly say that completely empty packets * with no type byte are forbidden, so treat them as deserving * an SSH_MSG_UNIMPLEMENTED. */ if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */ ssh2_msg_something_unimplemented(ssh, st->pktin); crStop(NULL); } /* * pktin->body and pktin->length should identify the semantic * content of the packet, excluding the initial type byte. */ st->pktin->type = st->pktin->data[5]; st->pktin->body = st->pktin->data + 6; st->pktin->length -= 6; assert(st->pktin->length >= 0); /* one last double-check */ if (ssh->logctx) ssh2_log_incoming_packet(ssh, st->pktin); st->pktin->savedpos = 0; crFinish(st->pktin); } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int clie_5_attach(struct usb_serial *serial) { struct usb_serial_port *port; unsigned int pipe; int j; /* TH55 registers 2 ports. Communication in from the UX50/TH55 uses bulk_in_endpointAddress from port 0. Communication out to the UX50/TH55 uses bulk_out_endpointAddress from port 1 Lets do a quick and dirty mapping */ /* some sanity check */ if (serial->num_ports < 2) return -1; /* port 0 now uses the modified endpoint Address */ port = serial->port[0]; port->bulk_out_endpointAddress = serial->port[1]->bulk_out_endpointAddress; pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress); for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j) port->write_urbs[j]->pipe = pipe; return 0; } Commit Message: USB: serial: visor: fix crash on detecting device without write_urbs The visor driver crashes in clie_5_attach() when a specially crafted USB device without bulk-out endpoint is detected. This fix adds a check that the device has proper configuration expected by the driver. Reported-by: Ralf Spenneberg <[email protected]> Signed-off-by: Vladis Dronov <[email protected]> Fixes: cfb8da8f69b8 ("USB: visor: fix initialisation of UX50/TH55 devices") Cc: stable <[email protected]> Signed-off-by: Johan Hovold <[email protected]> CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PrintPreviewUI::OnCancelPendingPreviewRequest() { g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, -1); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200 Target: 1 Example 2: Code: JSTestNamedConstructor::~JSTestNamedConstructor() { releaseImplIfNotNull(); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebRuntimeFeatures::EnableWebXR(bool enable) { RuntimeEnabledFeatures::SetWebXREnabled(enable); } Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag. The feature has long since been stable (since M64) and doesn't seem to be a need for this flag. BUG=788936 Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0 Reviewed-on: https://chromium-review.googlesource.com/c/1324143 Reviewed-by: Mike West <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Dave Tapuska <[email protected]> Cr-Commit-Position: refs/heads/master@{#607329} CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ActionReply Smb4KMountHelper::mount(const QVariantMap &args) { ActionReply reply; reply.addData("mh_mountpoint", args["mh_mountpoint"]); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); command << args["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << args["mh_command"].toString(); command << args["mh_options"].toStringList(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); #else #endif proc.setProgram(command); proc.start(); if (proc.waitForStarted(-1)) { bool user_kill = false; QStringList command; #if defined(Q_OS_LINUX) command << args["mh_command"].toString(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); command << args["mh_options"].toStringList(); #elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) command << args["mh_command"].toString(); command << args["mh_options"].toStringList(); command << args["mh_unc"].toString(); command << args["mh_mountpoint"].toString(); { } if (HelperSupport::isStopped()) { proc.kill(); user_kill = true; break; } else { } } if (proc.exitStatus() == KProcess::CrashExit) { if (!user_kill) { reply.setErrorCode(ActionReply::HelperError); reply.setErrorDescription(i18n("The mount process crashed.")); return reply; } else { } } else { QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData("mh_error_message", stdErr.trimmed()); } } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: void RenderWidgetHostImpl::WasResized() { WasResized(false); } Commit Message: Force a flush of drawing to the widget when a dialog is shown. BUG=823353 TEST=as in bug Change-Id: I5da777068fc29c5638ef02d50e59d5d7b2729260 Reviewed-on: https://chromium-review.googlesource.com/971661 Reviewed-by: Ken Buchanan <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#544518} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: jbig2_table_read_bits(const byte *data, size_t *bitoffset, const int bitlen) { uint32_t result = 0; uint32_t byte_offset = *bitoffset / 8; const int endbit = (*bitoffset & 7) + bitlen; const int n_proc_bytes = (endbit + 7) / 8; const int rshift = n_proc_bytes * 8 - endbit; int i; for (i = n_proc_bytes - 1; i >= 0; i--) { uint32_t d = data[byte_offset++]; const int nshift = i * 8 - rshift; if (nshift > 0) d <<= nshift; else if (nshift < 0) d >>= -nshift; result |= d; } result &= ~(-1 << bitlen); *bitoffset += bitlen; return result; } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FocusFirstNameField() { LOG(WARNING) << "Clicking on the tab."; ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER)); ASSERT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER)); LOG(WARNING) << "Focusing the first name field."; bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( render_view_host(), L"", L"if (document.readyState === 'complete')" L" document.getElementById('firstname').focus();" L"else" L" domAutomationController.send(false);", &result)); ASSERT_TRUE(result); } Commit Message: Convert the autofill interactive browser test to a normal browser_test. I added testing methods to fake input events that don't depend on the OS and being at the front. BUG=121574 Review URL: https://chromiumcodereview.appspot.com/10368010 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@135432 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: array_indexed_param_read(iparam_list * plist, const ref * pkey, iparam_loc * ploc) { ref *const arr = &((dict_param_list *) plist)->dict; check_type(*pkey, t_integer); if (pkey->value.intval < 0 || pkey->value.intval >= r_size(arr)) return 1; ploc->pvalue = arr->value.refs + pkey->value.intval; ploc->presult = &plist->results[pkey->value.intval]; *ploc->presult = 1; return 0; } Commit Message: CWE ID: CWE-704 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void TabStripModel::AppendTabContents(TabContentsWrapper* contents, bool foreground) { int index = order_controller_->DetermineInsertionIndexForAppending(); InsertTabContentsAt(index, contents, foreground ? (ADD_INHERIT_GROUP | ADD_ACTIVE) : ADD_NONE); } Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab. BUG=chromium-os:12088 TEST=verify bug per bug report. Review URL: http://codereview.chromium.org/6882058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: gplotCreate(const char *rootname, l_int32 outformat, const char *title, const char *xlabel, const char *ylabel) { char *newroot; char buf[L_BUF_SIZE]; l_int32 badchar; GPLOT *gplot; PROCNAME("gplotCreate"); if (!rootname) return (GPLOT *)ERROR_PTR("rootname not defined", procName, NULL); if (outformat != GPLOT_PNG && outformat != GPLOT_PS && outformat != GPLOT_EPS && outformat != GPLOT_LATEX) return (GPLOT *)ERROR_PTR("outformat invalid", procName, NULL); stringCheckForChars(rootname, "`;&|><\"?*", &badchar); if (badchar) /* danger of command injection */ return (GPLOT *)ERROR_PTR("invalid rootname", procName, NULL); if ((gplot = (GPLOT *)LEPT_CALLOC(1, sizeof(GPLOT))) == NULL) return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL); gplot->cmddata = sarrayCreate(0); gplot->datanames = sarrayCreate(0); gplot->plotdata = sarrayCreate(0); gplot->plottitles = sarrayCreate(0); gplot->plotstyles = numaCreate(0); /* Save title, labels, rootname, outformat, cmdname, outname */ newroot = genPathname(rootname, NULL); gplot->rootname = newroot; gplot->outformat = outformat; snprintf(buf, L_BUF_SIZE, "%s.cmd", rootname); gplot->cmdname = stringNew(buf); if (outformat == GPLOT_PNG) snprintf(buf, L_BUF_SIZE, "%s.png", newroot); else if (outformat == GPLOT_PS) snprintf(buf, L_BUF_SIZE, "%s.ps", newroot); else if (outformat == GPLOT_EPS) snprintf(buf, L_BUF_SIZE, "%s.eps", newroot); else if (outformat == GPLOT_LATEX) snprintf(buf, L_BUF_SIZE, "%s.tex", newroot); gplot->outname = stringNew(buf); if (title) gplot->title = stringNew(title); if (xlabel) gplot->xlabel = stringNew(xlabel); if (ylabel) gplot->ylabel = stringNew(ylabel); return gplot; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119 Target: 1 Example 2: Code: bool set_pool(PgSocket *client, const char *dbname, const char *username) { PgDatabase *db; PgUser *user; /* find database */ db = find_database(dbname); if (!db) { db = register_auto_database(dbname); if (!db) { disconnect_client(client, true, "No such database: %s", dbname); return false; } else { slog_info(client, "registered new auto-database: db = %s", dbname ); } } /* find user */ if (cf_auth_type == AUTH_ANY) { /* ignore requested user */ user = NULL; if (db->forced_user == NULL) { slog_error(client, "auth_type=any requires forced user"); disconnect_client(client, true, "bouncer config error"); return false; } client->auth_user = db->forced_user; } else { /* the user clients wants to log in as */ user = find_user(username); if (!user) { disconnect_client(client, true, "No such user: %s", username); return false; } client->auth_user = user; } /* pool user may be forced */ if (db->forced_user) user = db->forced_user; client->pool = get_pool(db, user); if (!client->pool) { disconnect_client(client, true, "no memory for pool"); return false; } return check_fast_fail(client); } Commit Message: Check if auth_user is set. Fixes a crash if password packet appears before startup packet (#42). CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: kdc_process_s4u_x509_user(krb5_context context, krb5_kdc_req *request, krb5_pa_data *pa_data, krb5_keyblock *tgs_subkey, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user); if (code) return code; code = verify_s4u_x509_user_checksum(context, tgs_subkey ? tgs_subkey : tgs_session, &req_data, request->nonce, *s4u_x509_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_s4u_x509_user(context, *s4u_x509_user); *s4u_x509_user = NULL; return code; } if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 || (*s4u_x509_user)->user_id.subject_cert.length != 0) { *status = "INVALID_S4U2SELF_REQUEST"; krb5_free_pa_s4u_x509_user(context, *s4u_x509_user); *s4u_x509_user = NULL; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; } return 0; } Commit Message: Prevent KDC unset status assertion failures Assign status values if S4U2Self padata fails to decode, if an S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request uses an evidence ticket which does not match the canonicalized request server principal name. Reported by Samuel Cabrero. If a status value is not assigned during KDC processing, default to "UNKNOWN_REASON" rather than failing an assertion. This change will prevent future denial of service bugs due to similar mistakes, and will allow us to omit assigning status values for unlikely errors such as small memory allocation failures. CVE-2017-11368: In MIT krb5 1.7 and later, an authenticated attacker can cause an assertion failure in krb5kdc by sending an invalid S4U2Self or S4U2Proxy request. CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C ticket: 8599 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-617 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void rd_release_device_space(struct rd_dev *rd_dev) { u32 i, j, page_count = 0, sg_per_table; struct rd_dev_sg_table *sg_table; struct page *pg; struct scatterlist *sg; if (!rd_dev->sg_table_array || !rd_dev->sg_table_count) return; sg_table = rd_dev->sg_table_array; for (i = 0; i < rd_dev->sg_table_count; i++) { sg = sg_table[i].sg_table; sg_per_table = sg_table[i].rd_sg_count; for (j = 0; j < sg_per_table; j++) { pg = sg_page(&sg[j]); if (pg) { __free_page(pg); page_count++; } } kfree(sg); } pr_debug("CORE_RD[%u] - Released device space for Ramdisk" " Device ID: %u, pages %u in %u tables total bytes %lu\n", rd_dev->rd_host->rd_host_id, rd_dev->rd_dev_id, page_count, rd_dev->sg_table_count, (unsigned long)page_count * PAGE_SIZE); kfree(sg_table); rd_dev->sg_table_array = NULL; rd_dev->sg_table_count = 0; } Commit Message: target/rd: Refactor rd_build_device_space + rd_release_device_space This patch refactors rd_build_device_space() + rd_release_device_space() into rd_allocate_sgl_table() + rd_release_device_space() so that they may be used seperatly for setup + release of protection information scatterlists. Also add explicit memset of pages within rd_allocate_sgl_table() based upon passed 'init_payload' value. v2 changes: - Drop unused sg_table from rd_release_device_space (Wei) Cc: Martin K. Petersen <[email protected]> Cc: Christoph Hellwig <[email protected]> Cc: Hannes Reinecke <[email protected]> Cc: Sagi Grimberg <[email protected]> Cc: Or Gerlitz <[email protected]> Signed-off-by: Nicholas Bellinger <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: explicit PdfServiceTestClient(service_manager::test::ServiceTest* test) : service_manager::test::ServiceTestClient(test) { registry_.AddInterface<service_manager::mojom::ServiceFactory>( base::Bind(&PdfServiceTestClient::Create, base::Unretained(this))); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ASF_Support::ASF_Support ( ASF_LegacyManager* _legacyManager,XMP_ProgressTracker* _progressTracker ) :legacyManager(_legacyManager),progressTracker(_progressTracker), posFileSizeInfo(0) { } Commit Message: CWE ID: CWE-835 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BluetoothOptionsHandler::DeviceNotification( const DictionaryValue& device) { web_ui_->CallJavascriptFunction( "options.SystemOptions.addBluetoothDevice", device); } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static void gcm_enc_hash_done(struct aead_request *req, int err) { struct crypto_gcm_req_priv_ctx *pctx = crypto_gcm_reqctx(req); if (!err) gcm_enc_copy_hash(req, pctx); aead_request_complete(req, err); } Commit Message: crypto: include crypto- module prefix in template This adds the module loading prefix "crypto-" to the template lookup as well. For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly includes the "crypto-" prefix at every level, correctly rejecting "vfat": net-pf-38 algif-hash crypto-vfat(blowfish) crypto-vfat(blowfish)-all crypto-vfat Reported-by: Mathias Krause <[email protected]> Signed-off-by: Kees Cook <[email protected]> Acked-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void TransportTexture::OnTexturesCreated(std::vector<int> textures) { bool ret = decoder_->MakeCurrent(); if (!ret) { LOG(ERROR) << "Failed to switch context"; return; } output_textures_->clear(); for (size_t i = 0; i < textures.size(); ++i) { uint32 gl_texture = 0; ret = decoder_->GetServiceTextureId(textures[i], &gl_texture); DCHECK(ret) << "Cannot translate client texture ID to service ID"; output_textures_->push_back(gl_texture); texture_map_.insert(std::make_pair(gl_texture, textures[i])); } create_task_->Run(); create_task_.reset(); output_textures_ = NULL; } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WT_NoiseGenerator (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pOutputBuffer; EAS_I32 phaseInc; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 nInterpolatedSample; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); return; } pOutputBuffer = pWTIntFrame->pAudioBuffer; phaseInc = pWTIntFrame->frame.phaseIncrement; /* get last two samples generated */ /*lint -e{704} <avoid divide for performance>*/ tmp0 = (EAS_I32) (pWTVoice->phaseAccum) >> 18; /*lint -e{704} <avoid divide for performance>*/ tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18; /* generate a buffer of noise */ while (numSamples--) { nInterpolatedSample = MULT_AUDIO_COEF( tmp0, (PHASE_ONE - pWTVoice->phaseFrac)); nInterpolatedSample += MULT_AUDIO_COEF( tmp1, pWTVoice->phaseFrac); *pOutputBuffer++ = (EAS_PCM) nInterpolatedSample; /* update PRNG */ pWTVoice->phaseFrac += (EAS_U32) phaseInc; if (GET_PHASE_INT_PART(pWTVoice->phaseFrac)) { tmp0 = tmp1; pWTVoice->phaseAccum = pWTVoice->loopEnd; pWTVoice->loopEnd = (5 * pWTVoice->loopEnd + 1); tmp1 = (EAS_I32) (pWTVoice->loopEnd) >> 18; pWTVoice->phaseFrac = GET_PHASE_FRAC_PART(pWTVoice->phaseFrac); } } } Commit Message: Sonivox: add SafetyNet log. Bug: 26366256 Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0 CWE ID: CWE-119 Target: 1 Example 2: Code: juniper_monitor_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_monitor_header { uint8_t pkt_type; uint8_t padding; uint8_t iif[2]; uint8_t service_id[4]; }; const struct juniper_monitor_header *mh; l2info.pictype = DLT_JUNIPER_MONITOR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; mh = (const struct juniper_monitor_header *)p; ND_TCHECK(*mh); if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ", EXTRACT_32BITS(&mh->service_id), EXTRACT_16BITS(&mh->iif), mh->pkt_type)); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; } Commit Message: CVE-2017-13004/Juniper: Add a bounds check. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BluetoothChooserDesktop::~BluetoothChooserDesktop() { bluetooth_chooser_controller_->ResetEventHandler(); } Commit Message: Ensure device choosers are closed on navigation The requestDevice() IPCs can race with navigation. This change ensures that choosers are closed on navigation and adds browser tests to exercise this for Web Bluetooth and WebUSB. Bug: 723503 Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c Reviewed-on: https://chromium-review.googlesource.com/1099961 Commit-Queue: Reilly Grant <[email protected]> Reviewed-by: Michael Wasserman <[email protected]> Reviewed-by: Jeffrey Yasskin <[email protected]> Cr-Commit-Position: refs/heads/master@{#569900} CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, int width, int height, int bandpos) { int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y; int clnpass_cnt = 0; int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS; int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC; for (y = 0; y < height; y++) memset(t1->data[y], 0, width * sizeof(**t1->data)); /* If code-block contains no compressed data: nothing to do. */ if (!cblk->length) return 0; for (y = 0; y < height + 2; y++) memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags)); cblk->data[cblk->length] = 0xff; cblk->data[cblk->length+1] = 0xff; ff_mqc_initdec(&t1->mqc, cblk->data); while (passno--) { switch(pass_t) { case 0: decode_sigpass(t1, width, height, bpno + 1, bandpos, bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol); break; case 1: decode_refpass(t1, width, height, bpno + 1); if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; case 2: decode_clnpass(s, t1, width, height, bpno + 1, bandpos, codsty->cblk_style & JPEG2000_CBLK_SEGSYM, vert_causal_ctx_csty_symbol); clnpass_cnt = clnpass_cnt + 1; if (bpass_csty_symbol && clnpass_cnt >= 4) ff_mqc_initdec(&t1->mqc, cblk->data); break; } pass_t++; if (pass_t == 3) { bpno--; pass_t = 0; } } return 0; } Commit Message: jpeg2000: check log2_cblk dimensions Fixes out of array access Fixes Ticket2895 Found-by: Piotr Bandurski <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int read_node_page(struct page *page, int op_flags) { struct f2fs_sb_info *sbi = F2FS_P_SB(page); struct node_info ni; struct f2fs_io_info fio = { .sbi = sbi, .type = NODE, .op = REQ_OP_READ, .op_flags = op_flags, .page = page, .encrypted_page = NULL, }; if (PageUptodate(page)) return LOCKED_PAGE; get_node_info(sbi, page->index, &ni); if (unlikely(ni.blk_addr == NULL_ADDR)) { ClearPageUptodate(page); return -ENOENT; } fio.new_blkaddr = fio.old_blkaddr = ni.blk_addr; return f2fs_submit_page_bio(&fio); } Commit Message: f2fs: fix race condition in between free nid allocator/initializer In below concurrent case, allocated nid can be loaded into free nid cache and be allocated again. Thread A Thread B - f2fs_create - f2fs_new_inode - alloc_nid - __insert_nid_to_list(ALLOC_NID_LIST) - f2fs_balance_fs_bg - build_free_nids - __build_free_nids - scan_nat_page - add_free_nid - __lookup_nat_cache - f2fs_add_link - init_inode_metadata - new_inode_page - new_node_page - set_node_addr - alloc_nid_done - __remove_nid_from_list(ALLOC_NID_LIST) - __insert_nid_to_list(FREE_NID_LIST) This patch makes nat cache lookup and free nid list operation being atomical to avoid this race condition. Signed-off-by: Jaegeuk Kim <[email protected]> Signed-off-by: Chao Yu <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual InputMethodDescriptors* GetSupportedInputMethods() { if (!initialized_successfully_) { InputMethodDescriptors* result = new InputMethodDescriptors; result->push_back(input_method::GetFallbackInputMethodDescriptor()); return result; } return chromeos::GetSupportedInputMethodDescriptors(); } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int em_sysexit(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; int usermode; u16 cs_sel = 0, ss_sel = 0; /* inject #GP if in real mode or Virtual 8086 mode */ if (ctxt->mode == X86EMUL_MODE_REAL || ctxt->mode == X86EMUL_MODE_VM86) return emulate_gp(ctxt, 0); setup_syscalls_segments(ctxt, &cs, &ss); if ((ctxt->rex_prefix & 0x8) != 0x0) usermode = X86EMUL_MODE_PROT64; else usermode = X86EMUL_MODE_PROT32; cs.dpl = 3; ss.dpl = 3; ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data); switch (usermode) { case X86EMUL_MODE_PROT32: cs_sel = (u16)(msr_data + 16); if ((msr_data & 0xfffc) == 0x0) return emulate_gp(ctxt, 0); ss_sel = (u16)(msr_data + 24); break; case X86EMUL_MODE_PROT64: cs_sel = (u16)(msr_data + 32); if (msr_data == 0x0) return emulate_gp(ctxt, 0); ss_sel = cs_sel + 8; cs.d = 0; cs.l = 1; break; } cs_sel |= SELECTOR_RPL_MASK; ss_sel |= SELECTOR_RPL_MASK; ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ctxt->_eip = reg_read(ctxt, VCPU_REGS_RDX); *reg_write(ctxt, VCPU_REGS_RSP) = reg_read(ctxt, VCPU_REGS_RCX); return X86EMUL_CONTINUE; } Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches Before changing rip (during jmp, call, ret, etc.) the target should be asserted to be canonical one, as real CPUs do. During sysret, both target rsp and rip should be canonical. If any of these values is noncanonical, a #GP exception should occur. The exception to this rule are syscall and sysenter instructions in which the assigned rip is checked during the assignment to the relevant MSRs. This patch fixes the emulator to behave as real CPUs do for near branches. Far branches are handled by the next patch. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: bool DirectoryExists(const FilePath& path) { base::ThreadRestrictions::AssertIOAllowed(); stat_wrapper_t file_info; if (CallStat(path.value().c_str(), &file_info) == 0) return S_ISDIR(file_info.st_mode); return false; } Commit Message: Fix creating target paths in file_util_posix CopyDirectory. BUG=167840 Review URL: https://chromiumcodereview.appspot.com/11773018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176659 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-22 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void XMLObjAttrAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); TestObjectV8Internal::XMLObjAttrAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BufferQueueConsumer::dump(String8& result, const char* prefix) const { mCore->dump(result, prefix); } Commit Message: BQ: Add permission check to BufferQueueConsumer::dump Bug 27046057 Change-Id: Id7bd8cf95045b497943ea39dde49e877aa6f5c4e CWE ID: CWE-264 Target: 1 Example 2: Code: Resource* DocumentLoader::StartPreload(Resource::Type type, FetchParameters& params) { Resource* resource = nullptr; switch (type) { case Resource::kImage: if (frame_) frame_->MaybeAllowImagePlaceholder(params); resource = ImageResource::Fetch(params, Fetcher()); break; case Resource::kScript: resource = ScriptResource::Fetch(params, Fetcher()); break; case Resource::kCSSStyleSheet: resource = CSSStyleSheetResource::Fetch(params, Fetcher()); break; case Resource::kFont: resource = FontResource::Fetch(params, Fetcher()); break; case Resource::kMedia: resource = RawResource::FetchMedia(params, Fetcher()); break; case Resource::kTextTrack: resource = RawResource::FetchTextTrack(params, Fetcher()); break; case Resource::kImportResource: resource = RawResource::FetchImport(params, Fetcher()); break; case Resource::kRaw: resource = RawResource::Fetch(params, Fetcher()); break; default: NOTREACHED(); } return resource; } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: struct b43_dmaring *b43_setup_dmaring(struct b43_wldev *dev, int controller_index, int for_tx, enum b43_dmatype type) { struct b43_dmaring *ring; int i, err; dma_addr_t dma_test; ring = kzalloc(sizeof(*ring), GFP_KERNEL); if (!ring) goto out; ring->nr_slots = B43_RXRING_SLOTS; if (for_tx) ring->nr_slots = B43_TXRING_SLOTS; ring->meta = kcalloc(ring->nr_slots, sizeof(struct b43_dmadesc_meta), GFP_KERNEL); if (!ring->meta) goto err_kfree_ring; for (i = 0; i < ring->nr_slots; i++) ring->meta->skb = B43_DMA_PTR_POISON; ring->type = type; ring->dev = dev; ring->mmio_base = b43_dmacontroller_base(type, controller_index); ring->index = controller_index; if (type == B43_DMA_64BIT) ring->ops = &dma64_ops; else ring->ops = &dma32_ops; if (for_tx) { ring->tx = 1; ring->current_slot = -1; } else { if (ring->index == 0) { ring->rx_buffersize = B43_DMA0_RX_BUFFERSIZE; ring->frameoffset = B43_DMA0_RX_FRAMEOFFSET; } else B43_WARN_ON(1); } #ifdef CONFIG_B43_DEBUG ring->last_injected_overflow = jiffies; #endif if (for_tx) { /* Assumption: B43_TXRING_SLOTS can be divided by TX_SLOTS_PER_FRAME */ BUILD_BUG_ON(B43_TXRING_SLOTS % TX_SLOTS_PER_FRAME != 0); ring->txhdr_cache = kcalloc(ring->nr_slots / TX_SLOTS_PER_FRAME, b43_txhdr_size(dev), GFP_KERNEL); if (!ring->txhdr_cache) goto err_kfree_meta; /* test for ability to dma to txhdr_cache */ dma_test = dma_map_single(dev->dev->dma_dev, ring->txhdr_cache, b43_txhdr_size(dev), DMA_TO_DEVICE); if (b43_dma_mapping_error(ring, dma_test, b43_txhdr_size(dev), 1)) { /* ugh realloc */ kfree(ring->txhdr_cache); ring->txhdr_cache = kcalloc(ring->nr_slots / TX_SLOTS_PER_FRAME, b43_txhdr_size(dev), GFP_KERNEL | GFP_DMA); if (!ring->txhdr_cache) goto err_kfree_meta; dma_test = dma_map_single(dev->dev->dma_dev, ring->txhdr_cache, b43_txhdr_size(dev), DMA_TO_DEVICE); if (b43_dma_mapping_error(ring, dma_test, b43_txhdr_size(dev), 1)) { b43err(dev->wl, "TXHDR DMA allocation failed\n"); goto err_kfree_txhdr_cache; } } dma_unmap_single(dev->dev->dma_dev, dma_test, b43_txhdr_size(dev), DMA_TO_DEVICE); } err = alloc_ringmemory(ring); if (err) goto err_kfree_txhdr_cache; err = dmacontroller_setup(ring); if (err) goto err_free_ringmemory; out: return ring; err_free_ringmemory: free_ringmemory(ring); err_kfree_txhdr_cache: kfree(ring->txhdr_cache); err_kfree_meta: kfree(ring->meta); err_kfree_ring: kfree(ring); ring = NULL; goto out; } Commit Message: b43: allocate receive buffers big enough for max frame len + offset Otherwise, skb_put inside of dma_rx can fail... https://bugzilla.kernel.org/show_bug.cgi?id=32042 Signed-off-by: John W. Linville <[email protected]> Acked-by: Larry Finger <[email protected]> Cc: [email protected] CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void vlan_setup(struct net_device *dev) { ether_setup(dev); dev->priv_flags |= IFF_802_1Q_VLAN; dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; dev->tx_queue_len = 0; dev->netdev_ops = &vlan_netdev_ops; dev->destructor = free_netdev; dev->ethtool_ops = &vlan_ethtool_ops; memset(dev->broadcast, 0, ETH_ALEN); } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void RenderWidgetHostImpl::ForwardMouseEventWithLatencyInfo( const blink::WebMouseEvent& mouse_event, const ui::LatencyInfo& latency) { TRACE_EVENT2("input", "RenderWidgetHostImpl::ForwardMouseEvent", "x", mouse_event.PositionInWidget().x, "y", mouse_event.PositionInWidget().y); DCHECK_GE(mouse_event.GetType(), blink::WebInputEvent::kMouseTypeFirst); DCHECK_LE(mouse_event.GetType(), blink::WebInputEvent::kMouseTypeLast); for (size_t i = 0; i < mouse_event_callbacks_.size(); ++i) { if (mouse_event_callbacks_[i].Run(mouse_event)) return; } if (ShouldDropInputEvents()) return; if (touch_emulator_ && touch_emulator_->HandleMouseEvent(mouse_event)) return; MouseEventWithLatencyInfo mouse_with_latency(mouse_event, latency); DispatchInputEventWithLatencyInfo(mouse_event, &mouse_with_latency.latency); input_router_->SendMouseEvent(mouse_with_latency); } Commit Message: Force a flush of drawing to the widget when a dialog is shown. BUG=823353 TEST=as in bug Change-Id: I5da777068fc29c5638ef02d50e59d5d7b2729260 Reviewed-on: https://chromium-review.googlesource.com/971661 Reviewed-by: Ken Buchanan <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#544518} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void tcp_parse_options(const struct sk_buff *skb, struct tcp_options_received *opt_rx, const u8 **hvpp, int estab) { const unsigned char *ptr; const struct tcphdr *th = tcp_hdr(skb); int length = (th->doff * 4) - sizeof(struct tcphdr); ptr = (const unsigned char *)(th + 1); opt_rx->saw_tstamp = 0; while (length > 0) { int opcode = *ptr++; int opsize; switch (opcode) { case TCPOPT_EOL: return; case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */ length--; continue; default: opsize = *ptr++; if (opsize < 2) /* "silly options" */ return; if (opsize > length) return; /* don't parse partial options */ switch (opcode) { case TCPOPT_MSS: if (opsize == TCPOLEN_MSS && th->syn && !estab) { u16 in_mss = get_unaligned_be16(ptr); if (in_mss) { if (opt_rx->user_mss && opt_rx->user_mss < in_mss) in_mss = opt_rx->user_mss; opt_rx->mss_clamp = in_mss; } } break; case TCPOPT_WINDOW: if (opsize == TCPOLEN_WINDOW && th->syn && !estab && sysctl_tcp_window_scaling) { __u8 snd_wscale = *(__u8 *)ptr; opt_rx->wscale_ok = 1; if (snd_wscale > 14) { if (net_ratelimit()) printk(KERN_INFO "tcp_parse_options: Illegal window " "scaling value %d >14 received.\n", snd_wscale); snd_wscale = 14; } opt_rx->snd_wscale = snd_wscale; } break; case TCPOPT_TIMESTAMP: if ((opsize == TCPOLEN_TIMESTAMP) && ((estab && opt_rx->tstamp_ok) || (!estab && sysctl_tcp_timestamps))) { opt_rx->saw_tstamp = 1; opt_rx->rcv_tsval = get_unaligned_be32(ptr); opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4); } break; case TCPOPT_SACK_PERM: if (opsize == TCPOLEN_SACK_PERM && th->syn && !estab && sysctl_tcp_sack) { opt_rx->sack_ok = 1; tcp_sack_reset(opt_rx); } break; case TCPOPT_SACK: if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) && !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) && opt_rx->sack_ok) { TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th; } break; #ifdef CONFIG_TCP_MD5SIG case TCPOPT_MD5SIG: /* * The MD5 Hash has already been * checked (see tcp_v{4,6}_do_rcv()). */ break; #endif case TCPOPT_COOKIE: /* This option is variable length. */ switch (opsize) { case TCPOLEN_COOKIE_BASE: /* not yet implemented */ break; case TCPOLEN_COOKIE_PAIR: /* not yet implemented */ break; case TCPOLEN_COOKIE_MIN+0: case TCPOLEN_COOKIE_MIN+2: case TCPOLEN_COOKIE_MIN+4: case TCPOLEN_COOKIE_MIN+6: case TCPOLEN_COOKIE_MAX: /* 16-bit multiple */ opt_rx->cookie_plus = opsize; *hvpp = ptr; break; default: /* ignore option */ break; } break; } ptr += opsize-2; length -= opsize; } } } Commit Message: tcp: drop SYN+FIN messages Denys Fedoryshchenko reported that SYN+FIN attacks were bringing his linux machines to their limits. Dont call conn_request() if the TCP flags includes SYN flag Reported-by: Denys Fedoryshchenko <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags) { struct dentry *dir; struct fscrypt_info *ci; int dir_has_key, cached_with_key; if (flags & LOOKUP_RCU) return -ECHILD; dir = dget_parent(dentry); if (!d_inode(dir)->i_sb->s_cop->is_encrypted(d_inode(dir))) { dput(dir); return 0; } ci = d_inode(dir)->i_crypt_info; if (ci && ci->ci_keyring_key && (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED) | (1 << KEY_FLAG_DEAD)))) ci = NULL; /* this should eventually be an flag in d_flags */ spin_lock(&dentry->d_lock); cached_with_key = dentry->d_flags & DCACHE_ENCRYPTED_WITH_KEY; spin_unlock(&dentry->d_lock); dir_has_key = (ci != NULL); dput(dir); /* * If the dentry was cached without the key, and it is a * negative dentry, it might be a valid name. We can't check * if the key has since been made available due to locking * reasons, so we fail the validation so ext4_lookup() can do * this check. * * We also fail the validation if the dentry was created with * the key present, but we no longer have the key, or vice versa. */ if ((!cached_with_key && d_is_negative(dentry)) || (!cached_with_key && dir_has_key) || (cached_with_key && !dir_has_key)) return 0; return 1; } Commit Message: fscrypt: remove broken support for detecting keyring key revocation Filesystem encryption ostensibly supported revoking a keyring key that had been used to "unlock" encrypted files, causing those files to become "locked" again. This was, however, buggy for several reasons, the most severe of which was that when key revocation happened to be detected for an inode, its fscrypt_info was immediately freed, even while other threads could be using it for encryption or decryption concurrently. This could be exploited to crash the kernel or worse. This patch fixes the use-after-free by removing the code which detects the keyring key having been revoked, invalidated, or expired. Instead, an encrypted inode that is "unlocked" now simply remains unlocked until it is evicted from memory. Note that this is no worse than the case for block device-level encryption, e.g. dm-crypt, and it still remains possible for a privileged user to evict unused pages, inodes, and dentries by running 'sync; echo 3 > /proc/sys/vm/drop_caches', or by simply unmounting the filesystem. In fact, one of those actions was already needed anyway for key revocation to work even somewhat sanely. This change is not expected to break any applications. In the future I'd like to implement a real API for fscrypt key revocation that interacts sanely with ongoing filesystem operations --- waiting for existing operations to complete and blocking new operations, and invalidating and sanitizing key material and plaintext from the VFS caches. But this is a hard problem, and for now this bug must be fixed. This bug affected almost all versions of ext4, f2fs, and ubifs encryption, and it was potentially reachable in any kernel configured with encryption support (CONFIG_EXT4_ENCRYPTION=y, CONFIG_EXT4_FS_ENCRYPTION=y, CONFIG_F2FS_FS_ENCRYPTION=y, or CONFIG_UBIFS_FS_ENCRYPTION=y). Note that older kernels did not use the shared fs/crypto/ code, but due to the potential security implications of this bug, it may still be worthwhile to backport this fix to them. Fixes: b7236e21d55f ("ext4 crypto: reorganize how we store keys in the inode") Cc: [email protected] # v4.2+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> Acked-by: Michael Halcrow <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: static struct sctp_packet *sctp_ootb_pkt_new(struct net *net, const struct sctp_association *asoc, const struct sctp_chunk *chunk) { struct sctp_packet *packet; struct sctp_transport *transport; __u16 sport; __u16 dport; __u32 vtag; /* Get the source and destination port from the inbound packet. */ sport = ntohs(chunk->sctp_hdr->dest); dport = ntohs(chunk->sctp_hdr->source); /* The V-tag is going to be the same as the inbound packet if no * association exists, otherwise, use the peer's vtag. */ if (asoc) { /* Special case the INIT-ACK as there is no peer's vtag * yet. */ switch(chunk->chunk_hdr->type) { case SCTP_CID_INIT_ACK: { sctp_initack_chunk_t *initack; initack = (sctp_initack_chunk_t *)chunk->chunk_hdr; vtag = ntohl(initack->init_hdr.init_tag); break; } default: vtag = asoc->peer.i.init_tag; break; } } else { /* Special case the INIT and stale COOKIE_ECHO as there is no * vtag yet. */ switch(chunk->chunk_hdr->type) { case SCTP_CID_INIT: { sctp_init_chunk_t *init; init = (sctp_init_chunk_t *)chunk->chunk_hdr; vtag = ntohl(init->init_hdr.init_tag); break; } default: vtag = ntohl(chunk->sctp_hdr->vtag); break; } } /* Make a transport for the bucket, Eliza... */ transport = sctp_transport_new(net, sctp_source(chunk), GFP_ATOMIC); if (!transport) goto nomem; /* Cache a route for the transport with the chunk's destination as * the source address. */ sctp_transport_route(transport, (union sctp_addr *)&chunk->dest, sctp_sk(net->sctp.ctl_sock)); packet = sctp_packet_init(&transport->packet, transport, sport, dport); packet = sctp_packet_config(packet, vtag, 0); return packet; nomem: return NULL; } Commit Message: sctp: Use correct sideffect command in duplicate cookie handling When SCTP is done processing a duplicate cookie chunk, it tries to delete a newly created association. For that, it has to set the right association for the side-effect processing to work. However, when it uses the SCTP_CMD_NEW_ASOC command, that performs more work then really needed (like hashing the associationa and assigning it an id) and there is no point to do that only to delete the association as a next step. In fact, it also creates an impossible condition where an association may be found by the getsockopt() call, and that association is empty. This causes a crash in some sctp getsockopts. The solution is rather simple. We simply use SCTP_CMD_SET_ASOC command that doesn't have all the overhead and does exactly what we need. Reported-by: Karl Heiss <[email protected]> Tested-by: Karl Heiss <[email protected]> CC: Neil Horman <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Acked-by: Neil Horman <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virDomainGetID(virDomainPtr domain) { VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, (unsigned int)-1); return domain->id; } Commit Message: virDomainGetTime: Deny on RO connections We have a policy that if API may end up talking to a guest agent it should require RW connection. We don't obey the rule in virDomainGetTime(). Signed-off-by: Michal Privoznik <[email protected]> CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int CCITTFaxStream::lookChar() { int code1, code2, code3; int b1i, blackPixels, i, bits; GBool gotEOL; if (buf != EOF) { return buf; } if (outputBits == 0) { if (eof) { return EOF; } err = gFalse; if (nextLine2D) { for (i = 0; i < columns && codingLine[i] < columns; ++i) { refLine[i] = codingLine[i]; } refLine[i++] = columns; refLine[i] = columns; codingLine[0] = 0; a0i = 0; b1i = 0; while (codingLine[a0i] < columns && !err) { code1 = getTwoDimCode(); switch (code1) { case twoDimPass: if (likely(b1i + 1 < columns + 2)) { addPixels(refLine[b1i + 1], blackPixels); if (refLine[b1i + 1] < columns) { b1i += 2; } } break; case twoDimHoriz: code1 = code2 = 0; if (blackPixels) { do { code1 += code3 = getBlackCode(); } while (code3 >= 64); do { code2 += code3 = getWhiteCode(); } while (code3 >= 64); } else { do { code1 += code3 = getWhiteCode(); } while (code3 >= 64); do { code2 += code3 = getBlackCode(); } while (code3 >= 64); } addPixels(codingLine[a0i] + code1, blackPixels); if (codingLine[a0i] < columns) { addPixels(codingLine[a0i] + code2, blackPixels ^ 1); } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } break; case twoDimVertR3: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i] + 3, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertR2: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i] + 2, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertR1: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i] + 1, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVert0: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixels(refLine[b1i], blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { ++b1i; while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertL3: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixelsNeg(refLine[b1i] - 3, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { if (b1i > 0) { --b1i; } else { ++b1i; } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertL2: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixelsNeg(refLine[b1i] - 2, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { if (b1i > 0) { --b1i; } else { ++b1i; } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case twoDimVertL1: if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } addPixelsNeg(refLine[b1i] - 1, blackPixels); blackPixels ^= 1; if (codingLine[a0i] < columns) { if (b1i > 0) { --b1i; } else { ++b1i; } while (refLine[b1i] <= codingLine[a0i] && refLine[b1i] < columns) { b1i += 2; if (unlikely(b1i > columns + 1)) { error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); err = gTrue; break; } } } break; case EOF: addPixels(columns, 0); eof = gTrue; break; default: error(errSyntaxError, getPos(), "Bad 2D code {0:04x} in CCITTFax stream", code1); addPixels(columns, 0); err = gTrue; break; } } } else { codingLine[0] = 0; a0i = 0; blackPixels = 0; while (codingLine[a0i] < columns) { code1 = 0; if (blackPixels) { do { code1 += code3 = getBlackCode(); } while (code3 >= 64); } else { do { code1 += code3 = getWhiteCode(); } while (code3 >= 64); } addPixels(codingLine[a0i] + code1, blackPixels); blackPixels ^= 1; } } gotEOL = gFalse; if (!endOfBlock && row == rows - 1) { eof = gTrue; } else if (endOfLine || !byteAlign) { code1 = lookBits(12); if (endOfLine) { while (code1 != EOF && code1 != 0x001) { eatBits(1); code1 = lookBits(12); } } else { while (code1 == 0) { eatBits(1); code1 = lookBits(12); } } if (code1 == 0x001) { eatBits(12); gotEOL = gTrue; } } if (byteAlign && !gotEOL) { inputBits &= ~7; } if (lookBits(1) == EOF) { eof = gTrue; } if (!eof && encoding > 0) { nextLine2D = !lookBits(1); eatBits(1); } if (endOfBlock && !endOfLine && byteAlign) { code1 = lookBits(24); if (code1 == 0x001001) { eatBits(12); gotEOL = gTrue; } } if (endOfBlock && gotEOL) { code1 = lookBits(12); if (code1 == 0x001) { eatBits(12); if (encoding > 0) { lookBits(1); eatBits(1); } if (encoding >= 0) { for (i = 0; i < 4; ++i) { code1 = lookBits(12); if (code1 != 0x001) { error(errSyntaxError, getPos(), "Bad RTC code in CCITTFax stream"); } eatBits(12); if (encoding > 0) { lookBits(1); eatBits(1); } } } eof = gTrue; } } else if (err && endOfLine) { while (1) { code1 = lookBits(13); if (code1 == EOF) { eof = gTrue; return EOF; } if ((code1 >> 1) == 0x001) { break; } eatBits(1); } eatBits(12); if (encoding > 0) { eatBits(1); nextLine2D = !(code1 & 1); } } if (codingLine[0] > 0) { outputBits = codingLine[a0i = 0]; } else { outputBits = codingLine[a0i = 1]; } ++row; } if (outputBits >= 8) { buf = (a0i & 1) ? 0x00 : 0xff; outputBits -= 8; if (outputBits == 0 && codingLine[a0i] < columns) { ++a0i; outputBits = codingLine[a0i] - codingLine[a0i - 1]; } } else { bits = 8; buf = 0; do { if (outputBits > bits) { buf <<= bits; if (!(a0i & 1)) { buf |= 0xff >> (8 - bits); } outputBits -= bits; bits = 0; } else { buf <<= outputBits; if (!(a0i & 1)) { buf |= 0xff >> (8 - outputBits); } bits -= outputBits; outputBits = 0; if (codingLine[a0i] < columns) { ++a0i; if (unlikely(a0i > columns)) { error(errSyntaxError, getPos(), "Bad bits {0:04x} in CCITTFax stream", bits); err = gTrue; break; } outputBits = codingLine[a0i] - codingLine[a0i - 1]; } else if (bits > 0) { buf <<= bits; bits = 0; } } } while (bits); } if (black) { buf ^= 0xff; } return buf; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: bool asn1_check_OID(struct asn1_data *data, const char *OID) { char *id; if (!asn1_read_OID(data, data, &id)) return false; if (strcmp(id, OID) != 0) { talloc_free(id); data->has_error = true; return false; } talloc_free(id); return true; } Commit Message: CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: gs_dc_get_pattern_id(const gx_device_color *pdevc) { if (!(gx_dc_is_pattern1_color(pdevc))) return gs_no_id; if (pdevc->colors.pattern.p_tile == NULL) return gs_no_id; return pdevc->colors.pattern.p_tile->id; } Commit Message: CWE ID: CWE-704 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) { jas_image_t *image; bmp_hdr_t hdr; bmp_info_t *info; uint_fast16_t cmptno; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; uint_fast16_t numcmpts; long n; image = 0; info = 0; if (optstr) { jas_eprintf("warning: ignoring BMP decoder options\n"); } jas_eprintf( "THE BMP FORMAT IS NOT FULLY SUPPORTED!\n" "THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n" "IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n" "TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n" ); /* Read the bitmap header. */ if (bmp_gethdr(in, &hdr)) { jas_eprintf("cannot get header\n"); goto error; JAS_DBGLOG(1, ( "BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n", hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off )); /* Read the bitmap information. */ if (!(info = bmp_getinfo(in))) { jas_eprintf("cannot get info\n"); } JAS_DBGLOG(1, ("BMP information: len %ld; width %ld; height %ld; numplanes %d; " "depth %d; enctype %ld; siz %ld; hres %ld; vres %ld; numcolors %ld; " "mincolors %ld\n", JAS_CAST(long, info->len), JAS_CAST(long, info->width), JAS_CAST(long, info->height), JAS_CAST(long, info->numplanes), JAS_CAST(long, info->depth), JAS_CAST(long, info->enctype), JAS_CAST(long, info->siz), JAS_CAST(long, info->hres), JAS_CAST(long, info->vres), JAS_CAST(long, info->numcolors), JAS_CAST(long, info->mincolors))); if (info->width < 0 || info->height < 0 || info->numplanes < 0 || info->depth < 0 || info->siz < 0 || info->hres < 0 || info->vres < 0) { jas_eprintf("corrupt bit stream\n"); goto error; } /* Ensure that we support this type of BMP file. */ if (!bmp_issupported(&hdr, info)) { jas_eprintf("error: unsupported BMP encoding\n"); } /* Skip over any useless data between the end of the palette and start of the bitmap data. */ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { jas_eprintf("error: possibly bad bitmap offset?\n"); goto error; if (n > 0) { jas_eprintf("skipping unknown data in BMP file\n"); if (bmp_gobble(in, n)) { } } /* Get the number of components. */ numcmpts = bmp_numcmpts(info); for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = info->width; cmptparm->height = info->height; cmptparm->prec = 8; cmptparm->sgnd = false; } /* Create image object. */ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read the bitmap data. */ if (bmp_getdata(in, info, image)) { } bmp_info_destroy(info); return image; error: if (info) { bmp_info_destroy(info); } if (image) { jas_image_destroy(image); } return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Target: 1 Example 2: Code: GpuProcessHost* GpuProcessHost::Get(GpuProcessKind kind, CauseForGpuLaunch cause) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance(); DCHECK(gpu_data_manager); if (!gpu_data_manager->GpuAccessAllowed()) return NULL; if (g_gpu_process_hosts[kind] && HostIsValid(g_gpu_process_hosts[kind])) return g_gpu_process_hosts[kind]; if (cause == CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH) return NULL; int host_id; host_id = ++g_last_host_id; UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLaunchCause", cause, CAUSE_FOR_GPU_LAUNCH_MAX_ENUM); GpuProcessHost* host = new GpuProcessHost(host_id, kind); if (host->Init()) return host; delete host; return NULL; } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: decode_rd_as (u_char *pnt, struct rd_as *rd_as) { rd_as->as = (u_int16_t) *pnt++ << 8; rd_as->as |= (u_int16_t) *pnt++; rd_as->val = ((u_int32_t) *pnt++ << 24); rd_as->val |= ((u_int32_t) *pnt++ << 16); rd_as->val |= ((u_int32_t) *pnt++ << 8); rd_as->val |= (u_int32_t) *pnt; } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: perform_gamma_threshold_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Don't test more than one instance of each palette - it's pointless, in * fact this test is somewhat excessive since libpng doesn't make this * decision based on colour type or bit depth! */ while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) if (palette_number == 0) { double test_gamma = 1.0; while (test_gamma >= .4) { /* There's little point testing the interlacing vs non-interlacing, * but this can be set from the command line. */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, test_gamma, 1/test_gamma); test_gamma *= .95; } /* And a special test for sRGB */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, .45455, 2.2); if (fail(pm)) return; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: rm_trace_export(struct trace_export **list, struct trace_export *export) { struct trace_export **p; for (p = list; *p != NULL; p = &(*p)->next) if (*p == export) break; if (*p != export) return -1; rcu_assign_pointer(*p, (*p)->next); return 0; } Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: jbig2_find_changing_element(const byte *line, int x, int w) { int a, b; if (line == 0) return w; if (x == -1) { a = 0; x = 0; } else { } while (x < w) { b = getbit(line, x); if (a != b) break; x++; } return x; } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void gdImageFill(gdImagePtr im, int x, int y, int nc) { int l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; int alphablending_bak; /* stack of filled segments */ /* struct seg stack[FILL_MAX],*sp = stack;; */ struct seg *stack = NULL; struct seg *sp; if (!im->trueColor && nc > (im->colorsTotal -1)) { return; } alphablending_bak = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (nc==gdTiled){ _gdImageFillTiled(im,x,y,nc); im->alphaBlendingFlag = alphablending_bak; return; } wx2=im->sx;wy2=im->sy; oc = gdImageGetPixel(im, x, y); if (oc==nc || x<0 || x>wx2 || y<0 || y>wy2) { im->alphaBlendingFlag = alphablending_bak; return; } /* Do not use the 4 neighbors implementation with * small images */ if (im->sx < 4) { int ix = x, iy = y, c; do { do { c = gdImageGetPixel(im, ix, iy); if (c != oc) { goto done; } gdImageSetPixel(im, ix, iy, nc); } while(ix++ < (im->sx -1)); ix = x; } while(iy++ < (im->sy -1)); goto done; } stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1); sp = stack; /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && gdImageGetPixel(im,x, y)==oc; x--) { gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for (; x<=wx2 && gdImageGetPixel(im,x, y)==oc; x++) { gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for (x++; x<=x2 && (gdImageGetPixel(im, x, y)!=oc); x++); l = x; } while (x<=x2); } efree(stack); done: im->alphaBlendingFlag = alphablending_bak; } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190 Target: 1 Example 2: Code: xfs_attr3_leaf_order( struct xfs_buf *leaf1_bp, struct xfs_attr3_icleaf_hdr *leaf1hdr, struct xfs_buf *leaf2_bp, struct xfs_attr3_icleaf_hdr *leaf2hdr) { struct xfs_attr_leaf_entry *entries1; struct xfs_attr_leaf_entry *entries2; entries1 = xfs_attr3_leaf_entryp(leaf1_bp->b_addr); entries2 = xfs_attr3_leaf_entryp(leaf2_bp->b_addr); if (leaf1hdr->count > 0 && leaf2hdr->count > 0 && ((be32_to_cpu(entries2[0].hashval) < be32_to_cpu(entries1[0].hashval)) || (be32_to_cpu(entries2[leaf2hdr->count - 1].hashval) < be32_to_cpu(entries1[leaf1hdr->count - 1].hashval)))) { return 1; } return 0; } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebGraphicsContext3DCommandBufferImpl::FlipVertically( uint8* framebuffer, unsigned int width, unsigned int height) { uint8* scanline = scanline_.get(); if (!scanline) return; unsigned int row_bytes = width * 4; unsigned int count = height / 2; for (unsigned int i = 0; i < count; i++) { uint8* row_a = framebuffer + i * row_bytes; uint8* row_b = framebuffer + (height - i - 1) * row_bytes; memcpy(scanline, row_b, row_bytes); memcpy(row_b, row_a, row_bytes); memcpy(row_a, scanline, row_bytes); } } Commit Message: Fix mismanagement in handling of temporary scanline for vertical flip. BUG=116637 TEST=manual test from bug report with ASAN Review URL: https://chromiumcodereview.appspot.com/9617038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125301 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DataReductionProxyConfig::FetchWarmupProbeURL() { DCHECK(thread_checker_.CalledOnValidThread()); if (!enabled_by_user_) { RecordWarmupURLFetchAttemptEvent( WarmupURLFetchAttemptEvent::kProxyNotEnabledByUser); return; } if (!params::FetchWarmupProbeURLEnabled()) { RecordWarmupURLFetchAttemptEvent( WarmupURLFetchAttemptEvent::kWarmupURLFetchingDisabled); return; } if (connection_type_ == network::mojom::ConnectionType::CONNECTION_NONE) { RecordWarmupURLFetchAttemptEvent( WarmupURLFetchAttemptEvent::kConnectionTypeNone); return; } base::Optional<DataReductionProxyServer> warmup_proxy = GetProxyConnectionToProbe(); if (!warmup_proxy) return; warmup_url_fetch_in_flight_secure_proxy_ = warmup_proxy->IsSecureProxy(); warmup_url_fetch_in_flight_core_proxy_ = warmup_proxy->IsCoreProxy(); size_t previous_attempt_counts = GetWarmupURLFetchAttemptCounts(); network_properties_manager_->OnWarmupFetchInitiated( warmup_url_fetch_in_flight_secure_proxy_, warmup_url_fetch_in_flight_core_proxy_); RecordWarmupURLFetchAttemptEvent(WarmupURLFetchAttemptEvent::kFetchInitiated); warmup_url_fetcher_->FetchWarmupURL(previous_attempt_counts, warmup_proxy.value()); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416 Target: 1 Example 2: Code: void RenderFrameImpl::OnSetOverlayRoutingToken( const base::UnguessableToken& token) { overlay_routing_token_ = token; for (const auto& cb : pending_routing_token_callbacks_) cb.Run(overlay_routing_token_.value()); pending_routing_token_callbacks_.clear(); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char colorspace[MagickPathExtent], text[MagickPathExtent]; Image *image; long x_offset, y_offset; PixelInfo pixel; MagickBooleanType status; QuantumAny range; register ssize_t i, x; register Quantum *q; ssize_t count, type, y; unsigned long depth, height, max_value, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) ResetMagickMemory(text,0,sizeof(text)); (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { width=0; height=0; max_value=0; *colorspace='\0'; count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value, colorspace); if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=width; image->rows=height; for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ; image->depth=depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); LocaleLower(colorspace); i=(ssize_t) strlen(colorspace)-1; image->alpha_trait=UndefinedPixelTrait; if ((i > 0) && (colorspace[i] == 'a')) { colorspace[i]='\0'; image->alpha_trait=BlendPixelTrait; } type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace); if (type < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) SetImageBackgroundColor(image,exception); (void) SetImageColorspace(image,(ColorspaceType) type,exception); GetPixelInfo(image,&pixel); range=GetQuantumRange(image->depth); for (y=0; y < (ssize_t) image->rows; y++) { double alpha, black, blue, green, red; red=0.0; green=0.0; blue=0.0; black=0.0; alpha=0.0; for (x=0; x < (ssize_t) image->columns; x++) { if (ReadBlobString(image,text) == (char *) NULL) break; switch (image->colorspace) { case GRAYColorspace: { if (image->alpha_trait != UndefinedPixelTrait) { count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&alpha); green=red; blue=red; break; } count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset, &y_offset,&red); green=red; blue=red; break; } case CMYKColorspace: { if (image->alpha_trait != UndefinedPixelTrait) { count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&black,&alpha); break; } count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue,&black); break; } default: { if (image->alpha_trait != UndefinedPixelTrait) { count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&alpha); break; } count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue); break; } } if (strchr(text,'%') != (char *) NULL) { red*=0.01*range; green*=0.01*range; blue*=0.01*range; black*=0.01*range; alpha*=0.01*range; } if (image->colorspace == LabColorspace) { green+=(range+1)/2.0; blue+=(range+1)/2.0; } pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5), range); pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5), range); pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5), range); pixel.black=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (black+0.5), range); pixel.alpha=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (alpha+0.5), range); q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1, exception); if (q == (Quantum *) NULL) continue; SetPixelViaPixelInfo(image,&pixel,q); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/591 CWE ID: CWE-835 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static struct sock *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq; struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif struct flowi6 fl6; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (!newsk) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } ireq = inet_rsk(req); if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; ip6_dst_store(newsk, dst, NULL, NULL); inet6_sk_rx_dst_set(newsk, skb); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; tcp_ca_openreq_child(newsk, dst); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = tcp_mss_clamp(tcp_sk(sk), dst_metric_advmss(dst)); tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr); if (key) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr, AF_INET6, key->key, key->keylen, sk_gfp_mask(sk, GFP_ATOMIC)); } #endif if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); tcp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); if (*own_req) { tcp_move_syn(newtp, req); /* Clone pktoptions received with SYN, if we own the req */ if (ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, sk_gfp_mask(sk, GFP_ATOMIC)); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) { tcp_v6_restore_cb(newnp->pktoptions); skb_set_owner_r(newnp->pktoptions, newsk); } } } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: tcp_listendrop(sk); return NULL; } Commit Message: ipv6/dccp: do not inherit ipv6_mc_list from parent Like commit 657831ffc38e ("dccp/tcp: do not inherit mc_list from parent") we should clear ipv6_mc_list etc. for IPv6 sockets too. Cc: Eric Dumazet <[email protected]> Signed-off-by: Cong Wang <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 1 Example 2: Code: pdf_process_grestore(fz_context *ctx, pdf_processor *proc, pdf_csi *csi) { if (csi->gstate > 0) { if (proc->op_Q) proc->op_Q(ctx, proc); --csi->gstate; } } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ModuleExport size_t RegisterBMPImage(void) { MagickInfo *entry; entry=SetMagickInfo("BMP"); entry->decoder=(DecodeImageHandler *) ReadBMPImage; entry->encoder=(EncodeImageHandler *) WriteBMPImage; entry->magick=(IsImageFormatHandler *) IsBMP; entry->description=ConstantString("Microsoft Windows bitmap image"); entry->module=ConstantString("BMP"); entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("BMP2"); entry->encoder=(EncodeImageHandler *) WriteBMPImage; entry->magick=(IsImageFormatHandler *) IsBMP; entry->description=ConstantString("Microsoft Windows bitmap image (V2)"); entry->module=ConstantString("BMP"); entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); entry=SetMagickInfo("BMP3"); entry->encoder=(EncodeImageHandler *) WriteBMPImage; entry->magick=(IsImageFormatHandler *) IsBMP; entry->description=ConstantString("Microsoft Windows bitmap image (V3)"); entry->module=ConstantString("BMP"); entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long ContentEncoding::ParseCompressionEntry(long long start, long long size, IMkvReader* pReader, ContentCompression* compression) { assert(pReader); assert(compression); long long pos = start; const long long stop = start + size; bool valid = false; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x254) { long long algo = UnserializeUInt(pReader, pos, size); if (algo < 0) return E_FILE_FORMAT_INVALID; compression->algo = algo; valid = true; } else if (id == 0x255) { if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } compression->settings = buf; compression->settings_len = buflen; } pos += size; // consume payload assert(pos <= stop); } if (!valid) return E_FILE_FORMAT_INVALID; return 0; } 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 Target: 1 Example 2: Code: static int check_chain_extensions(X509_STORE_CTX *ctx) { int i, ok = 0, must_be_ca, plen = 0; X509 *x; int (*cb) (int xok, X509_STORE_CTX *xctx); int proxy_path_length = 0; int purpose; int allow_proxy_certs; cb = ctx->verify_cb; /*- * must_be_ca can have 1 of 3 values: * -1: we accept both CA and non-CA certificates, to allow direct * use of self-signed certificates (which are marked as CA). * 0: we only accept non-CA certificates. This is currently not * used, but the possibility is present for future extensions. * 1: we only accept CA certificates. This is currently used for * all certificates in the chain except the leaf certificate. */ must_be_ca = -1; /* CRL path validation */ if (ctx->parent) { allow_proxy_certs = 0; purpose = X509_PURPOSE_CRL_SIGN; } else { allow_proxy_certs = ! !(ctx->param->flags & X509_V_FLAG_ALLOW_PROXY_CERTS); /* * A hack to keep people who don't want to modify their software * happy */ if (getenv("OPENSSL_ALLOW_PROXY_CERTS")) allow_proxy_certs = 1; purpose = ctx->param->purpose; } /* Check all untrusted certificates */ for (i = 0; i < ctx->last_untrusted; i++) { int ret; x = sk_X509_value(ctx->chain, i); if (!(ctx->param->flags & X509_V_FLAG_IGNORE_CRITICAL) && (x->ex_flags & EXFLAG_CRITICAL)) { ctx->error = X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } if (!allow_proxy_certs && (x->ex_flags & EXFLAG_PROXY)) { ctx->error = X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } ret = X509_check_ca(x); switch (must_be_ca) { case -1: if ((ctx->param->flags & X509_V_FLAG_X509_STRICT) && (ret != 1) && (ret != 0)) { ret = 0; ctx->error = X509_V_ERR_INVALID_CA; } else ret = 1; break; case 0: if (ret != 0) { ret = 0; ctx->error = X509_V_ERR_INVALID_NON_CA; } else ret = 1; break; default: if ((ret == 0) || ((ctx->param->flags & X509_V_FLAG_X509_STRICT) && (ret != 1))) { ret = 0; ctx->error = X509_V_ERR_INVALID_CA; } else ret = 1; break; } if (ret == 0) { ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } if (ctx->param->purpose > 0) { ret = X509_check_purpose(x, purpose, must_be_ca > 0); if ((ret == 0) || ((ctx->param->flags & X509_V_FLAG_X509_STRICT) && (ret != 1))) { ctx->error = X509_V_ERR_INVALID_PURPOSE; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } } /* Check pathlen if not self issued */ if ((i > 1) && !(x->ex_flags & EXFLAG_SI) && (x->ex_pathlen != -1) && (plen > (x->ex_pathlen + proxy_path_length + 1))) { ctx->error = X509_V_ERR_PATH_LENGTH_EXCEEDED; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } /* Increment path length if not self issued */ if (!(x->ex_flags & EXFLAG_SI)) plen++; /* * If this certificate is a proxy certificate, the next certificate * must be another proxy certificate or a EE certificate. If not, * the next certificate must be a CA certificate. */ if (x->ex_flags & EXFLAG_PROXY) { if (x->ex_pcpathlen != -1 && i > x->ex_pcpathlen) { ctx->error = X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED; ctx->error_depth = i; ctx->current_cert = x; ok = cb(0, ctx); if (!ok) goto end; } proxy_path_length++; must_be_ca = 0; } else must_be_ca = 1; } ok = 1; end: return ok; } Commit Message: Fix length checks in X509_cmp_time to avoid out-of-bounds reads. Also tighten X509_cmp_time to reject more than three fractional seconds in the time; and to reject trailing garbage after the offset. CVE-2015-1789 Reviewed-by: Viktor Dukhovni <[email protected]> Reviewed-by: Richard Levitte <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void opl3_panning(int dev, int voice, int value) { devc->voc[voice].panning = value; } Commit Message: sound/oss/opl3: validate voice and channel indexes User-controllable indexes for voice and channel values may cause reading and writing beyond the bounds of their respective arrays, leading to potentially exploitable memory corruption. Validate these indexes. Signed-off-by: Dan Rosenberg <[email protected]> Cc: [email protected] Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: TreeCache::TreeCache() {} Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void UpdateContentLengthPrefsForDataReductionProxy( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, bool via_data_reduction_proxy, base::Time now, PrefService* prefs) { base::TimeDelta time_since_unix_epoch = now - base::Time::UnixEpoch(); const int kMinDaysSinceUnixEpoch = 365 * 2; // 2 years. const int kMaxDaysSinceUnixEpoch = 365 * 1000; // 1000 years. if (time_since_unix_epoch.InDays() < kMinDaysSinceUnixEpoch || time_since_unix_epoch.InDays() > kMaxDaysSinceUnixEpoch) { return; } int64 then_internal = prefs->GetInt64( prefs::kDailyHttpContentLengthLastUpdateDate); base::Time then_midnight = base::Time::FromInternalValue(then_internal).LocalMidnight(); base::Time midnight = now.LocalMidnight(); int days_since_last_update = (midnight - then_midnight).InDays(); DailyDataSavingUpdate total( prefs::kDailyHttpOriginalContentLength, prefs::kDailyHttpReceivedContentLength, prefs); total.UpdateForDataChange(days_since_last_update); DailyDataSavingUpdate proxy_enabled( prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled, prefs::kDailyContentLengthWithDataReductionProxyEnabled, prefs); proxy_enabled.UpdateForDataChange(days_since_last_update); DailyDataSavingUpdate via_proxy( prefs::kDailyOriginalContentLengthViaDataReductionProxy, prefs::kDailyContentLengthViaDataReductionProxy, prefs); via_proxy.UpdateForDataChange(days_since_last_update); total.Add(original_content_length, received_content_length); if (with_data_reduction_proxy_enabled) { proxy_enabled.Add(original_content_length, received_content_length); if (via_data_reduction_proxy) { via_proxy.Add(original_content_length, received_content_length); } } if (days_since_last_update) { prefs->SetInt64(prefs::kDailyHttpContentLengthLastUpdateDate, midnight.ToInternalValue()); if (days_since_last_update == 1) { RecordDailyContentLengthHistograms( total.GetOriginalListPrefValue(kNumDaysInHistory - 2), total.GetReceivedListPrefValue(kNumDaysInHistory - 2), proxy_enabled.GetOriginalListPrefValue(kNumDaysInHistory - 2), proxy_enabled.GetReceivedListPrefValue(kNumDaysInHistory - 2), via_proxy.GetOriginalListPrefValue(kNumDaysInHistory - 2), via_proxy.GetReceivedListPrefValue(kNumDaysInHistory - 2)); } } } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: FileReaderLoader::~FileReaderLoader() { terminate(); if (!m_urlForReading.isEmpty()) ThreadableBlobRegistry::unregisterBlobURL(m_urlForReading); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: static Long Current_Ratio( EXEC_OP ) { if ( CUR.metrics.ratio ) return CUR.metrics.ratio; if ( CUR.GS.projVector.y == 0 ) CUR.metrics.ratio = CUR.metrics.x_ratio; else if ( CUR.GS.projVector.x == 0 ) CUR.metrics.ratio = CUR.metrics.y_ratio; else { Long x, y; x = MulDiv_Round( CUR.GS.projVector.x, CUR.metrics.x_ratio, 0x4000 ); y = MulDiv_Round( CUR.GS.projVector.y, CUR.metrics.y_ratio, 0x4000 ); CUR.metrics.ratio = Norm( x, y ); } return CUR.metrics.ratio; } Commit Message: CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xsltCopyNamespaceList(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNsPtr cur) { xmlNsPtr ret = NULL, tmp; xmlNsPtr p = NULL,q; if (cur == NULL) return(NULL); if (cur->type != XML_NAMESPACE_DECL) return(NULL); /* * One can add namespaces only on element nodes */ if ((node != NULL) && (node->type != XML_ELEMENT_NODE)) node = NULL; while (cur != NULL) { if (cur->type != XML_NAMESPACE_DECL) break; /* * Avoid duplicating namespace declarations in the tree if * a matching declaration is in scope. */ if (node != NULL) { if ((node->ns != NULL) && (xmlStrEqual(node->ns->prefix, cur->prefix)) && (xmlStrEqual(node->ns->href, cur->href))) { cur = cur->next; continue; } tmp = xmlSearchNs(node->doc, node, cur->prefix); if ((tmp != NULL) && (xmlStrEqual(tmp->href, cur->href))) { cur = cur->next; continue; } } #ifdef XSLT_REFACTORED /* * Namespace exclusion and ns-aliasing is performed at * compilation-time in the refactored code. */ q = xmlNewNs(node, cur->href, cur->prefix); if (p == NULL) { ret = p = q; } else { p->next = q; p = q; } #else /* * TODO: Remove this if the refactored code gets enabled. */ if (!xmlStrEqual(cur->href, XSLT_NAMESPACE)) { const xmlChar *URI; /* TODO apply cascading */ URI = (const xmlChar *) xmlHashLookup(ctxt->style->nsAliases, cur->href); if (URI == UNDEFINED_DEFAULT_NS) continue; if (URI != NULL) { q = xmlNewNs(node, URI, cur->prefix); } else { q = xmlNewNs(node, cur->href, cur->prefix); } if (p == NULL) { ret = p = q; } else { p->next = q; p = q; } } #endif cur = cur->next; } return(ret); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(int argc, char *argv[]) { p_fm_config_conx_hdlt hdl; int instance = 0; fm_mgr_config_errno_t res; char *rem_addr = NULL; char *community = "public"; char Opts[256]; int arg; char *command; int i; /* Get options at the command line (overide default values) */ strcpy(Opts, "i:d:h-"); while ((arg = getopt(argc, argv, Opts)) != EOF) { switch (arg) { case 'h': case '-': usage(argv[0]); return(0); case 'i': instance = atol(optarg); break; case 'd': rem_addr = optarg; break; default: usage(argv[0]); return(-1); } } if(optind >= argc){ fprintf(stderr, "Command required\n"); usage(argv[0]); return -1; } command = argv[optind++]; printf("Connecting to %s FM instance %d\n", (rem_addr==NULL) ? "LOCAL":rem_addr, instance); if((res = fm_mgr_config_init(&hdl,instance, rem_addr, community)) != FM_CONF_OK) { fprintf(stderr, "Failed to initialize the client handle: %d\n", res); goto die_clean; } if((res = fm_mgr_config_connect(hdl)) != FM_CONF_OK) { fprintf(stderr, "Failed to connect: (%d) %s\n",res,fm_mgr_get_error_str(res)); goto die_clean; } for(i=0;i<commandListLen;i++){ if(strcmp(command,commandList[i].name) == 0){ return commandList[i].cmdPtr(hdl, commandList[i].mgr, (argc - optind), &argv[optind]); } } fprintf(stderr, "Command (%s) is not valid\n",command); usage(argv[0]); res = -1; die_clean: if (hdl) free(hdl); return res; } Commit Message: Fix scripts and code that use well-known tmp files. CWE ID: CWE-362 Target: 1 Example 2: Code: older_enctype(krb5_enctype enctype) { switch (enctype) { case ETYPE_DES_CBC_CRC: case ETYPE_DES_CBC_MD4: case ETYPE_DES_CBC_MD5: case ETYPE_DES3_CBC_SHA1: case ETYPE_ARCFOUR_HMAC_MD5: case ETYPE_ARCFOUR_HMAC_MD5_56: /* * The following three is "old" windows enctypes and is needed for * windows 2000 hosts. */ case ETYPE_ARCFOUR_MD4: case ETYPE_ARCFOUR_HMAC_OLD: case ETYPE_ARCFOUR_HMAC_OLD_EXP: return 1; default: return 0; } } Commit Message: Security: Avoid NULL structure pointer member dereference This can happen in the error path when processing malformed AS requests with a NULL client name. Bug originally introduced on Fri Feb 13 09:26:01 2015 +0100 in commit: a873e21d7c06f22943a90a41dc733ae76799390d kdc: base _kdc_fast_mk_error() on krb5_mk_error_ext() Original patch by Jeffrey Altman <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long long AudioTrack::GetBitDepth() const { return m_bitDepth; } 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ShellWindow::ShellWindow(Profile* profile, const extensions::Extension* extension, const GURL& url) : profile_(profile), extension_(extension), ALLOW_THIS_IN_INITIALIZER_LIST( extension_function_dispatcher_(profile, this)) { web_contents_ = WebContents::Create( profile, SiteInstance::CreateForURL(profile, url), MSG_ROUTING_NONE, NULL, NULL); contents_.reset(new TabContents(web_contents_)); content::WebContentsObserver::Observe(web_contents_); web_contents_->SetDelegate(this); chrome::SetViewType(web_contents_, chrome::VIEW_TYPE_APP_SHELL); web_contents_->GetMutableRendererPrefs()-> browser_handles_all_top_level_requests = true; web_contents_->GetRenderViewHost()->SyncRendererPrefs(); web_contents_->GetController().LoadURL( url, content::Referrer(), content::PAGE_TRANSITION_LINK, std::string()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, content::Source<Profile>(profile_)); registrar_.Add(this, content::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); TabContents* tab_contents = TabContents::FromWebContents(web_contents_); InfoBarTabHelper* infobar_helper = tab_contents->infobar_tab_helper(); infobar_helper->set_infobars_enabled(false); browser::StartKeepAlive(); } Commit Message: Make chrome.appWindow.create() provide access to the child window at a predictable time. When you first create a window with chrome.appWindow.create(), it won't have loaded any resources. So, at create time, you are guaranteed that: child_window.location.href == 'about:blank' child_window.document.documentElement.outerHTML == '<html><head></head><body></body></html>' This is in line with the behaviour of window.open(). BUG=131735 TEST=browser_tests:PlatformAppBrowserTest.WindowsApi Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=144072 Review URL: https://chromiumcodereview.appspot.com/10644006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@144356 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: pdf_set_pattern(fz_context *ctx, pdf_run_processor *pr, int what, pdf_pattern *pat, float *v) { pdf_gstate *gs; pdf_material *mat; gs = pdf_flush_text(ctx, pr); mat = what == PDF_FILL ? &gs->fill : &gs->stroke; pdf_drop_pattern(ctx, mat->pattern); mat->pattern = NULL; mat->kind = PDF_MAT_PATTERN; if (pat) mat->pattern = pdf_keep_pattern(ctx, pat); if (v) pdf_set_color(ctx, pr, what, v); mat->gstate_num = pr->gparent; } Commit Message: CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: zrestore(i_ctx_t *i_ctx_p) { os_ptr op = osp; alloc_save_t *asave; bool last; vm_save_t *vmsave; int code = restore_check_operand(op, &asave, idmemory); if (code < 0) return code; if_debug2m('u', imemory, "[u]vmrestore 0x%lx, id = %lu\n", (ulong) alloc_save_client_data(asave), (ulong) op->value.saveid); if (I_VALIDATE_BEFORE_RESTORE) ivalidate_clean_spaces(i_ctx_p); ivalidate_clean_spaces(i_ctx_p); /* Check the contents of the stacks. */ { int code; if ((code = restore_check_stack(i_ctx_p, &o_stack, asave, false)) < 0 || (code = restore_check_stack(i_ctx_p, &e_stack, asave, true)) < 0 || (code = restore_check_stack(i_ctx_p, &d_stack, asave, false)) < 0 ) { osp++; return code; } } /* Reset l_new in all stack entries if the new save level is zero. */ /* Also do some special fixing on the e-stack. */ restore_fix_stack(i_ctx_p, &o_stack, asave, false); } Commit Message: CWE ID: CWE-78 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: MagickExport void RemoveDuplicateLayers(Image **images, ExceptionInfo *exception) { register Image *curr, *next; RectangleInfo bounds; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); curr=GetFirstImageInList(*images); for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next) { if ( curr->columns != next->columns || curr->rows != next->rows || curr->page.x != next->page.x || curr->page.y != next->page.y ) continue; bounds=CompareImagesBounds(curr,next,CompareAnyLayer,exception); if ( bounds.x < 0 ) { /* the two images are the same, merge time delays and delete one. */ size_t time; time = curr->delay*1000/curr->ticks_per_second; time += next->delay*1000/next->ticks_per_second; next->ticks_per_second = 100L; next->delay = time*curr->ticks_per_second/1000; next->iterations = curr->iterations; *images = curr; (void) DeleteImageFromList(images); } } *images = GetFirstImageInList(*images); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1629 CWE ID: CWE-369 Target: 1 Example 2: Code: void __blk_run_queue(struct request_queue *q) { lockdep_assert_held(q->queue_lock); WARN_ON_ONCE(q->mq_ops); if (unlikely(blk_queue_stopped(q))) return; __blk_run_queue_uncond(q); } Commit Message: block: blk_init_allocated_queue() set q->fq as NULL in the fail case We find the memory use-after-free issue in __blk_drain_queue() on the kernel 4.14. After read the latest kernel 4.18-rc6 we think it has the same problem. Memory is allocated for q->fq in the blk_init_allocated_queue(). If the elevator init function called with error return, it will run into the fail case to free the q->fq. Then the __blk_drain_queue() uses the same memory after the free of the q->fq, it will lead to the unpredictable event. The patch is to set q->fq as NULL in the fail case of blk_init_allocated_queue(). Fixes: commit 7c94e1c157a2 ("block: introduce blk_flush_queue to drive flush machinery") Cc: <[email protected]> Reviewed-by: Ming Lei <[email protected]> Reviewed-by: Bart Van Assche <[email protected]> Signed-off-by: xiao jin <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md) { X509_REQ *ret; X509_REQ_INFO *ri; int i; EVP_PKEY *pktmp; ret = X509_REQ_new(); if (ret == NULL) { X509err(X509_F_X509_TO_X509_REQ, ERR_R_MALLOC_FAILURE); goto err; } ri = ret->req_info; ri->version->length = 1; ri->version->data = (unsigned char *)OPENSSL_malloc(1); if (ri->version->data == NULL) goto err; ri->version->data[0] = 0; /* version == 0 */ if (!X509_REQ_set_subject_name(ret, X509_get_subject_name(x))) goto err; pktmp = X509_get_pubkey(x); i = X509_REQ_set_pubkey(ret, pktmp); EVP_PKEY_free(pktmp); if (!i) if (pkey != NULL) { if (!X509_REQ_sign(ret, pkey, md)) goto err; } return (ret); err: X509_REQ_free(ret); return (NULL); } Commit Message: CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PlatformSensorProviderLinux::CreateSensorAndNotify( mojom::SensorType type, SensorInfoLinux* sensor_device) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); scoped_refptr<PlatformSensorLinux> sensor; mojo::ScopedSharedBufferMapping mapping = MapSharedBufferForType(type); if (sensor_device && mapping && StartPollingThread()) { sensor = new PlatformSensorLinux(type, std::move(mapping), this, sensor_device, polling_thread_->task_runner()); } NotifySensorCreated(type, sensor); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 Target: 1 Example 2: Code: static void update_event_times(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; u64 run_end; if (event->state < PERF_EVENT_STATE_INACTIVE || event->group_leader->state < PERF_EVENT_STATE_INACTIVE) return; /* * in cgroup mode, time_enabled represents * the time the event was enabled AND active * tasks were in the monitored cgroup. This is * independent of the activity of the context as * there may be a mix of cgroup and non-cgroup events. * * That is why we treat cgroup events differently * here. */ if (is_cgroup_event(event)) run_end = perf_cgroup_event_time(event); else if (ctx->is_active) run_end = ctx->time; else run_end = event->tstamp_stopped; event->total_time_enabled = run_end - event->tstamp_enabled; if (event->state == PERF_EVENT_STATE_INACTIVE) run_end = event->tstamp_stopped; else run_end = perf_event_time(event); event->total_time_running = run_end - event->tstamp_running; } Commit Message: perf: Treat attr.config as u64 in perf_swevent_init() Trinity discovered that we fail to check all 64 bits of attr.config passed by user space, resulting to out-of-bounds access of the perf_swevent_enabled array in sw_perf_event_destroy(). Introduced in commit b0a873ebb ("perf: Register PMU implementations"). Signed-off-by: Tommi Rantala <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: [email protected] Cc: Paul Mackerras <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int tcp_read_sock(struct sock *sk, read_descriptor_t *desc, sk_read_actor_t recv_actor) { struct sk_buff *skb; struct tcp_sock *tp = tcp_sk(sk); u32 seq = tp->copied_seq; u32 offset; int copied = 0; if (sk->sk_state == TCP_LISTEN) return -ENOTCONN; while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) { if (offset < skb->len) { int used; size_t len; len = skb->len - offset; /* Stop reading if we hit a patch of urgent data */ if (tp->urg_data) { u32 urg_offset = tp->urg_seq - seq; if (urg_offset < len) len = urg_offset; if (!len) break; } used = recv_actor(desc, skb, offset, len); if (used < 0) { if (!copied) copied = used; break; } else if (used <= len) { seq += used; copied += used; offset += used; } /* * If recv_actor drops the lock (e.g. TCP splice * receive) the skb pointer might be invalid when * getting here: tcp_collapse might have deleted it * while aggregating skbs from the socket queue. */ skb = tcp_recv_skb(sk, seq-1, &offset); if (!skb || (offset+1 != skb->len)) break; } if (tcp_hdr(skb)->fin) { sk_eat_skb(sk, skb, 0); ++seq; break; } sk_eat_skb(sk, skb, 0); if (!desc->count) break; } tp->copied_seq = seq; tcp_rcv_space_adjust(sk); /* Clean up data we have read: This will do ACK frames. */ if (copied > 0) tcp_cleanup_rbuf(sk, copied); return copied; } Commit Message: net: Fix oops from tcp_collapse() when using splice() tcp_read_sock() can have a eat skbs without immediately advancing copied_seq. This can cause a panic in tcp_collapse() if it is called as a result of the recv_actor dropping the socket lock. A userspace program that splices data from a socket to either another socket or to a file can trigger this bug. Signed-off-by: Steven J. Magnani <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ExprResolveBoolean(struct xkb_context *ctx, const ExprDef *expr, bool *set_rtrn) { bool ok = false; const char *ident; switch (expr->expr.op) { case EXPR_VALUE: if (expr->expr.value_type != EXPR_TYPE_BOOLEAN) { log_err(ctx, "Found constant of type %s where boolean was expected\n", expr_value_type_to_string(expr->expr.value_type)); return false; } *set_rtrn = expr->boolean.set; return true; case EXPR_IDENT: ident = xkb_atom_text(ctx, expr->ident.ident); if (ident) { if (istreq(ident, "true") || istreq(ident, "yes") || istreq(ident, "on")) { *set_rtrn = true; return true; } else if (istreq(ident, "false") || istreq(ident, "no") || istreq(ident, "off")) { *set_rtrn = false; return true; } } log_err(ctx, "Identifier \"%s\" of type boolean is unknown\n", ident); return false; case EXPR_FIELD_REF: log_err(ctx, "Default \"%s.%s\" of type boolean is unknown\n", xkb_atom_text(ctx, expr->field_ref.element), xkb_atom_text(ctx, expr->field_ref.field)); return false; case EXPR_INVERT: case EXPR_NOT: ok = ExprResolveBoolean(ctx, expr, set_rtrn); if (ok) *set_rtrn = !*set_rtrn; return ok; case EXPR_ADD: case EXPR_SUBTRACT: case EXPR_MULTIPLY: case EXPR_DIVIDE: case EXPR_ASSIGN: case EXPR_NEGATE: case EXPR_UNARY_PLUS: log_err(ctx, "%s of boolean values not permitted\n", expr_op_type_to_string(expr->expr.op)); break; default: log_wsgo(ctx, "Unknown operator %d in ResolveBoolean\n", expr->expr.op); break; } return false; } Commit Message: xkbcomp: fix stack overflow when evaluating boolean negation The expression evaluator would go into an infinite recursion when evaluating something like this as a boolean: `!True`. Instead of recursing to just `True` and negating, it recursed to `!True` itself again. Bug inherited from xkbcomp. Caught with the afl fuzzer. Signed-off-by: Ran Benita <[email protected]> CWE ID: CWE-400 Target: 1 Example 2: Code: static gboolean visibility_notify_event(GtkWidget *text_view, GdkEventVisibility *event) { gint wx, wy, bx, by; GdkWindow *win = gtk_text_view_get_window(GTK_TEXT_VIEW(text_view), GTK_TEXT_WINDOW_TEXT); GdkDeviceManager *device_manager = gdk_display_get_device_manager(gdk_window_get_display (win)); GdkDevice *pointer = gdk_device_manager_get_client_pointer(device_manager); gdk_window_get_device_position(gtk_widget_get_window(text_view), pointer, &wx, &wy, NULL); gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(text_view), GTK_TEXT_WINDOW_WIDGET, wx, wy, &bx, &by); set_cursor_if_appropriate(GTK_TEXT_VIEW (text_view), bx, by); return FALSE; } Commit Message: wizard: fix save users changes after reviewing dump dir files If the user reviewed the dump dir's files during reporting the crash, the changes was thrown away and original data was passed to the bugzilla bug report. report-gtk saves the first text view buffer and then reloads data from the reported problem directory, which causes that the changes made to those text views are thrown away. Function save_text_if_changed(), except of saving text, also reload the files from dump dir and update gui state from the dump dir. The commit moves the reloading and updating gui functions away from this function. Related to rhbz#1270235 Signed-off-by: Matej Habrnal <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void LockScreenMediaControlsView::MediaSessionInfoChanged( media_session::mojom::MediaSessionInfoPtr session_info) { if (hide_controls_timer_->IsRunning()) return; if (!media_controls_enabled_.Run() || !session_info) { hide_media_controls_.Run(); } else if (!IsDrawn() && session_info->playback_state == media_session::mojom::MediaPlaybackState::kPaused) { hide_media_controls_.Run(); } else if (!IsDrawn()) { show_media_controls_.Run(); } if (IsDrawn()) { SetIsPlaying(session_info && session_info->playback_state == media_session::mojom::MediaPlaybackState::kPlaying); } } Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks This CL rearranges the different components of the CrOS lock screen media controls based on the newest mocks. This involves resizing most of the child views and their spacings. The artwork was also resized and re-positioned. Additionally, the close button was moved from the main view to the header row child view. Artist and title data about the current session will eventually be placed to the right of the artwork, but right now this space is empty. See the bug for before and after pictures. Bug: 991647 Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554 Reviewed-by: Xiyuan Xia <[email protected]> Reviewed-by: Becca Hughes <[email protected]> Commit-Queue: Mia Bergeron <[email protected]> Cr-Commit-Position: refs/heads/master@{#686253} CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr) { uint32 i; float xres = 0.0, yres = 0.0; uint16 nstrips = 0, ntiles = 0, planar = 0; uint16 bps = 0, spp = 0, res_unit = 0; uint16 orientation = 0; uint16 input_compression = 0, input_photometric = 0; uint16 subsampling_horiz, subsampling_vert; uint32 width = 0, length = 0; uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0; uint32 tw = 0, tl = 0; /* Tile width and length */ uint32 tile_rowsize = 0; unsigned char *read_buff = NULL; unsigned char *new_buff = NULL; int readunit = 0; static uint32 prev_readsize = 0; TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) TIFFError("loadImage","Image lacks Photometric interpreation tag"); if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width)) TIFFError("loadimage","Image lacks image width tag"); if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length)) TIFFError("loadimage","Image lacks image length tag"); TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres); TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres); if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit)) res_unit = RESUNIT_INCH; if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression)) input_compression = COMPRESSION_NONE; #ifdef DEBUG2 char compressionid[16]; switch (input_compression) { case COMPRESSION_NONE: /* 1 dump mode */ strcpy (compressionid, "None/dump"); break; case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */ strcpy (compressionid, "Huffman RLE"); break; case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */ strcpy (compressionid, "Group3 Fax"); break; case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */ strcpy (compressionid, "Group4 Fax"); break; case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */ strcpy (compressionid, "LZW"); break; case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */ strcpy (compressionid, "Old Jpeg"); break; case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */ strcpy (compressionid, "New Jpeg"); break; case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */ strcpy (compressionid, "Next RLE"); break; case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */ strcpy (compressionid, "CITTRLEW"); break; case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */ strcpy (compressionid, "Mac Packbits"); break; case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */ strcpy (compressionid, "Thunderscan"); break; case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */ strcpy (compressionid, "IT8 padded"); break; case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */ strcpy (compressionid, "IT8 RLE"); break; case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */ strcpy (compressionid, "IT8 mono"); break; case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */ strcpy (compressionid, "IT8 lineart"); break; case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */ strcpy (compressionid, "Pixar 10 bit"); break; case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */ strcpy (compressionid, "Pixar 11bit"); break; case COMPRESSION_DEFLATE: /* 32946 Deflate compression */ strcpy (compressionid, "Deflate"); break; case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */ strcpy (compressionid, "Adobe deflate"); break; default: strcpy (compressionid, "None/unknown"); break; } TIFFError("loadImage", "Input compression %s", compressionid); #endif scanlinesize = TIFFScanlineSize(in); image->bps = bps; image->spp = spp; image->planar = planar; image->width = width; image->length = length; image->xres = xres; image->yres = yres; image->res_unit = res_unit; image->compression = input_compression; image->photometric = input_photometric; #ifdef DEBUG2 char photometricid[12]; switch (input_photometric) { case PHOTOMETRIC_MINISWHITE: strcpy (photometricid, "MinIsWhite"); break; case PHOTOMETRIC_MINISBLACK: strcpy (photometricid, "MinIsBlack"); break; case PHOTOMETRIC_RGB: strcpy (photometricid, "RGB"); break; case PHOTOMETRIC_PALETTE: strcpy (photometricid, "Palette"); break; case PHOTOMETRIC_MASK: strcpy (photometricid, "Mask"); break; case PHOTOMETRIC_SEPARATED: strcpy (photometricid, "Separated"); break; case PHOTOMETRIC_YCBCR: strcpy (photometricid, "YCBCR"); break; case PHOTOMETRIC_CIELAB: strcpy (photometricid, "CIELab"); break; case PHOTOMETRIC_ICCLAB: strcpy (photometricid, "ICCLab"); break; case PHOTOMETRIC_ITULAB: strcpy (photometricid, "ITULab"); break; case PHOTOMETRIC_LOGL: strcpy (photometricid, "LogL"); break; case PHOTOMETRIC_LOGLUV: strcpy (photometricid, "LOGLuv"); break; default: strcpy (photometricid, "Unknown"); break; } TIFFError("loadImage", "Input photometric interpretation %s", photometricid); #endif image->orientation = orientation; switch (orientation) { case 0: case ORIENTATION_TOPLEFT: image->adjustments = 0; break; case ORIENTATION_TOPRIGHT: image->adjustments = MIRROR_HORIZ; break; case ORIENTATION_BOTRIGHT: image->adjustments = ROTATECW_180; break; case ORIENTATION_BOTLEFT: image->adjustments = MIRROR_VERT; break; case ORIENTATION_LEFTTOP: image->adjustments = MIRROR_VERT | ROTATECW_90; break; case ORIENTATION_RIGHTTOP: image->adjustments = ROTATECW_90; break; case ORIENTATION_RIGHTBOT: image->adjustments = MIRROR_VERT | ROTATECW_270; break; case ORIENTATION_LEFTBOT: image->adjustments = ROTATECW_270; break; default: image->adjustments = 0; image->orientation = ORIENTATION_TOPLEFT; } if ((bps == 0) || (spp == 0)) { TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)", spp, bps); return (-1); } if (TIFFIsTiled(in)) { readunit = TILE; tlsize = TIFFTileSize(in); ntiles = TIFFNumberOfTiles(in); TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); tile_rowsize = TIFFTileRowSize(in); if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0) { TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero."); exit(-1); } buffsize = tlsize * ntiles; if (tlsize != (buffsize / ntiles)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } if (buffsize < (uint32)(ntiles * tl * tile_rowsize)) { buffsize = ntiles * tl * tile_rowsize; if (ntiles != (buffsize / tl / tile_rowsize)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } #ifdef DEBUG2 TIFFError("loadImage", "Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu", tlsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Tilesize: %u, Number of Tiles: %u, Tile row size: %u", tlsize, ntiles, tile_rowsize); } else { uint32 buffsize_check; readunit = STRIP; TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); stsize = TIFFStripSize(in); nstrips = TIFFNumberOfStrips(in); if (nstrips == 0 || stsize == 0) { TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero."); exit(-1); } buffsize = stsize * nstrips; if (stsize != (buffsize / nstrips)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } buffsize_check = ((length * width * spp * bps) + 7); if (length != ((buffsize_check - 7) / width / spp / bps)) { TIFFError("loadImage", "Integer overflow detected."); exit(-1); } if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8)) { buffsize = ((length * width * spp * bps) + 7) / 8; #ifdef DEBUG2 TIFFError("loadImage", "Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu", stsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u", stsize, nstrips, rowsperstrip, scanlinesize); } if (input_compression == COMPRESSION_JPEG) { /* Force conversion to RGB */ jpegcolormode = JPEGCOLORMODE_RGB; TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } /* The clause up to the read statement is taken from Tom Lane's tiffcp patch */ else { /* Otherwise, can't handle subsampled input */ if (input_photometric == PHOTOMETRIC_YCBCR) { TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsampling_horiz, &subsampling_vert); if (subsampling_horiz != 1 || subsampling_vert != 1) { TIFFError("loadImage", "Can't copy/convert subsampled image with subsampling %d horiz %d vert", subsampling_horiz, subsampling_vert); return (-1); } } } read_buff = *read_ptr; /* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */ /* outside buffer */ if (!read_buff) read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); else { if (prev_readsize < buffsize) { new_buff = _TIFFrealloc(read_buff, buffsize+3); if (!new_buff) { free (read_buff); read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); } else read_buff = new_buff; } } if (!read_buff) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } read_buff[buffsize] = 0; read_buff[buffsize+1] = 0; read_buff[buffsize+2] = 0; prev_readsize = buffsize; *read_ptr = read_buff; /* N.B. The read functions used copy separate plane data into a buffer as interleaved * samples rather than separate planes so the same logic works to extract regions * regardless of the way the data are organized in the input file. */ switch (readunit) { case STRIP: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigStripsIntoBuffer(in, read_buff))) { TIFFError("loadImage", "Unable to read contiguous strips into buffer"); return (-1); } } else { if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump))) { TIFFError("loadImage", "Unable to read separate strips into buffer"); return (-1); } } break; case TILE: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read contiguous tiles into buffer"); return (-1); } } else { if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read separate tiles into buffer"); return (-1); } } break; default: TIFFError("loadImage", "Unsupported image file format"); return (-1); break; } if ((dump->infile != NULL) && (dump->level == 2)) { dump_info (dump->infile, dump->format, "loadImage", "Image width %d, length %d, Raw image data, %4d bytes", width, length, buffsize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d", bps, spp); for (i = 0; i < length; i++) dump_buffer(dump->infile, dump->format, 1, scanlinesize, i, read_buff + (i * scanlinesize)); } return (0); } /* end loadImage */ Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities in heap or stack allocated buffers. Reported as MSVR 35093, MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR 35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities in heap allocated buffers. Reported as MSVR 35094. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1() that didn't reset the tif_rawcc and tif_rawcp members. I'm not completely sure if that could happen in practice outside of the odd behaviour of t2p_seekproc() of tiff2pdf). The report points that a better fix could be to check the return value of TIFFFlushData1() in places where it isn't done currently, but it seems this patch is enough. Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan & Suha Can from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-787 Target: 1 Example 2: Code: render_state_set_resolution( RenderState state, int resolution ) { state->resolution = resolution; state->need_rescale = 1; } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, cpu_used_); } else if (video->frame() == 3) { vpx_active_map_t map = {0}; uint8_t active_map[9 * 13] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, }; map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; ASSERT_EQ(map.cols, 13u); ASSERT_EQ(map.rows, 9u); map.active_map = active_map; encoder->Control(VP8E_SET_ACTIVEMAP, &map); } else if (video->frame() == 15) { vpx_active_map_t map = {0}; map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; map.active_map = NULL; encoder->Control(VP8E_SET_ACTIVEMAP, &map); } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb_is_err_queue(skb) && skb->len && (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS)) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } } Commit Message: tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: void Browser::UseCompactNavigationBarChanged() { window_->ToggleUseCompactNavigationBar(); } Commit Message: Implement a bubble that appears at the top of the screen when a tab enters fullscreen mode via webkitRequestFullScreen(), telling the user how to exit fullscreen. This is implemented as an NSView rather than an NSWindow because the floating chrome that appears in presentation mode should overlap the bubble. Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac: the mode in which the UI is hidden, accessible by moving the cursor to the top of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode. On Lion, however, fullscreen mode does not imply presentation mode: in non-presentation fullscreen mode, the chrome is permanently shown. It is possible to switch between presentation mode and fullscreen mode using the presentation mode UI control. When a tab initiates fullscreen mode on Lion, we enter presentation mode if not in presentation mode already. When the user exits fullscreen mode using Chrome UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we return the user to the mode they were in before the tab entered fullscreen. BUG=14471 TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen. Need to test the Lion logic somehow, with no Lion trybots. BUG=96883 Original review http://codereview.chromium.org/7890056/ TBR=thakis Review URL: http://codereview.chromium.org/7920024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int dev_set_mtu(struct net_device *dev, int new_mtu) { const struct net_device_ops *ops = dev->netdev_ops; int err; if (new_mtu == dev->mtu) return 0; /* MTU must be positive. */ if (new_mtu < 0) return -EINVAL; if (!netif_device_present(dev)) return -ENODEV; err = 0; if (ops->ndo_change_mtu) err = ops->ndo_change_mtu(dev, new_mtu); else dev->mtu = new_mtu; if (!err && dev->flags & IFF_UP) call_netdevice_notifiers(NETDEV_CHANGEMTU, dev); return err; } Commit Message: veth: Dont kfree_skb() after dev_forward_skb() In case of congestion, netif_rx() frees the skb, so we must assume dev_forward_skb() also consume skb. Bug introduced by commit 445409602c092 (veth: move loopback logic to common location) We must change dev_forward_skb() to always consume skb, and veth to not double free it. Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3 Reported-by: Martín Ferrari <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int link_pipe(struct pipe_inode_info *ipipe, struct pipe_inode_info *opipe, size_t len, unsigned int flags) { struct pipe_buffer *ibuf, *obuf; int ret = 0, i = 0, nbuf; /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes * could deadlock (one doing tee from A -> B, the other from B -> A). */ pipe_double_lock(ipipe, opipe); do { if (!opipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; break; } /* * If we have iterated all input buffers or ran out of * output room, break. */ if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) break; ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1)); nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); /* * Get a reference to this pipe buffer, * so we can copy the contents over. */ pipe_buf_get(ipipe, ibuf); obuf = opipe->bufs + nbuf; *obuf = *ibuf; /* * Don't inherit the gift flag, we need to * prevent multiple steals of this page. */ obuf->flags &= ~PIPE_BUF_FLAG_GIFT; pipe_buf_mark_unmergeable(obuf); if (obuf->len > len) obuf->len = len; opipe->nrbufs++; ret += obuf->len; len -= obuf->len; i++; } while (len); /* * return EAGAIN if we have the potential of some data in the * future, otherwise just return 0 */ if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK)) ret = -EAGAIN; pipe_unlock(ipipe); pipe_unlock(opipe); /* * If we put data in the output pipe, wakeup any potential readers. */ if (ret > 0) wakeup_pipe_readers(opipe); return ret; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416 Target: 1 Example 2: Code: is_cross_tgs_principal(krb5_const_principal principal) { if (!krb5_is_tgs_principal(principal)) return FALSE; if (!data_eq(*krb5_princ_component(kdc_context, principal, 1), *krb5_princ_realm(kdc_context, principal))) return TRUE; else return FALSE; } Commit Message: Fix S4U2Self KDC crash when anon is restricted In validate_as_request(), when enforcing restrict_anonymous_to_tgt, use client.princ instead of request->client; the latter is NULL when validating S4U2Self requests. CVE-2016-3120: In MIT krb5 1.9 and later, an authenticated attacker can cause krb5kdc to dereference a null pointer if the restrict_anonymous_to_tgt option is set to true, by making an S4U2Self request. CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:H/RL:OF/RC:C ticket: 8458 (new) target_version: 1.14-next target_version: 1.13-next CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: gfx::Image GetTabAlertIndicatorAffordanceImage(TabAlertState alert_state, SkColor button_color) { switch (alert_state) { case TabAlertState::AUDIO_PLAYING: return GetTabAlertIndicatorImage(TabAlertState::AUDIO_MUTING, button_color); case TabAlertState::AUDIO_MUTING: return GetTabAlertIndicatorImage(TabAlertState::AUDIO_PLAYING, button_color); case TabAlertState::NONE: case TabAlertState::MEDIA_RECORDING: case TabAlertState::TAB_CAPTURING: case TabAlertState::BLUETOOTH_CONNECTED: case TabAlertState::USB_CONNECTED: return GetTabAlertIndicatorImage(alert_state, button_color); } NOTREACHED(); return GetTabAlertIndicatorImage(alert_state, button_color); } Commit Message: Fix nullptr crash in IsSiteMuted This CL adds a nullptr check in IsSiteMuted to prevent a crash on Mac. Bug: 797647 Change-Id: Ic36f0fb39f2dbdf49d2bec9e548a4a6e339dc9a2 Reviewed-on: https://chromium-review.googlesource.com/848245 Reviewed-by: Mounir Lamouri <[email protected]> Reviewed-by: Yuri Wiitala <[email protected]> Commit-Queue: Tommy Steimel <[email protected]> Cr-Commit-Position: refs/heads/master@{#526825} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ChromeClientImpl::Focus() { if (web_view_->Client()) web_view_->Client()->DidFocus(); } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID: Target: 1 Example 2: Code: static int out_get_render_position(const struct audio_stream_out *stream, uint32_t *dsp_frames) { (void)stream; *dsp_frames = 0; return -EINVAL; } Commit Message: Fix audio record pre-processing proc_buf_out consistently initialized. intermediate scratch buffers consistently initialized. prevent read failure from overwriting memory. Test: POC, CTS, camera record Bug: 62873231 Change-Id: Ie26e12a419a5819c1c5c3a0bcf1876d6d7aca686 (cherry picked from commit 6d7b330c27efba944817e647955da48e54fd74eb) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool tcmur_unregister_handler(struct tcmur_handler *handler) { int i; for (i = 0; i < darray_size(g_runner_handlers); i++) { if (darray_item(g_runner_handlers, i) == handler) { darray_remove(g_runner_handlers, i); return true; } } return false; } Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS Trying to unregister an internal handler ended up in a SEGFAULT, because the tcmur_handler->opaque was NULL. Way to reproduce: dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow we use a newly introduced boolean in struct tcmur_handler for keeping track of external handlers. As suggested by mikechristie adjusting the public data structure is acceptable. CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline int l2cap_config_req(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u16 cmd_len, u8 *data) { struct l2cap_conf_req *req = (struct l2cap_conf_req *) data; u16 dcid, flags; u8 rsp[64]; struct sock *sk; int len; dcid = __le16_to_cpu(req->dcid); flags = __le16_to_cpu(req->flags); BT_DBG("dcid 0x%4.4x flags 0x%2.2x", dcid, flags); sk = l2cap_get_chan_by_scid(&conn->chan_list, dcid); if (!sk) return -ENOENT; if (sk->sk_state == BT_DISCONN) goto unlock; /* Reject if config buffer is too small. */ len = cmd_len - sizeof(*req); if (l2cap_pi(sk)->conf_len + len > sizeof(l2cap_pi(sk)->conf_req)) { l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, l2cap_build_conf_rsp(sk, rsp, L2CAP_CONF_REJECT, flags), rsp); goto unlock; } /* Store config. */ memcpy(l2cap_pi(sk)->conf_req + l2cap_pi(sk)->conf_len, req->data, len); l2cap_pi(sk)->conf_len += len; if (flags & 0x0001) { /* Incomplete config. Send empty response. */ l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, l2cap_build_conf_rsp(sk, rsp, L2CAP_CONF_SUCCESS, 0x0001), rsp); goto unlock; } /* Complete config. */ len = l2cap_parse_conf_req(sk, rsp); if (len < 0) goto unlock; l2cap_send_cmd(conn, cmd->ident, L2CAP_CONF_RSP, len, rsp); /* Reset config buffer. */ l2cap_pi(sk)->conf_len = 0; if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_OUTPUT_DONE)) goto unlock; if (l2cap_pi(sk)->conf_state & L2CAP_CONF_INPUT_DONE) { sk->sk_state = BT_CONNECTED; l2cap_chan_ready(sk); goto unlock; } if (!(l2cap_pi(sk)->conf_state & L2CAP_CONF_REQ_SENT)) { u8 buf[64]; l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ, l2cap_build_conf_req(sk, buf), buf); } unlock: bh_unlock_sock(sk); return 0; } Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode Add support to config_req and config_rsp to configure ERTM and Streaming mode. If the remote device specifies ERTM or Streaming mode, then the same mode is proposed. Otherwise ERTM or Basic mode is used. And in case of a state 2 device, the remote device should propose the same mode. If not, then the channel gets disconnected. Signed-off-by: Gustavo F. Padovan <[email protected]> Signed-off-by: Marcel Holtmann <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: ps_parser_to_fixed_array( PS_Parser parser, FT_Int max_values, FT_Fixed* values, FT_Int power_ten ) { ps_parser_skip_spaces( parser ); return ps_tofixedarray( &parser->cursor, parser->limit, max_values, values, power_ten ); } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WebElement RenderFrameImpl::GetFocusedElement() { WebDocument doc = frame_->document(); if (!doc.isNull()) return doc.focusedElement(); return WebElement(); } Commit Message: Add logging to figure out which IPC we're failing to deserialize in RenderFrame. BUG=369553 [email protected] Review URL: https://codereview.chromium.org/263833020 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268565 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FetchManager::Loader::Start() { if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) && !execution_context_->GetContentSecurityPolicy()->AllowConnectToSource( fetch_request_data_->Url())) { PerformNetworkError( "Refused to connect to '" + fetch_request_data_->Url().ElidedString() + "' because it violates the document's Content Security Policy."); return; } if ((SecurityOrigin::Create(fetch_request_data_->Url()) ->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) || (fetch_request_data_->Url().ProtocolIsData() && fetch_request_data_->SameOriginDataURLFlag()) || (fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) { PerformSchemeFetch(); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) { PerformNetworkError("Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". Request mode is \"same-origin\" but the URL\'s " "origin is not same as the request origin " + fetch_request_data_->Origin()->ToString() + "."); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) { fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting); PerformSchemeFetch(); return; } if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI( fetch_request_data_->Url().Protocol())) { PerformNetworkError( "Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". URL scheme must be \"http\" or \"https\" for CORS request."); return; } fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting); PerformHTTPFetch(); } Commit Message: [Fetch API] Fix redirect leak on "no-cors" requests The spec issue is now fixed, and this CL follows the spec change[1]. 1: https://github.com/whatwg/fetch/commit/14858d3e9402285a7ff3b5e47a22896ff3adc95d Bug: 791324 Change-Id: Ic3e3955f43578b38fc44a5a6b2a1b43d56a2becb Reviewed-on: https://chromium-review.googlesource.com/1023613 Reviewed-by: Tsuyoshi Horo <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#552964} CWE ID: CWE-200 Target: 1 Example 2: Code: void WorkerGlobalScopeFileSystem::webkitRequestFileSystem(WorkerGlobalScope& worker, int type, long long size, PassOwnPtr<FileSystemCallback> successCallback, PassOwnPtr<ErrorCallback> errorCallback) { ExecutionContext* secureContext = worker.executionContext(); if (!secureContext->securityOrigin()->canAccessFileSystem()) { DOMFileSystem::scheduleCallback(&worker, errorCallback, FileError::create(FileError::SECURITY_ERR)); return; } FileSystemType fileSystemType = static_cast<FileSystemType>(type); if (!DOMFileSystemBase::isValidType(fileSystemType)) { DOMFileSystem::scheduleCallback(&worker, errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR)); return; } LocalFileSystem::from(worker)->requestFileSystem(&worker, fileSystemType, size, FileSystemCallbacks::create(successCallback, errorCallback, &worker, fileSystemType)); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int intel_pmu_drain_bts_buffer(void) { struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events); struct debug_store *ds = cpuc->ds; struct bts_record { u64 from; u64 to; u64 flags; }; struct perf_event *event = cpuc->events[X86_PMC_IDX_FIXED_BTS]; struct bts_record *at, *top; struct perf_output_handle handle; struct perf_event_header header; struct perf_sample_data data; struct pt_regs regs; if (!event) return 0; if (!x86_pmu.bts_active) return 0; at = (struct bts_record *)(unsigned long)ds->bts_buffer_base; top = (struct bts_record *)(unsigned long)ds->bts_index; if (top <= at) return 0; ds->bts_index = ds->bts_buffer_base; perf_sample_data_init(&data, 0); data.period = event->hw.last_period; regs.ip = 0; /* * Prepare a generic sample, i.e. fill in the invariant fields. * We will overwrite the from and to address before we output * the sample. */ perf_prepare_sample(&header, &data, event, &regs); if (perf_output_begin(&handle, event, header.size * (top - at), 1, 1)) return 1; for (; at < top; at++) { data.ip = at->from; data.addr = at->to; perf_output_sample(&handle, &header, &data, event); } perf_output_end(&handle); /* There's new data available. */ event->hw.interrupts++; event->pending_kill = POLL_IN; return 1; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: allocate(struct file *file, int allocate_idat) { struct control *control = png_voidcast(struct control*, file->alloc_ptr); if (allocate_idat) { assert(file->idat == NULL); IDAT_init(&control->idat, file); } else /* chunk */ { assert(file->chunk == NULL); chunk_init(&control->chunk, file); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: static MagickBooleanType IsVICAR(const unsigned char *magick, const size_t length) { if (length < 14) return(MagickFalse); if (LocaleNCompare((const char *) magick,"LBLSIZE",7) == 0) return(MagickTrue); if (LocaleNCompare((const char *) magick,"NJPL1I",6) == 0) return(MagickTrue); if (LocaleNCompare((const char *) magick,"PDS_VERSION_ID",14) == 0) return(MagickTrue); return(MagickFalse); } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ChromeClientImpl::PrintDelegate(LocalFrame* frame) { NotifyPopupOpeningObservers(); if (web_view_->Client()) web_view_->Client()->PrintPage(WebLocalFrameImpl::FromFrame(frame)); } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void OnSuggestionModelAdded(UiScene* scene, UiBrowserInterface* browser, Model* model, SuggestionBinding* element_binding) { auto icon = base::MakeUnique<VectorIcon>(100); icon->SetDrawPhase(kPhaseForeground); icon->SetType(kTypeOmniboxSuggestionIcon); icon->set_hit_testable(false); icon->SetSize(kSuggestionIconSizeDMM, kSuggestionIconSizeDMM); BindColor(model, icon.get(), &ColorScheme::omnibox_icon, &VectorIcon::SetColor); VectorIcon* p_icon = icon.get(); auto icon_box = base::MakeUnique<UiElement>(); icon_box->SetDrawPhase(kPhaseNone); icon_box->SetType(kTypeOmniboxSuggestionIconField); icon_box->SetSize(kSuggestionIconFieldWidthDMM, kSuggestionHeightDMM); icon_box->AddChild(std::move(icon)); auto content_text = base::MakeUnique<Text>(kSuggestionContentTextHeightDMM); content_text->SetDrawPhase(kPhaseForeground); content_text->SetType(kTypeOmniboxSuggestionContentText); content_text->set_hit_testable(false); content_text->SetTextLayoutMode(TextLayoutMode::kSingleLineFixedWidth); content_text->SetSize(kSuggestionTextFieldWidthDMM, 0); content_text->SetTextAlignment(UiTexture::kTextAlignmentLeft); BindColor(model, content_text.get(), &ColorScheme::omnibox_suggestion_content, &Text::SetColor); Text* p_content_text = content_text.get(); auto description_text = base::MakeUnique<Text>(kSuggestionDescriptionTextHeightDMM); description_text->SetDrawPhase(kPhaseForeground); description_text->SetType(kTypeOmniboxSuggestionDescriptionText); description_text->set_hit_testable(false); content_text->SetTextLayoutMode(TextLayoutMode::kSingleLineFixedWidth); description_text->SetSize(kSuggestionTextFieldWidthDMM, 0); description_text->SetTextAlignment(UiTexture::kTextAlignmentLeft); BindColor(model, description_text.get(), &ColorScheme::omnibox_suggestion_description, &Text::SetColor); Text* p_description_text = description_text.get(); auto text_layout = base::MakeUnique<LinearLayout>(LinearLayout::kDown); text_layout->SetType(kTypeOmniboxSuggestionTextLayout); text_layout->set_hit_testable(false); text_layout->set_margin(kSuggestionLineGapDMM); text_layout->AddChild(std::move(content_text)); text_layout->AddChild(std::move(description_text)); auto right_margin = base::MakeUnique<UiElement>(); right_margin->SetDrawPhase(kPhaseNone); right_margin->SetSize(kSuggestionRightMarginDMM, kSuggestionHeightDMM); auto suggestion_layout = base::MakeUnique<LinearLayout>(LinearLayout::kRight); suggestion_layout->SetType(kTypeOmniboxSuggestionLayout); suggestion_layout->set_hit_testable(false); suggestion_layout->AddChild(std::move(icon_box)); suggestion_layout->AddChild(std::move(text_layout)); suggestion_layout->AddChild(std::move(right_margin)); auto background = Create<Button>( kNone, kPhaseForeground, base::BindRepeating( [](UiBrowserInterface* b, Model* m, SuggestionBinding* e) { b->Navigate(e->model()->destination); m->omnibox_input_active = false; }, base::Unretained(browser), base::Unretained(model), base::Unretained(element_binding))); background->SetType(kTypeOmniboxSuggestionBackground); background->set_hit_testable(true); background->set_bubble_events(true); background->set_bounds_contain_children(true); background->set_hover_offset(0.0); BindButtonColors(model, background.get(), &ColorScheme::suggestion_button_colors, &Button::SetButtonColors); background->AddChild(std::move(suggestion_layout)); element_binding->bindings().push_back( VR_BIND_FUNC(base::string16, SuggestionBinding, element_binding, model()->content, Text, p_content_text, SetText)); element_binding->bindings().push_back( base::MakeUnique<Binding<base::string16>>( base::BindRepeating( [](SuggestionBinding* m) { return m->model()->description; }, base::Unretained(element_binding)), base::BindRepeating( [](Text* v, const base::string16& text) { v->SetVisibleImmediately(!text.empty()); v->set_requires_layout(!text.empty()); if (!text.empty()) { v->SetText(text); } }, base::Unretained(p_description_text)))); element_binding->bindings().push_back( VR_BIND(AutocompleteMatch::Type, SuggestionBinding, element_binding, model()->type, VectorIcon, p_icon, SetIcon(AutocompleteMatch::TypeToVectorIcon(value)))); element_binding->set_view(background.get()); scene->AddUiElement(kOmniboxSuggestions, std::move(background)); } Commit Message: Fix wrapping behavior of description text in omnibox suggestion This regression is introduced by https://chromium-review.googlesource.com/c/chromium/src/+/827033 The description text should not wrap. Bug: NONE Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: Iaac5e6176e1730853406602835d61fe1e80ec0d0 Reviewed-on: https://chromium-review.googlesource.com/839960 Reviewed-by: Christopher Grant <[email protected]> Commit-Queue: Biao She <[email protected]> Cr-Commit-Position: refs/heads/master@{#525806} CWE ID: CWE-200 Target: 1 Example 2: Code: void cifs_oplock_break(struct work_struct *work) { struct cifsFileInfo *cfile = container_of(work, struct cifsFileInfo, oplock_break); struct inode *inode = cfile->dentry->d_inode; struct cifsInodeInfo *cinode = CIFS_I(inode); struct cifs_tcon *tcon = tlink_tcon(cfile->tlink); int rc = 0; if (!CIFS_CACHE_WRITE(cinode) && CIFS_CACHE_READ(cinode) && cifs_has_mand_locks(cinode)) { cifs_dbg(FYI, "Reset oplock to None for inode=%p due to mand locks\n", inode); cinode->oplock = 0; } if (inode && S_ISREG(inode->i_mode)) { if (CIFS_CACHE_READ(cinode)) break_lease(inode, O_RDONLY); else break_lease(inode, O_WRONLY); rc = filemap_fdatawrite(inode->i_mapping); if (!CIFS_CACHE_READ(cinode)) { rc = filemap_fdatawait(inode->i_mapping); mapping_set_error(inode->i_mapping, rc); cifs_invalidate_mapping(inode); } cifs_dbg(FYI, "Oplock flush inode %p rc %d\n", inode, rc); } rc = cifs_push_locks(cfile); if (rc) cifs_dbg(VFS, "Push locks rc = %d\n", rc); /* * releasing stale oplock after recent reconnect of smb session using * a now incorrect file handle is not a data integrity issue but do * not bother sending an oplock release if session to server still is * disconnected since oplock already released by the server */ if (!cfile->oplock_break_cancelled) { rc = tcon->ses->server->ops->oplock_response(tcon, &cfile->fid, cinode); cifs_dbg(FYI, "Oplock release rc = %d\n", rc); } } Commit Message: cifs: ensure that uncached writes handle unmapped areas correctly It's possible for userland to pass down an iovec via writev() that has a bogus user pointer in it. If that happens and we're doing an uncached write, then we can end up getting less bytes than we expect from the call to iov_iter_copy_from_user. This is CVE-2014-0069 cifs_iovec_write isn't set up to handle that situation however. It'll blindly keep chugging through the page array and not filling those pages with anything useful. Worse yet, we'll later end up with a negative number in wdata->tailsz, which will confuse the sending routines and cause an oops at the very least. Fix this by having the copy phase of cifs_iovec_write stop copying data in this situation and send the last write as a short one. At the same time, we want to avoid sending a zero-length write to the server, so break out of the loop and set rc to -EFAULT if that happens. This also allows us to handle the case where no address in the iovec is valid. [Note: Marking this for stable on v3.4+ kernels, but kernels as old as v2.6.38 may have a similar problem and may need similar fix] Cc: <[email protected]> # v3.4+ Reviewed-by: Pavel Shilovsky <[email protected]> Reported-by: Al Viro <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) { if (HasTextBeingDragged()) return ui::DragDropTypes::DRAG_NONE; if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) { GURL url; base::string16 title; if (data.GetURLAndTitle( ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) { base::string16 text( StripJavascriptSchemas(base::UTF8ToUTF16(url.spec()))); if (model()->CanPasteAndGo(text)) { model()->PasteAndGo(text); return ui::DragDropTypes::DRAG_COPY; } } } else if (data.HasString()) { base::string16 text; if (data.GetString(&text)) { base::string16 collapsed_text(base::CollapseWhitespace(text, true)); if (model()->CanPasteAndGo(collapsed_text)) model()->PasteAndGo(collapsed_text); return ui::DragDropTypes::DRAG_COPY; } } return ui::DragDropTypes::DRAG_NONE; } Commit Message: Strip JavaScript schemas on Linux text drop When dropping text onto the Omnibox, any leading JavaScript schemes should be stripped to avoid a "self-XSS" attack. This stripping already occurs in all cases except when plaintext is dropped on Linux. This CL corrects that oversight. Bug: 768910 Change-Id: I43af24ace4a13cf61d15a32eb9382dcdd498a062 Reviewed-on: https://chromium-review.googlesource.com/685638 Reviewed-by: Justin Donnelly <[email protected]> Commit-Queue: Eric Lawrence <[email protected]> Cr-Commit-Position: refs/heads/master@{#504695} CWE ID: CWE-79 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PageInfo::OnChangePasswordButtonPressed( content::WebContents* web_contents) { #if defined(FULL_SAFE_BROWSING) DCHECK(password_protection_service_); DCHECK(safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE || safe_browsing_status_ == SAFE_BROWSING_STATUS_ENTERPRISE_PASSWORD_REUSE); password_protection_service_->OnUserAction( web_contents, safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE ? PasswordReuseEvent::SIGN_IN_PASSWORD : PasswordReuseEvent::ENTERPRISE_PASSWORD, safe_browsing::WarningUIType::PAGE_INFO, safe_browsing::WarningAction::CHANGE_PASSWORD); #endif } Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii." This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c. Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests: https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649 PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered PageInfoBubbleViewTest.EnsureCloseCallback PageInfoBubbleViewTest.NotificationPermissionRevokeUkm PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart PageInfoBubbleViewTest.SetPermissionInfo PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0 [ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered ==9056==WARNING: MemorySanitizer: use-of-uninitialized-value #0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3 #1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7 #2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8 #3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3 #4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24 ... Original change's description: > PageInfo: decouple safe browsing and TLS statii. > > Previously, the Page Info bubble maintained a single variable to > identify all reasons that a page might have a non-standard status. This > lead to the display logic making assumptions about, for instance, the > validity of a certificate when the page was flagged by Safe Browsing. > > This CL separates out the Safe Browsing status from the site identity > status so that the page info bubble can inform the user that the site's > certificate is invalid, even if it's also flagged by Safe Browsing. > > Bug: 869925 > Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537 > Reviewed-by: Mustafa Emre Acer <[email protected]> > Reviewed-by: Bret Sepulveda <[email protected]> > Auto-Submit: Joe DeBlasio <[email protected]> > Commit-Queue: Joe DeBlasio <[email protected]> > Cr-Commit-Position: refs/heads/master@{#671847} [email protected],[email protected],[email protected] Change-Id: I8be652952e7276bcc9266124693352e467159cc4 No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 869925 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985 Reviewed-by: Takashi Sakamoto <[email protected]> Commit-Queue: Takashi Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#671932} CWE ID: CWE-311 Target: 1 Example 2: Code: ~CompositorSwapClient() { } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void anubis_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src) { struct anubis_ctx *ctx = crypto_tfm_ctx(tfm); anubis_crypt(ctx->D, dst, src, ctx->R); } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool RenderFrameHostManager::CanSubframeSwapProcess( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* dest_instance, bool was_server_redirect) { DCHECK(!source_instance || !dest_instance); GURL resolved_url = dest_url; if (url::Origin::Create(resolved_url).unique()) { if (source_instance) { resolved_url = source_instance->GetSiteURL(); } else if (dest_instance) { resolved_url = dest_instance->GetSiteURL(); } else { if (!was_server_redirect) return false; } } if (!IsRendererTransferNeededForNavigation(render_frame_host_.get(), resolved_url)) { DCHECK(!dest_instance || dest_instance == render_frame_host_->GetSiteInstance()); return false; } return true; } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285 Target: 1 Example 2: Code: void DidConsume(int bytes) { SetOffset(used_ + bytes); } Commit Message: net: don't process truncated headers on HTTPS connections. This change causes us to not process any headers unless they are correctly terminated with a \r\n\r\n sequence. BUG=244260 Review URL: https://chromiumcodereview.appspot.com/15688012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202927 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebRuntimeFeatures::enableSessionStorage(bool enable) { RuntimeEnabledFeatures::setSessionStorageEnabled(enable); } Commit Message: Remove SpeechSynthesis runtime flag (status=stable) BUG=402536 Review URL: https://codereview.chromium.org/482273005 git-svn-id: svn://svn.chromium.org/blink/trunk@180763 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-94 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data) { HashAndString *data = (HashAndString*) user_data; gchar *in = (gchar*) val; g_hash_table_insert (data->hash, g_strdup ((gchar*) key), g_strjoin (" ", data->string, in, NULL)); } Commit Message: CWE ID: CWE-264 Target: 1 Example 2: Code: void CoordinatorImpl::OnHeapDumpTimeOut(uint64_t dump_guid) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); QueuedRequest* request = GetCurrentRequest(); if (!request || request->dump_guid != dump_guid) return; if (request->heap_dump_in_progress) { request->heap_dump_in_progress = false; FinalizeGlobalMemoryDumpIfAllManagersReplied(); } } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <[email protected]> Commit-Queue: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: OxideQQuickWebView::WebProcessStatus OxideQQuickWebView::webProcessStatus() const { Q_D(const OxideQQuickWebView); Q_STATIC_ASSERT( WebProcessRunning == static_cast<WebProcessStatus>(oxide::qt::WEB_PROCESS_RUNNING)); Q_STATIC_ASSERT( WebProcessKilled == static_cast<WebProcessStatus>(oxide::qt::WEB_PROCESS_KILLED)); Q_STATIC_ASSERT( WebProcessCrashed == static_cast<WebProcessStatus>(oxide::qt::WEB_PROCESS_CRASHED)); if (!d->proxy_) { return WebProcessRunning; } return static_cast<WebProcessStatus>(d->proxy_->webProcessStatus()); } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: V8ContextNativeHandler::V8ContextNativeHandler(ScriptContext* context, Dispatcher* dispatcher) : ObjectBackedNativeHandler(context), context_(context), dispatcher_(dispatcher) { RouteFunction("GetAvailability", base::Bind(&V8ContextNativeHandler::GetAvailability, base::Unretained(this))); RouteFunction("GetModuleSystem", base::Bind(&V8ContextNativeHandler::GetModuleSystem, base::Unretained(this))); RouteFunction( "RunWithNativesEnabledModuleSystem", base::Bind(&V8ContextNativeHandler::RunWithNativesEnabledModuleSystem, base::Unretained(this))); } Commit Message: Add a test that getModuleSystem() doesn't work cross origin BUG=504011 [email protected] [email protected] Review URL: https://codereview.chromium.org/1241443004 Cr-Commit-Position: refs/heads/master@{#338663} CWE ID: CWE-79 Target: 1 Example 2: Code: void WebBluetoothServiceImpl::OnStartDiscoverySession( blink::mojom::WebBluetoothScanClientAssociatedPtr client, blink::mojom::WebBluetoothRequestLEScanOptionsPtr options, std::unique_ptr<device::BluetoothDiscoverySession> session) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!discovery_session_); discovery_session_ = std::move(session); if (AreScanFiltersAllowed(options->filters)) { auto scanning_client = std::make_unique<ScanningClient>( std::move(client), std::move(options), std::move(discovery_callback_), nullptr); scanning_client->RunRequestScanningStartCallback( blink::mojom::WebBluetoothResult::SUCCESS); scanning_client->set_allow_send_event(true); scanning_clients_.push_back(std::move(scanning_client)); return; } device_scanning_prompt_controller_ = std::make_unique<BluetoothDeviceScanningPromptController>( this, render_frame_host_); scanning_clients_.push_back(std::make_unique<ScanningClient>( std::move(client), std::move(options), std::move(discovery_callback_), device_scanning_prompt_controller_.get())); device_scanning_prompt_controller_->ShowPermissionPrompt(); } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 4, &tmp)) return -1; *val = (tmp & 0x80000000) ? (-JAS_CAST(longlong, (((~tmp) & 0x7fffffff) + 1))) : JAS_CAST(longlong, tmp); return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void MultibufferDataSource::StartCallback() { DCHECK(render_task_runner_->BelongsToCurrentThread()); if (!init_cb_) { SetReader(nullptr); return; } bool success = reader_ && reader_->Available() > 0 && url_data() && (!assume_fully_buffered() || url_data()->length() != kPositionNotSpecified); if (success) { { base::AutoLock auto_lock(lock_); total_bytes_ = url_data()->length(); } streaming_ = !assume_fully_buffered() && (total_bytes_ == kPositionNotSpecified || !url_data()->range_supported()); media_log_->SetDoubleProperty("total_bytes", static_cast<double>(total_bytes_)); media_log_->SetBooleanProperty("streaming", streaming_); } else { SetReader(nullptr); } base::AutoLock auto_lock(lock_); if (stop_signal_received_) return; if (success) { if (total_bytes_ != kPositionNotSpecified) { host_->SetTotalBytes(total_bytes_); if (assume_fully_buffered()) host_->AddBufferedByteRange(0, total_bytes_); } media_log_->SetBooleanProperty("single_origin", single_origin_); media_log_->SetBooleanProperty("passed_cors_access_check", DidPassCORSAccessCheck()); media_log_->SetBooleanProperty("range_header_supported", url_data()->range_supported()); } render_task_runner_->PostTask(FROM_HERE, base::Bind(std::move(init_cb_), success)); UpdateBufferSizes(); UpdateLoadingState_Locked(true); } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Target: 1 Example 2: Code: int test_div_word(BIO *bp) { BIGNUM a,b; BN_ULONG r,s; int i; BN_init(&a); BN_init(&b); for (i=0; i<num0; i++) { do { BN_bntest_rand(&a,512,-1,0); BN_bntest_rand(&b,BN_BITS2,-1,0); s = b.d[0]; } while (!s); BN_copy(&b, &a); r = BN_div_word(&b, s); if (bp != NULL) { if (!results) { BN_print(bp,&a); BIO_puts(bp," / "); print_word(bp,s); BIO_puts(bp," - "); } BN_print(bp,&b); BIO_puts(bp,"\n"); if (!results) { BN_print(bp,&a); BIO_puts(bp," % "); print_word(bp,s); BIO_puts(bp," - "); } print_word(bp,r); BIO_puts(bp,"\n"); } BN_mul_word(&b,s); BN_add_word(&b,r); BN_sub(&b,&a,&b); if(!BN_is_zero(&b)) { fprintf(stderr,"Division (word) test failed!\n"); return 0; } } BN_free(&a); BN_free(&b); return(1); } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <[email protected]> CWE ID: CWE-310 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, length; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->storage_class=PseudoClass; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; } switch (sun_info.maptype) { case RMT_NONE: { if (sun_info.depth < 24) { /* Create linear color ramp. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } break; } case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum(sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum(sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum(sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: break; } image->matte=sun_info.depth == 32 ? MagickTrue : MagickFalse; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); number_pixels=(MagickSizeType) image->columns*image->rows; if ((sun_info.type != RT_ENCODED) && (sun_info.depth >= 8) && ((number_pixels*((sun_info.depth+7)/8)) > sun_info.length)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_data=(unsigned char *) AcquireQuantumMemory((size_t) sun_info.length, sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); sun_pixels=sun_data; bytes_per_line=0; if (sun_info.type == RT_ENCODED) { size_t height; /* Read run-length encoded raster pixels. */ height=sun_info.height; bytes_per_line=sun_info.width*sun_info.depth; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); } /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) SetPixelIndex(indexes+x+7-bit,((*p) & (0x01 << bit) ? 0x00 : 0x01)); p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) SetPixelIndex(indexes+x+7-bit,(*p) & (0x01 << bit) ? 0x00 : 0x01); p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { if (bytes_per_line == 0) bytes_per_line=image->columns; length=image->rows*(image->columns+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->matte != MagickFalse) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; length=image->rows*(bytes_per_line+image->columns % 2); if (((sun_info.type == RT_ENCODED) && (length > (bytes_per_line*image->rows))) || ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*p++)); if (sun_info.type == RT_STANDARD) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); } else { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); } if (image->colors != 0) { SetPixelRed(q,image->colormap[(ssize_t) GetPixelRed(q)].red); SetPixelGreen(q,image->colormap[(ssize_t) GetPixelGreen(q)].green); SetPixelBlue(q,image->colormap[(ssize_t) GetPixelBlue(q)].blue); } q++; } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: mobility_opt_print(netdissect_options *ndo, const u_char *bp, const unsigned len) { unsigned i, optlen; for (i = 0; i < len; i += optlen) { ND_TCHECK(bp[i]); if (bp[i] == IP6MOPT_PAD1) optlen = 1; else { if (i + 1 < len) { ND_TCHECK(bp[i + 1]); optlen = bp[i + 1] + 2; } else goto trunc; } if (i + optlen > len) goto trunc; ND_TCHECK(bp[i + optlen]); switch (bp[i]) { case IP6MOPT_PAD1: ND_PRINT((ndo, "(pad1)")); break; case IP6MOPT_PADN: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(padn: trunc)")); goto trunc; } ND_PRINT((ndo, "(padn)")); break; case IP6MOPT_REFRESH: if (len - i < IP6MOPT_REFRESH_MINLEN) { ND_PRINT((ndo, "(refresh: trunc)")); goto trunc; } /* units of 4 secs */ ND_TCHECK_16BITS(&bp[i+2]); ND_PRINT((ndo, "(refresh: %u)", EXTRACT_16BITS(&bp[i+2]) << 2)); break; case IP6MOPT_ALTCOA: if (len - i < IP6MOPT_ALTCOA_MINLEN) { ND_PRINT((ndo, "(altcoa: trunc)")); goto trunc; } ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2]))); break; case IP6MOPT_NONCEID: if (len - i < IP6MOPT_NONCEID_MINLEN) { ND_PRINT((ndo, "(ni: trunc)")); goto trunc; } ND_TCHECK_16BITS(&bp[i+2]); ND_TCHECK_16BITS(&bp[i+4]); ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)", EXTRACT_16BITS(&bp[i+2]), EXTRACT_16BITS(&bp[i+4]))); break; case IP6MOPT_AUTH: if (len - i < IP6MOPT_AUTH_MINLEN) { ND_PRINT((ndo, "(auth: trunc)")); goto trunc; } ND_PRINT((ndo, "(auth)")); break; default: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i])); goto trunc; } ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1])); break; } } return 0; trunc: return 1; } Commit Message: CVE-2017-13025/IPv6 mobility: Add a bounds check before fetching data This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't cause 'tcpdump: pcap_loop: truncated dump file' CWE ID: CWE-125 Target: 1 Example 2: Code: void serverLog(int level, const char *fmt, ...) { va_list ap; char msg[LOG_MAX_LEN]; if ((level&0xff) < server.verbosity) return; va_start(ap, fmt); vsnprintf(msg, sizeof(msg), fmt, ap); va_end(ap); serverLogRaw(level,msg); } Commit Message: Security: Cross Protocol Scripting protection. This is an attempt at mitigating problems due to cross protocol scripting, an attack targeting services using line oriented protocols like Redis that can accept HTTP requests as valid protocol, by discarding the invalid parts and accepting the payloads sent, for example, via a POST request. For this to be effective, when we detect POST and Host: and terminate the connection asynchronously, the networking code was modified in order to never process further input. It was later verified that in a pipelined request containing a POST command, the successive commands are not executed. CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: receive_carbon(void **state) { prof_input("/carbons on"); prof_connect(); assert_true(stbbr_received( "<iq id='*' type='set'><enable xmlns='urn:xmpp:carbons:2'/></iq>" )); stbbr_send( "<presence to='stabber@localhost' from='buddy1@localhost/mobile'>" "<priority>10</priority>" "<status>On my mobile</status>" "</presence>" ); assert_true(prof_output_exact("Buddy1 (mobile) is online, \"On my mobile\"")); prof_input("/msg Buddy1"); assert_true(prof_output_exact("unencrypted")); stbbr_send( "<message type='chat' to='stabber@localhost/profanity' from='buddy1@localhost'>" "<received xmlns='urn:xmpp:carbons:2'>" "<forwarded xmlns='urn:xmpp:forward:0'>" "<message id='prof_msg_7' xmlns='jabber:client' type='chat' lang='en' to='stabber@localhost/profanity' from='buddy1@localhost/mobile'>" "<body>test carbon from recipient</body>" "</message>" "</forwarded>" "</received>" "</message>" ); assert_true(prof_output_regex("Buddy1/mobile: .+test carbon from recipient")); } Commit Message: Add carbons from check CWE ID: CWE-346 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ResourceDispatcherHostImpl::OnSSLCertificateError( net::URLRequest* request, const net::SSLInfo& ssl_info, bool is_hsts_host) { DCHECK(request); ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); DCHECK(info); GlobalRequestID request_id(info->GetChildID(), info->GetRequestID()); int render_process_id; int render_view_id; if(!info->GetAssociatedRenderView(&render_process_id, &render_view_id)) NOTREACHED(); SSLManager::OnSSLCertificateError(ssl_delegate_weak_factory_.GetWeakPtr(), request_id, info->GetResourceType(), request->url(), render_process_id, render_view_id, ssl_info, is_hsts_host); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static struct svc_rdma_fastreg_mr *rdma_alloc_frmr(struct svcxprt_rdma *xprt) { struct ib_mr *mr; struct scatterlist *sg; struct svc_rdma_fastreg_mr *frmr; u32 num_sg; frmr = kmalloc(sizeof(*frmr), GFP_KERNEL); if (!frmr) goto err; num_sg = min_t(u32, RPCSVC_MAXPAGES, xprt->sc_frmr_pg_list_len); mr = ib_alloc_mr(xprt->sc_pd, IB_MR_TYPE_MEM_REG, num_sg); if (IS_ERR(mr)) goto err_free_frmr; sg = kcalloc(RPCSVC_MAXPAGES, sizeof(*sg), GFP_KERNEL); if (!sg) goto err_free_mr; sg_init_table(sg, RPCSVC_MAXPAGES); frmr->mr = mr; frmr->sg = sg; INIT_LIST_HEAD(&frmr->frmr_list); return frmr; err_free_mr: ib_dereg_mr(mr); err_free_frmr: kfree(frmr); err: return ERR_PTR(-ENOMEM); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t OMXNodeInstance::useBuffer( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) { return BAD_VALUE; } BufferMeta *buffer_meta; bool useBackup = mMetadataType[portIndex] != kMetadataBufferTypeInvalid; OMX_U8 *data = static_cast<OMX_U8 *>(params->pointer()); if (useBackup) { data = new (std::nothrow) OMX_U8[allottedSize]; if (data == NULL) { return NO_MEMORY; } memset(data, 0, allottedSize); if (allottedSize != params->size()) { CLOG_ERROR(useBuffer, BAD_VALUE, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, data)); delete[] data; return BAD_VALUE; } buffer_meta = new BufferMeta( params, portIndex, false /* copyToOmx */, false /* copyFromOmx */, data); } else { buffer_meta = new BufferMeta( params, portIndex, false /* copyFromOmx */, false /* copyToOmx */, NULL); } OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_UseBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize, data); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER( portIndex, (size_t)allottedSize, data)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT( *buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer())); return OK; } Commit Message: IOMX: do not convert ANWB to gralloc source in emptyBuffer Bug: 29422020 Bug: 31412859 Change-Id: If48e3e0b6f1af99a459fdc3f6f03744bbf0dc375 (cherry picked from commit 534bb6132a6a664f90b42b3ef81298b42efb3dc2) CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok) { /*- * (0) check whether the desired fragment is available * if so: * (1) copy over the fragment to s->init_buf->data[] * (2) update s->init_num */ pitem *item; hm_fragment *frag; int al; *ok = 0; item = pqueue_peek(s->d1->buffered_messages); if (item == NULL) return 0; frag = (hm_fragment *)item->data; /* Don't return if reassembly still in progress */ if (frag->reassembly != NULL) frag->msg_header.frag_len); } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: void CL_ShowIP_f(void) { Sys_ShowIP(); } Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s. CWE ID: CWE-269 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: dissect_ac_if_hdr_body(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_, proto_tree *tree, usb_conv_info_t *usb_conv_info) { gint offset_start; guint16 bcdADC; guint8 ver_major; double ver; guint8 if_in_collection, i; audio_conv_info_t *audio_conv_info; offset_start = offset; bcdADC = tvb_get_letohs(tvb, offset); ver_major = USB_AUDIO_BCD44_TO_DEC(bcdADC>>8); ver = ver_major + USB_AUDIO_BCD44_TO_DEC(bcdADC&0xFF) / 100.0; proto_tree_add_double_format_value(tree, hf_ac_if_hdr_ver, tvb, offset, 2, ver, "%2.2f", ver); audio_conv_info = (audio_conv_info_t *)usb_conv_info->class_data; if(!audio_conv_info) { audio_conv_info = wmem_new(wmem_file_scope(), audio_conv_info_t); usb_conv_info->class_data = audio_conv_info; /* XXX - set reasonable default values for all components that are not filled in by this function */ } audio_conv_info->ver_major = ver_major; offset += 2; /* version 1 refers to the Basic Audio Device specification, version 2 is the Audio Device class specification, see above */ if (ver_major==1) { proto_tree_add_item(tree, hf_ac_if_hdr_total_len, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; if_in_collection = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_ac_if_hdr_bInCollection, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; for (i=0; i<if_in_collection; i++) { proto_tree_add_item(tree, hf_ac_if_hdr_if_num, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; } } return offset-offset_start; } Commit Message: Make class "type" for USB conversations. USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match. Bug: 12356 Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209 Reviewed-on: https://code.wireshark.org/review/15212 Petri-Dish: Michael Mann <[email protected]> Reviewed-by: Martin Kaiser <[email protected]> Petri-Dish: Martin Kaiser <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Michael Mann <[email protected]> CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> optionsObjectCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.optionsObject"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(Dictionary, oo, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); if (args.Length() > 0 && !oo.isUndefinedOrNull() && !oo.isObject()) { return V8Proxy::throwTypeError("Not an object."); } if (args.Length() <= 1) { imp->optionsObject(oo); return v8::Handle<v8::Value>(); } EXCEPTION_BLOCK(Dictionary, ooo, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); if (args.Length() > 1 && !ooo.isUndefinedOrNull() && !ooo.isObject()) { return V8Proxy::throwTypeError("Not an object."); } imp->optionsObject(oo, ooo); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: static void iucv_process_message(struct sock *sk, struct sk_buff *skb, struct iucv_path *path, struct iucv_message *msg) { int rc; unsigned int len; len = iucv_msg_length(msg); /* store msg target class in the second 4 bytes of skb ctrl buffer */ /* Note: the first 4 bytes are reserved for msg tag */ memcpy(CB_TRGCLS(skb), &msg->class, CB_TRGCLS_LEN); /* check for special IPRM messages (e.g. iucv_sock_shutdown) */ if ((msg->flags & IUCV_IPRMDATA) && len > 7) { if (memcmp(msg->rmmsg, iprm_shutdown, 8) == 0) { skb->data = NULL; skb->len = 0; } } else { rc = pr_iucv->message_receive(path, msg, msg->flags & IUCV_IPRMDATA, skb->data, len, NULL); if (rc) { kfree_skb(skb); return; } /* we need to fragment iucv messages for SOCK_STREAM only; * for SOCK_SEQPACKET, it is only relevant if we support * record segmentation using MSG_EOR (see also recvmsg()) */ if (sk->sk_type == SOCK_STREAM && skb->truesize >= sk->sk_rcvbuf / 4) { rc = iucv_fragment_skb(sk, skb, len); kfree_skb(skb); skb = NULL; if (rc) { pr_iucv->path_sever(path, NULL); return; } skb = skb_dequeue(&iucv_sk(sk)->backlog_skb_q); } else { skb_reset_transport_header(skb); skb_reset_network_header(skb); skb->len = len; } } if (sock_queue_rcv_skb(sk, skb)) skb_queue_head(&iucv_sk(sk)->backlog_skb_q, skb); } Commit Message: iucv: Fix missing msg_namelen update in iucv_sock_recvmsg() The current code does not fill the msg_name member in case it is set. It also does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that by simply setting msg_namelen to 0 as obviously nobody cared about iucv_sock_recvmsg() not filling the msg_name in case it was set. Cc: Ursula Braun <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: smb2_readv_callback(struct mid_q_entry *mid) { struct cifs_readdata *rdata = mid->callback_data; struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink); struct TCP_Server_Info *server = tcon->ses->server; struct smb2_sync_hdr *shdr = (struct smb2_sync_hdr *)rdata->iov[1].iov_base; unsigned int credits_received = 1; struct smb_rqst rqst = { .rq_iov = rdata->iov, .rq_nvec = 2, .rq_pages = rdata->pages, .rq_npages = rdata->nr_pages, .rq_pagesz = rdata->pagesz, .rq_tailsz = rdata->tailsz }; cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n", __func__, mid->mid, mid->mid_state, rdata->result, rdata->bytes); switch (mid->mid_state) { case MID_RESPONSE_RECEIVED: credits_received = le16_to_cpu(shdr->CreditRequest); /* result already set, check signature */ if (server->sign) { int rc; rc = smb2_verify_signature(&rqst, server); if (rc) cifs_dbg(VFS, "SMB signature verification returned error = %d\n", rc); } /* FIXME: should this be counted toward the initiating task? */ task_io_account_read(rdata->got_bytes); cifs_stats_bytes_read(tcon, rdata->got_bytes); break; case MID_REQUEST_SUBMITTED: case MID_RETRY_NEEDED: rdata->result = -EAGAIN; if (server->sign && rdata->got_bytes) /* reset bytes number since we can not check a sign */ rdata->got_bytes = 0; /* FIXME: should this be counted toward the initiating task? */ task_io_account_read(rdata->got_bytes); cifs_stats_bytes_read(tcon, rdata->got_bytes); break; default: if (rdata->result != -ENODATA) rdata->result = -EIO; } if (rdata->result) cifs_stats_fail_inc(tcon, SMB2_READ_HE); queue_work(cifsiod_wq, &rdata->work); mutex_lock(&server->srv_mutex); DeleteMidQEntry(mid); mutex_unlock(&server->srv_mutex); add_credits(server, credits_received, 0); } Commit Message: CIFS: Enable encryption during session setup phase In order to allow encryption on SMB connection we need to exchange a session key and generate encryption and decryption keys. Signed-off-by: Pavel Shilovsky <[email protected]> CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PowerPopupView() { SetHorizontalAlignment(ALIGN_RIGHT); UpdateText(); } Commit Message: ash: Fix right-alignment of power-status text. It turns out setting ALING_RIGHT on a Label isn't enough to get proper right-aligned text. Label has to be explicitly told that it is multi-lined. BUG=none TEST=none Review URL: https://chromiumcodereview.appspot.com/9918026 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@129898 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static void cpuid_mask(u32 *word, int wordnum) { *word &= boot_cpu_data.x86_capability[wordnum]; } Commit Message: KVM: X86: Don't report L2 emulation failures to user-space This patch prevents that emulation failures which result from emulating an instruction for an L2-Guest results in being reported to userspace. Without this patch a malicious L2-Guest would be able to kill the L1 by triggering a race-condition between an vmexit and the instruction emulator. With this patch the L2 will most likely only kill itself in this situation. Signed-off-by: Joerg Roedel <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool RenderWidgetHostViewAura::HasCompositionText() { return has_composition_text_; } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { size_t ofs = CDF_GETUINT32(p, (i << 1) + 1); q = (const uint8_t *)(const void *) ((const char *)(const void *)p + ofs - 2 * sizeof(uint32_t)); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; } Commit Message: CVE-2014-0207: Prevent 0 element vectors and vectors longer than the number of properties from accessing random memory. CWE ID: CWE-119 Target: 1 Example 2: Code: AXObject* HTMLInputElement::PopupRootAXObject() { return input_type_view_->PopupRootAXObject(); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport) { struct keydata *keyptr = get_keyptr(); u32 hash[4]; /* * Pick a unique starting offset for each ephemeral port search * (saddr, daddr, dport) and 48bits of random data. */ hash[0] = (__force u32)saddr; hash[1] = (__force u32)daddr; hash[2] = (__force u32)dport ^ keyptr->secret[10]; hash[3] = keyptr->secret[11]; return half_md4_transform(hash, keyptr->secret); } Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sockaddr_llc *uaddr = (struct sockaddr_llc *)msg->msg_name; const int nonblock = flags & MSG_DONTWAIT; struct sk_buff *skb = NULL; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); unsigned long cpu_flags; size_t copied = 0; u32 peek_seq = 0; u32 *seq; unsigned long used; int target; /* Read at least this many bytes */ long timeo; msg->msg_namelen = 0; lock_sock(sk); copied = -ENOTCONN; if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN)) goto out; timeo = sock_rcvtimeo(sk, nonblock); seq = &llc->copied_seq; if (flags & MSG_PEEK) { peek_seq = llc->copied_seq; seq = &peek_seq; } target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); copied = 0; do { u32 offset; /* * We need to check signals first, to get correct SIGURG * handling. FIXME: Need to check this doesn't impact 1003.1g * and move it down to the bottom of the loop */ if (signal_pending(current)) { if (copied) break; copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; break; } /* Next get a buffer. */ skb = skb_peek(&sk->sk_receive_queue); if (skb) { offset = *seq; goto found_ok_skb; } /* Well, if we have backlog, try to process it now yet. */ if (copied >= target && !sk->sk_backlog.tail) break; if (copied) { if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo || (flags & MSG_PEEK)) break; } else { if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { copied = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) { if (!sock_flag(sk, SOCK_DONE)) { /* * This occurs when user tries to read * from never connected socket. */ copied = -ENOTCONN; break; } break; } if (!timeo) { copied = -EAGAIN; break; } } if (copied >= target) { /* Do not sleep, just process backlog. */ release_sock(sk); lock_sock(sk); } else sk_wait_data(sk, &timeo); if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) { net_dbg_ratelimited("LLC(%s:%d): Application bug, race in MSG_PEEK\n", current->comm, task_pid_nr(current)); peek_seq = llc->copied_seq; } continue; found_ok_skb: /* Ok so how much can we use? */ used = skb->len - offset; if (len < used) used = len; if (!(flags & MSG_TRUNC)) { int rc = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, used); if (rc) { /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } } *seq += used; copied += used; len -= used; /* For non stream protcols we get one packet per recvmsg call */ if (sk->sk_type != SOCK_STREAM) goto copy_uaddr; if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } /* Partial read */ if (used + offset < skb->len) continue; } while (len > 0); out: release_sock(sk); return copied; copy_uaddr: if (uaddr != NULL && skb != NULL) { memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr)); msg->msg_namelen = sizeof(*uaddr); } if (llc_sk(sk)->cmsg_flags) llc_cmsg_rcv(msg, skb); if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } goto out; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val) { switch (dr) { case 0 ... 3: vcpu->arch.db[dr] = val; if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)) vcpu->arch.eff_db[dr] = val; break; case 4: if (kvm_read_cr4_bits(vcpu, X86_CR4_DE)) return 1; /* #UD */ /* fall through */ case 6: if (val & 0xffffffff00000000ULL) return -1; /* #GP */ vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1; break; case 5: if (kvm_read_cr4_bits(vcpu, X86_CR4_DE)) return 1; /* #UD */ /* fall through */ default: /* 7 */ if (val & 0xffffffff00000000ULL) return -1; /* #GP */ vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1; kvm_update_dr7(vcpu); break; } return 0; } Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <[email protected]> Cc: [email protected] Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline struct inet_timewait_sock *tw_head(struct hlist_nulls_head *head) { return hlist_nulls_empty(head) ? NULL : list_entry(head->first, struct inet_timewait_sock, tw_node); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_FUNCTION(mcrypt_encrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190 Target: 1 Example 2: Code: GF_Err EncodeFile(char *in, GF_ISOFile *mp4, GF_SMEncodeOptions *opts, FILE *logs) { #ifdef GPAC_DISABLE_SMGR return GF_NOT_SUPPORTED; #else GF_Err e; GF_SceneLoader load; GF_SceneManager *ctx; GF_SceneGraph *sg; #ifndef GPAC_DISABLE_SCENE_STATS GF_StatManager *statsman = NULL; #endif sg = gf_sg_new(); ctx = gf_sm_new(sg); memset(&load, 0, sizeof(GF_SceneLoader)); load.fileName = in; load.ctx = ctx; load.swf_import_flags = swf_flags; load.swf_flatten_limit = swf_flatten_angle; /*since we're encoding we must get MPEG4 nodes only*/ load.flags = GF_SM_LOAD_MPEG4_STRICT; e = gf_sm_load_init(&load); if (e<0) { gf_sm_load_done(&load); fprintf(stderr, "Cannot load context %s - %s\n", in, gf_error_to_string(e)); goto err_exit; } e = gf_sm_load_run(&load); gf_sm_load_done(&load); #ifndef GPAC_DISABLE_SCENE_STATS if (opts->auto_quant) { fprintf(stderr, "Analysing Scene for Automatic Quantization\n"); statsman = gf_sm_stats_new(); e = gf_sm_stats_for_scene(statsman, ctx); if (!e) { GF_SceneStatistics *stats = gf_sm_stats_get(statsman); /*LASeR*/ if (opts->auto_quant==1) { if (opts->resolution > (s32)stats->frac_res_2d) { fprintf(stderr, " Given resolution %d is (unnecessarily) too high, using %d instead.\n", opts->resolution, stats->frac_res_2d); opts->resolution = stats->frac_res_2d; } else if (stats->int_res_2d + opts->resolution <= 0) { fprintf(stderr, " Given resolution %d is too low, using %d instead.\n", opts->resolution, stats->int_res_2d - 1); opts->resolution = 1 - stats->int_res_2d; } opts->coord_bits = stats->int_res_2d + opts->resolution; fprintf(stderr, " Coordinates & Lengths encoded using "); if (opts->resolution < 0) fprintf(stderr, "only the %d most significant bits (of %d).\n", opts->coord_bits, stats->int_res_2d); else fprintf(stderr, "a %d.%d representation\n", stats->int_res_2d, opts->resolution); fprintf(stderr, " Matrix Scale & Skew Coefficients "); if (opts->coord_bits - 8 < stats->scale_int_res_2d) { opts->scale_bits = stats->scale_int_res_2d - opts->coord_bits + 8; fprintf(stderr, "encoded using a %d.8 representation\n", stats->scale_int_res_2d); } else { opts->scale_bits = 0; fprintf(stderr, "encoded using a %d.8 representation\n", opts->coord_bits - 8); } } #ifndef GPAC_DISABLE_VRML /*BIFS*/ else if (stats->base_layer) { GF_AUContext *au; GF_CommandField *inf; M_QuantizationParameter *qp; GF_Command *com = gf_sg_command_new(ctx->scene_graph, GF_SG_GLOBAL_QUANTIZER); qp = (M_QuantizationParameter *) gf_node_new(ctx->scene_graph, TAG_MPEG4_QuantizationParameter); inf = gf_sg_command_field_new(com); inf->new_node = (GF_Node *)qp; inf->field_ptr = &inf->new_node; inf->fieldType = GF_SG_VRML_SFNODE; gf_node_register(inf->new_node, NULL); au = gf_list_get(stats->base_layer->AUs, 0); gf_list_insert(au->commands, com, 0); qp->useEfficientCoding = 1; qp->textureCoordinateQuant = 0; if ((stats->count_2f+stats->count_2d) && opts->resolution) { qp->position2DMin = stats->min_2d; qp->position2DMax = stats->max_2d; qp->position2DNbBits = opts->resolution; qp->position2DQuant = 1; } if ((stats->count_3f+stats->count_3d) && opts->resolution) { qp->position3DMin = stats->min_3d; qp->position3DMax = stats->max_3d; qp->position3DQuant = opts->resolution; qp->position3DQuant = 1; qp->textureCoordinateQuant = 1; } #if 0 if (stats->count_float && opts->resolution) { qp->scaleMin = stats->min_fixed; qp->scaleMax = stats->max_fixed; qp->scaleNbBits = 2*opts->resolution; qp->scaleQuant = 1; } #endif } #endif } } #endif /*GPAC_DISABLE_SCENE_STATS*/ if (e<0) { fprintf(stderr, "Error loading file %s\n", gf_error_to_string(e)); goto err_exit; } else { gf_log_cbk prev_logs = NULL; if (logs) { gf_log_set_tool_level(GF_LOG_CODING, GF_LOG_DEBUG); prev_logs = gf_log_set_callback(logs, scene_coding_log); } opts->src_url = in; e = gf_sm_encode_to_file(ctx, mp4, opts); if (logs) { gf_log_set_tool_level(GF_LOG_CODING, GF_LOG_ERROR); gf_log_set_callback(NULL, prev_logs); } } gf_isom_set_brand_info(mp4, GF_ISOM_BRAND_MP42, 1); gf_isom_modify_alternate_brand(mp4, GF_ISOM_BRAND_ISOM, 1); err_exit: #ifndef GPAC_DISABLE_SCENE_STATS if (statsman) gf_sm_stats_del(statsman); #endif gf_sm_del(ctx); gf_sg_del(sg); return e; #endif /*GPAC_DISABLE_SMGR*/ } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void NavigationRequest::OnStartChecksComplete( NavigationThrottle::ThrottleCheckResult result) { DCHECK(result.action() != NavigationThrottle::DEFER); DCHECK(result.action() != NavigationThrottle::BLOCK_RESPONSE); if (on_start_checks_complete_closure_) on_start_checks_complete_closure_.Run(); if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE || result.action() == NavigationThrottle::CANCEL || result.action() == NavigationThrottle::BLOCK_REQUEST || result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) { #if DCHECK_IS_ON() if (result.action() == NavigationThrottle::BLOCK_REQUEST) { DCHECK(result.net_error_code() == net::ERR_BLOCKED_BY_CLIENT || result.net_error_code() == net::ERR_BLOCKED_BY_ADMINISTRATOR); } else if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE) { DCHECK_EQ(result.net_error_code(), net::ERR_ABORTED); } #endif BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&NavigationRequest::OnRequestFailedInternal, weak_factory_.GetWeakPtr(), false, result.net_error_code(), base::nullopt, true, result.error_page_content())); return; } DCHECK_NE(AssociatedSiteInstanceType::NONE, associated_site_instance_type_); RenderFrameHostImpl* navigating_frame_host = associated_site_instance_type_ == AssociatedSiteInstanceType::SPECULATIVE ? frame_tree_node_->render_manager()->speculative_frame_host() : frame_tree_node_->current_frame_host(); DCHECK(navigating_frame_host); navigation_handle_->SetExpectedProcess(navigating_frame_host->GetProcess()); BrowserContext* browser_context = frame_tree_node_->navigator()->GetController()->GetBrowserContext(); StoragePartition* partition = BrowserContext::GetStoragePartition( browser_context, navigating_frame_host->GetSiteInstance()); DCHECK(partition); bool can_create_service_worker = (frame_tree_node_->pending_frame_policy().sandbox_flags & blink::WebSandboxFlags::kOrigin) != blink::WebSandboxFlags::kOrigin; request_params_.should_create_service_worker = can_create_service_worker; if (can_create_service_worker) { ServiceWorkerContextWrapper* service_worker_context = static_cast<ServiceWorkerContextWrapper*>( partition->GetServiceWorkerContext()); navigation_handle_->InitServiceWorkerHandle(service_worker_context); } if (IsSchemeSupportedForAppCache(common_params_.url)) { if (navigating_frame_host->GetRenderViewHost() ->GetWebkitPreferences() .application_cache_enabled) { navigation_handle_->InitAppCacheHandle( static_cast<ChromeAppCacheService*>(partition->GetAppCacheService())); } } request_params_.navigation_timing.fetch_start = base::TimeTicks::Now(); GURL base_url; #if defined(OS_ANDROID) NavigationEntry* last_committed_entry = frame_tree_node_->navigator()->GetController()->GetLastCommittedEntry(); if (last_committed_entry) base_url = last_committed_entry->GetBaseURLForDataURL(); #endif const GURL& top_document_url = !base_url.is_empty() ? base_url : frame_tree_node_->frame_tree()->root()->current_url(); const GURL& site_for_cookies = frame_tree_node_->IsMainFrame() ? common_params_.url : top_document_url; bool parent_is_main_frame = !frame_tree_node_->parent() ? false : frame_tree_node_->parent()->IsMainFrame(); std::unique_ptr<NavigationUIData> navigation_ui_data; if (navigation_handle_->GetNavigationUIData()) navigation_ui_data = navigation_handle_->GetNavigationUIData()->Clone(); bool is_for_guests_only = navigation_handle_->GetStartingSiteInstance()->GetSiteURL(). SchemeIs(kGuestScheme); bool report_raw_headers = false; RenderFrameDevToolsAgentHost::ApplyOverrides( frame_tree_node_, begin_params_.get(), &report_raw_headers); RenderFrameDevToolsAgentHost::OnNavigationRequestWillBeSent(*this); loader_ = NavigationURLLoader::Create( browser_context->GetResourceContext(), partition, std::make_unique<NavigationRequestInfo>( common_params_, begin_params_.Clone(), site_for_cookies, frame_tree_node_->IsMainFrame(), parent_is_main_frame, IsSecureFrame(frame_tree_node_->parent()), frame_tree_node_->frame_tree_node_id(), is_for_guests_only, report_raw_headers, navigating_frame_host->GetVisibilityState() == blink::mojom::PageVisibilityState::kPrerender, blob_url_loader_factory_ ? blob_url_loader_factory_->Clone() : nullptr), std::move(navigation_ui_data), navigation_handle_->service_worker_handle(), navigation_handle_->appcache_handle(), this); } Commit Message: Check ancestors when setting an <iframe> navigation's "site for cookies". Currently, we're setting the "site for cookies" only by looking at the top-level document. We ought to be verifying that the ancestor frames are same-site before doing so. We do this correctly in Blink (see `Document::SiteForCookies`), but didn't do so when navigating in the browser. This patch addresses the majority of the problem by walking the ancestor chain when processing a NavigationRequest. If all the ancestors are same-site, we set the "site for cookies" to the top-level document's URL. If they aren't all same-site, we set it to an empty URL to ensure that we don't send SameSite cookies. Bug: 833847 Change-Id: Icd77f31fa618fa9f8b59fc3b15e1bed6ee05aabd Reviewed-on: https://chromium-review.googlesource.com/1025772 Reviewed-by: Alex Moshchuk <[email protected]> Commit-Queue: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#553942} CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: safecat_color_encoding(char *buffer, size_t bufsize, size_t pos, PNG_CONST color_encoding *e, double encoding_gamma) { if (e != 0) { if (encoding_gamma != 0) pos = safecat(buffer, bufsize, pos, "("); pos = safecat(buffer, bufsize, pos, "R("); pos = safecatd(buffer, bufsize, pos, e->red.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->red.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->red.Z, 4); pos = safecat(buffer, bufsize, pos, "),G("); pos = safecatd(buffer, bufsize, pos, e->green.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->green.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->green.Z, 4); pos = safecat(buffer, bufsize, pos, "),B("); pos = safecatd(buffer, bufsize, pos, e->blue.X, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4); pos = safecat(buffer, bufsize, pos, ","); pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4); pos = safecat(buffer, bufsize, pos, ")"); if (encoding_gamma != 0) pos = safecat(buffer, bufsize, pos, ")"); } if (encoding_gamma != 0) { pos = safecat(buffer, bufsize, pos, "^"); pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5); } return pos; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: void WallpaperManagerBase::SetCommandLineForTesting( base::CommandLine* command_line) { command_line_for_testing_ = command_line; SetDefaultWallpaperPathsFromCommandLine(command_line); } Commit Message: [reland] Do not set default wallpaper unless it should do so. [email protected], [email protected] Bug: 751382 Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda Reviewed-on: https://chromium-review.googlesource.com/619754 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Alexander Alekseev <[email protected]> Reviewed-by: Biao She <[email protected]> Cr-Original-Commit-Position: refs/heads/master@{#498325} Reviewed-on: https://chromium-review.googlesource.com/646430 Cr-Commit-Position: refs/heads/master@{#498982} CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: RenderFrameImpl::CreateWorkerFetchContext() { blink::WebServiceWorkerNetworkProvider* web_provider = frame_->GetDocumentLoader()->GetServiceWorkerNetworkProvider(); DCHECK(web_provider); ServiceWorkerNetworkProvider* provider = ServiceWorkerNetworkProvider::FromWebServiceWorkerNetworkProvider( web_provider); mojom::ServiceWorkerWorkerClientRequest service_worker_client_request; mojom::ServiceWorkerContainerHostPtrInfo container_host_ptr_info; ServiceWorkerProviderContext* provider_context = provider->context(); if (provider_context) { service_worker_client_request = provider_context->CreateWorkerClientRequest(); if (ServiceWorkerUtils::IsServicificationEnabled()) container_host_ptr_info = provider_context->CloneContainerHostPtrInfo(); } std::unique_ptr<WorkerFetchContextImpl> worker_fetch_context = std::make_unique<WorkerFetchContextImpl>( std::move(service_worker_client_request), std::move(container_host_ptr_info), GetLoaderFactoryBundle()->Clone(), GetContentClient()->renderer()->CreateURLLoaderThrottleProvider( URLLoaderThrottleProviderType::kWorker)); worker_fetch_context->set_parent_frame_id(routing_id_); worker_fetch_context->set_site_for_cookies( frame_->GetDocument().SiteForCookies()); worker_fetch_context->set_is_secure_context( frame_->GetDocument().IsSecureContext()); worker_fetch_context->set_service_worker_provider_id(provider->provider_id()); worker_fetch_context->set_is_controlled_by_service_worker( provider->IsControlledByServiceWorker()); worker_fetch_context->set_origin_url( GURL(frame_->GetDocument().Url()).GetOrigin()); { SCOPED_UMA_HISTOGRAM_TIMER( "RenderFrameObservers.WillCreateWorkerFetchContext"); for (auto& observer : observers_) observer.WillCreateWorkerFetchContext(worker_fetch_context.get()); } return std::move(worker_fetch_context); } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: get_uncompressed_data(struct archive_read *a, const void **buff, size_t size, size_t minimum) { struct _7zip *zip = (struct _7zip *)a->format->data; ssize_t bytes_avail; if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) { /* Copy mode. */ /* * Note: '1' here is a performance optimization. * Recall that the decompression layer returns a count of * available bytes; asking for more than that forces the * decompressor to combine reads by copying data. */ *buff = __archive_read_ahead(a, 1, &bytes_avail); if (bytes_avail <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated 7-Zip file data"); return (ARCHIVE_FATAL); } if ((size_t)bytes_avail > zip->uncompressed_buffer_bytes_remaining) bytes_avail = (ssize_t) zip->uncompressed_buffer_bytes_remaining; if ((size_t)bytes_avail > size) bytes_avail = (ssize_t)size; zip->pack_stream_bytes_unconsumed = bytes_avail; } else if (zip->uncompressed_buffer_pointer == NULL) { /* Decompression has failed. */ archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive"); return (ARCHIVE_FATAL); } else { /* Packed mode. */ if (minimum > zip->uncompressed_buffer_bytes_remaining) { /* * If remaining uncompressed data size is less than * the minimum size, fill the buffer up to the * minimum size. */ if (extract_pack_stream(a, minimum) < 0) return (ARCHIVE_FATAL); } if (size > zip->uncompressed_buffer_bytes_remaining) bytes_avail = (ssize_t) zip->uncompressed_buffer_bytes_remaining; else bytes_avail = (ssize_t)size; *buff = zip->uncompressed_buffer_pointer; zip->uncompressed_buffer_pointer += bytes_avail; } zip->uncompressed_buffer_bytes_remaining -= bytes_avail; return (bytes_avail); } Commit Message: 7zip: fix crash when parsing certain archives Fuzzing with CRCs disabled revealed that a call to get_uncompressed_data() would sometimes fail to return at least 'minimum' bytes. This can cause the crc32() invocation in header_bytes to read off into invalid memory. A specially crafted archive can use this to cause a crash. An ASAN trace is below, but ASAN is not required - an uninstrumented binary will also crash. ==7719==ERROR: AddressSanitizer: SEGV on unknown address 0x631000040000 (pc 0x7fbdb3b3ec1d bp 0x7ffe77a51310 sp 0x7ffe77a51150 T0) ==7719==The signal is caused by a READ memory access. #0 0x7fbdb3b3ec1c in crc32_z (/lib/x86_64-linux-gnu/libz.so.1+0x2c1c) #1 0x84f5eb in header_bytes (/tmp/libarchive/bsdtar+0x84f5eb) #2 0x856156 in read_Header (/tmp/libarchive/bsdtar+0x856156) #3 0x84e134 in slurp_central_directory (/tmp/libarchive/bsdtar+0x84e134) #4 0x849690 in archive_read_format_7zip_read_header (/tmp/libarchive/bsdtar+0x849690) #5 0x5713b7 in _archive_read_next_header2 (/tmp/libarchive/bsdtar+0x5713b7) #6 0x570e63 in _archive_read_next_header (/tmp/libarchive/bsdtar+0x570e63) #7 0x6f08bd in archive_read_next_header (/tmp/libarchive/bsdtar+0x6f08bd) #8 0x52373f in read_archive (/tmp/libarchive/bsdtar+0x52373f) #9 0x5257be in tar_mode_x (/tmp/libarchive/bsdtar+0x5257be) #10 0x51daeb in main (/tmp/libarchive/bsdtar+0x51daeb) #11 0x7fbdb27cab96 in __libc_start_main /build/glibc-OTsEL5/glibc-2.27/csu/../csu/libc-start.c:310 #12 0x41dd09 in _start (/tmp/libarchive/bsdtar+0x41dd09) This was primarly done with afl and FairFuzz. Some early corpus entries may have been generated by qsym. CWE ID: CWE-125 Target: 1 Example 2: Code: _skip(conn c, int n, const char *line, int len) { /* Invert the meaning of in_job_read while throwing away data -- it * counts the bytes that remain to be thrown away. */ c->in_job = 0; c->in_job_read = n; fill_extra_data(c); if (c->in_job_read == 0) return reply(c, line, len, STATE_SENDWORD); c->reply = line; c->reply_len = len; c->reply_sent = 0; c->state = STATE_BITBUCKET; return; } Commit Message: Discard job body bytes if the job is too big. Previously, a malicious user could craft a job payload and inject beanstalk commands without the client application knowing. (An extra-careful client library could check the size of the job body before sending the put command, but most libraries do not do this, nor should they have to.) Reported by Graham Barr. CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameHostImpl::Stop() { TRACE_EVENT1("navigation", "RenderFrameHostImpl::Stop", "frame_tree_node", frame_tree_node_->frame_tree_node_id()); Send(new FrameMsg_Stop(routing_id_)); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AppControllerImpl::GetApps( mojom::AppController::GetAppsCallback callback) { std::vector<chromeos::kiosk_next_home::mojom::AppPtr> app_list; app_service_proxy_->AppRegistryCache().ForEachApp( [this, &app_list](const apps::AppUpdate& update) { app_list.push_back(CreateAppPtr(update)); }); std::move(callback).Run(std::move(app_list)); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416 Target: 1 Example 2: Code: static struct sk_buff **ip4ip6_gro_receive(struct sk_buff **head, struct sk_buff *skb) { /* Common GRO receive for SIT and IP6IP6 */ if (NAPI_GRO_CB(skb)->encap_mark) { NAPI_GRO_CB(skb)->flush = 1; return NULL; } NAPI_GRO_CB(skb)->encap_mark = 1; return inet_gro_receive(head, skb); } Commit Message: ipv6: Prevent overrun when parsing v6 header options The KASAN warning repoted below was discovered with a syzkaller program. The reproducer is basically: int s = socket(AF_INET6, SOCK_RAW, NEXTHDR_HOP); send(s, &one_byte_of_data, 1, MSG_MORE); send(s, &more_than_mtu_bytes_data, 2000, 0); The socket() call sets the nexthdr field of the v6 header to NEXTHDR_HOP, the first send call primes the payload with a non zero byte of data, and the second send call triggers the fragmentation path. The fragmentation code tries to parse the header options in order to figure out where to insert the fragment option. Since nexthdr points to an invalid option, the calculation of the size of the network header can made to be much larger than the linear section of the skb and data is read outside of it. This fix makes ip6_find_1stfrag return an error if it detects running out-of-bounds. [ 42.361487] ================================================================== [ 42.364412] BUG: KASAN: slab-out-of-bounds in ip6_fragment+0x11c8/0x3730 [ 42.365471] Read of size 840 at addr ffff88000969e798 by task ip6_fragment-oo/3789 [ 42.366469] [ 42.366696] CPU: 1 PID: 3789 Comm: ip6_fragment-oo Not tainted 4.11.0+ #41 [ 42.367628] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.1-1ubuntu1 04/01/2014 [ 42.368824] Call Trace: [ 42.369183] dump_stack+0xb3/0x10b [ 42.369664] print_address_description+0x73/0x290 [ 42.370325] kasan_report+0x252/0x370 [ 42.370839] ? ip6_fragment+0x11c8/0x3730 [ 42.371396] check_memory_region+0x13c/0x1a0 [ 42.371978] memcpy+0x23/0x50 [ 42.372395] ip6_fragment+0x11c8/0x3730 [ 42.372920] ? nf_ct_expect_unregister_notifier+0x110/0x110 [ 42.373681] ? ip6_copy_metadata+0x7f0/0x7f0 [ 42.374263] ? ip6_forward+0x2e30/0x2e30 [ 42.374803] ip6_finish_output+0x584/0x990 [ 42.375350] ip6_output+0x1b7/0x690 [ 42.375836] ? ip6_finish_output+0x990/0x990 [ 42.376411] ? ip6_fragment+0x3730/0x3730 [ 42.376968] ip6_local_out+0x95/0x160 [ 42.377471] ip6_send_skb+0xa1/0x330 [ 42.377969] ip6_push_pending_frames+0xb3/0xe0 [ 42.378589] rawv6_sendmsg+0x2051/0x2db0 [ 42.379129] ? rawv6_bind+0x8b0/0x8b0 [ 42.379633] ? _copy_from_user+0x84/0xe0 [ 42.380193] ? debug_check_no_locks_freed+0x290/0x290 [ 42.380878] ? ___sys_sendmsg+0x162/0x930 [ 42.381427] ? rcu_read_lock_sched_held+0xa3/0x120 [ 42.382074] ? sock_has_perm+0x1f6/0x290 [ 42.382614] ? ___sys_sendmsg+0x167/0x930 [ 42.383173] ? lock_downgrade+0x660/0x660 [ 42.383727] inet_sendmsg+0x123/0x500 [ 42.384226] ? inet_sendmsg+0x123/0x500 [ 42.384748] ? inet_recvmsg+0x540/0x540 [ 42.385263] sock_sendmsg+0xca/0x110 [ 42.385758] SYSC_sendto+0x217/0x380 [ 42.386249] ? SYSC_connect+0x310/0x310 [ 42.386783] ? __might_fault+0x110/0x1d0 [ 42.387324] ? lock_downgrade+0x660/0x660 [ 42.387880] ? __fget_light+0xa1/0x1f0 [ 42.388403] ? __fdget+0x18/0x20 [ 42.388851] ? sock_common_setsockopt+0x95/0xd0 [ 42.389472] ? SyS_setsockopt+0x17f/0x260 [ 42.390021] ? entry_SYSCALL_64_fastpath+0x5/0xbe [ 42.390650] SyS_sendto+0x40/0x50 [ 42.391103] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.391731] RIP: 0033:0x7fbbb711e383 [ 42.392217] RSP: 002b:00007ffff4d34f28 EFLAGS: 00000246 ORIG_RAX: 000000000000002c [ 42.393235] RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007fbbb711e383 [ 42.394195] RDX: 0000000000001000 RSI: 00007ffff4d34f60 RDI: 0000000000000003 [ 42.395145] RBP: 0000000000000046 R08: 00007ffff4d34f40 R09: 0000000000000018 [ 42.396056] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000400aad [ 42.396598] R13: 0000000000000066 R14: 00007ffff4d34ee0 R15: 00007fbbb717af00 [ 42.397257] [ 42.397411] Allocated by task 3789: [ 42.397702] save_stack_trace+0x16/0x20 [ 42.398005] save_stack+0x46/0xd0 [ 42.398267] kasan_kmalloc+0xad/0xe0 [ 42.398548] kasan_slab_alloc+0x12/0x20 [ 42.398848] __kmalloc_node_track_caller+0xcb/0x380 [ 42.399224] __kmalloc_reserve.isra.32+0x41/0xe0 [ 42.399654] __alloc_skb+0xf8/0x580 [ 42.400003] sock_wmalloc+0xab/0xf0 [ 42.400346] __ip6_append_data.isra.41+0x2472/0x33d0 [ 42.400813] ip6_append_data+0x1a8/0x2f0 [ 42.401122] rawv6_sendmsg+0x11ee/0x2db0 [ 42.401505] inet_sendmsg+0x123/0x500 [ 42.401860] sock_sendmsg+0xca/0x110 [ 42.402209] ___sys_sendmsg+0x7cb/0x930 [ 42.402582] __sys_sendmsg+0xd9/0x190 [ 42.402941] SyS_sendmsg+0x2d/0x50 [ 42.403273] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.403718] [ 42.403871] Freed by task 1794: [ 42.404146] save_stack_trace+0x16/0x20 [ 42.404515] save_stack+0x46/0xd0 [ 42.404827] kasan_slab_free+0x72/0xc0 [ 42.405167] kfree+0xe8/0x2b0 [ 42.405462] skb_free_head+0x74/0xb0 [ 42.405806] skb_release_data+0x30e/0x3a0 [ 42.406198] skb_release_all+0x4a/0x60 [ 42.406563] consume_skb+0x113/0x2e0 [ 42.406910] skb_free_datagram+0x1a/0xe0 [ 42.407288] netlink_recvmsg+0x60d/0xe40 [ 42.407667] sock_recvmsg+0xd7/0x110 [ 42.408022] ___sys_recvmsg+0x25c/0x580 [ 42.408395] __sys_recvmsg+0xd6/0x190 [ 42.408753] SyS_recvmsg+0x2d/0x50 [ 42.409086] entry_SYSCALL_64_fastpath+0x1f/0xbe [ 42.409513] [ 42.409665] The buggy address belongs to the object at ffff88000969e780 [ 42.409665] which belongs to the cache kmalloc-512 of size 512 [ 42.410846] The buggy address is located 24 bytes inside of [ 42.410846] 512-byte region [ffff88000969e780, ffff88000969e980) [ 42.411941] The buggy address belongs to the page: [ 42.412405] page:ffffea000025a780 count:1 mapcount:0 mapping: (null) index:0x0 compound_mapcount: 0 [ 42.413298] flags: 0x100000000008100(slab|head) [ 42.413729] raw: 0100000000008100 0000000000000000 0000000000000000 00000001800c000c [ 42.414387] raw: ffffea00002a9500 0000000900000007 ffff88000c401280 0000000000000000 [ 42.415074] page dumped because: kasan: bad access detected [ 42.415604] [ 42.415757] Memory state around the buggy address: [ 42.416222] ffff88000969e880: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 42.416904] ffff88000969e900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 [ 42.417591] >ffff88000969e980: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc [ 42.418273] ^ [ 42.418588] ffff88000969ea00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [ 42.419273] ffff88000969ea80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [ 42.419882] ================================================================== Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Craig Gallek <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static __always_inline int __do_follow_link(struct path *path, struct nameidata *nd) { int error; void *cookie; struct dentry *dentry = path->dentry; touch_atime(path->mnt, dentry); nd_set_link(nd, NULL); if (path->mnt != nd->path.mnt) { path_to_nameidata(path, nd); dget(dentry); } mntget(path->mnt); cookie = dentry->d_inode->i_op->follow_link(dentry, nd); error = PTR_ERR(cookie); if (!IS_ERR(cookie)) { char *s = nd_get_link(nd); error = 0; if (s) error = __vfs_follow_link(nd, s); else if (nd->last_type == LAST_BIND) { error = force_reval_path(&nd->path, nd); if (error) path_put(&nd->path); } if (dentry->d_inode->i_op->put_link) dentry->d_inode->i_op->put_link(dentry, nd, cookie); } return error; } Commit Message: fix autofs/afs/etc. magic mountpoint breakage We end up trying to kfree() nd.last.name on open("/mnt/tmp", O_CREAT) if /mnt/tmp is an autofs direct mount. The reason is that nd.last_type is bogus here; we want LAST_BIND for everything of that kind and we get LAST_NORM left over from finding parent directory. So make sure that it *is* set properly; set to LAST_BIND before doing ->follow_link() - for normal symlinks it will be changed by __vfs_follow_link() and everything else needs it set that way. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) { sapi_header_struct sapi_header; char *colon_offset; char *header_line; uint header_line_len; int http_response_code; if (SG(headers_sent) && !SG(request_info).no_headers) { const char *output_start_filename = php_output_get_start_filename(TSRMLS_C); int output_start_lineno = php_output_get_start_lineno(TSRMLS_C); if (output_start_filename) { sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent by (output started at %s:%d)", output_start_filename, output_start_lineno); } else { sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent"); } return FAILURE; } switch (op) { case SAPI_HEADER_SET_STATUS: sapi_update_response_code((int)(zend_intptr_t) arg TSRMLS_CC); return SUCCESS; case SAPI_HEADER_ADD: case SAPI_HEADER_REPLACE: case SAPI_HEADER_DELETE: { sapi_header_line *p = arg; if (!p->line || !p->line_len) { return FAILURE; } header_line = p->line; header_line_len = p->line_len; http_response_code = p->response_code; break; } case SAPI_HEADER_DELETE_ALL: if (sapi_module.header_handler) { sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); } zend_llist_clean(&SG(sapi_headers).headers); return SUCCESS; default: return FAILURE; } header_line = estrndup(header_line, header_line_len); /* cut off trailing spaces, linefeeds and carriage-returns */ if (header_line_len && isspace(header_line[header_line_len-1])) { do { header_line_len--; } while(header_line_len && isspace(header_line[header_line_len-1])); header_line[header_line_len]='\0'; } if (op == SAPI_HEADER_DELETE) { if (strchr(header_line, ':')) { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header to delete may not contain colon."); return FAILURE; } if (sapi_module.header_handler) { sapi_header.header = header_line; sapi_header.header_len = header_line_len; sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); } sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len); efree(header_line); return SUCCESS; } else { /* new line/NUL character safety check */ int i; for (i = 0; i < header_line_len; i++) { /* RFC 2616 allows new lines if followed by SP or HT */ int illegal_break = (header_line[i+1] != ' ' && header_line[i+1] != '\t') && ( header_line[i] == '\n' || (header_line[i] == '\r' && header_line[i+1] != '\n')); if (illegal_break) { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header may not contain " "more than a single header, new line detected"); return FAILURE; } if (header_line[i] == '\0') { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header may not contain NUL bytes"); return FAILURE; } } } sapi_header.header = header_line; sapi_header.header_len = header_line_len; /* Check the header for a few cases that we have special support for in SAPI */ if (header_line_len>=5 && !strncasecmp(header_line, "HTTP/", 5)) { /* filter out the response code */ sapi_update_response_code(sapi_extract_response_code(header_line) TSRMLS_CC); /* sapi_update_response_code doesn't free the status line if the code didn't change */ if (SG(sapi_headers).http_status_line) { efree(SG(sapi_headers).http_status_line); } SG(sapi_headers).http_status_line = header_line; return SUCCESS; } else { colon_offset = strchr(header_line, ':'); if (colon_offset) { *colon_offset = 0; if (!STRCASECMP(header_line, "Content-Type")) { char *ptr = colon_offset+1, *mimetype = NULL, *newheader; size_t len = header_line_len - (ptr - header_line), newlen; while (*ptr == ' ') { ptr++; len--; } /* Disable possible output compression for images */ if (!strncmp(ptr, "image/", sizeof("image/")-1)) { zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"), "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); } mimetype = estrdup(ptr); newlen = sapi_apply_default_charset(&mimetype, len TSRMLS_CC); if (!SG(sapi_headers).mimetype){ SG(sapi_headers).mimetype = estrdup(mimetype); } if (newlen != 0) { newlen += sizeof("Content-type: "); newheader = emalloc(newlen); PHP_STRLCPY(newheader, "Content-type: ", newlen, sizeof("Content-type: ")-1); strlcat(newheader, mimetype, newlen); sapi_header.header = newheader; sapi_header.header_len = newlen - 1; efree(header_line); } efree(mimetype); SG(sapi_headers).send_default_content_type = 0; } else if (!STRCASECMP(header_line, "Content-Length")) { /* Script is setting Content-length. The script cannot reasonably * know the size of the message body after compression, so it's best * do disable compression altogether. This contributes to making scripts * portable between setups that have and don't have zlib compression * enabled globally. See req #44164 */ zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"), "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); } else if (!STRCASECMP(header_line, "Location")) { if ((SG(sapi_headers).http_response_code < 300 || SG(sapi_headers).http_response_code > 399) && SG(sapi_headers).http_response_code != 201) { /* Return a Found Redirect if one is not already specified */ if (http_response_code) { /* user specified redirect code */ sapi_update_response_code(http_response_code TSRMLS_CC); } else if (SG(request_info).proto_num > 1000 && SG(request_info).request_method && strcmp(SG(request_info).request_method, "HEAD") && strcmp(SG(request_info).request_method, "GET")) { sapi_update_response_code(303 TSRMLS_CC); } else { sapi_update_response_code(302 TSRMLS_CC); } } } else if (!STRCASECMP(header_line, "WWW-Authenticate")) { /* HTTP Authentication */ sapi_update_response_code(401 TSRMLS_CC); /* authentication-required */ } if (sapi_header.header==header_line) { *colon_offset = ':'; } } } if (http_response_code) { sapi_update_response_code(http_response_code TSRMLS_CC); } sapi_header_add_op(op, &sapi_header TSRMLS_CC); return SUCCESS; } Commit Message: Update header handling to RFC 7230 CWE ID: CWE-79 Target: 1 Example 2: Code: bool Extension::IsElevatedHostList( const URLPatternList& old_list, const URLPatternList& new_list) { std::vector<std::string> new_hosts = GetDistinctHosts(new_list, false); std::vector<std::string> old_hosts = GetDistinctHosts(old_list, false); std::set<std::string> old_hosts_set(old_hosts.begin(), old_hosts.end()); std::set<std::string> new_hosts_set(new_hosts.begin(), new_hosts.end()); std::set<std::string> new_hosts_only; std::set_difference(new_hosts_set.begin(), new_hosts_set.end(), old_hosts_set.begin(), old_hosts_set.end(), std::inserter(new_hosts_only, new_hosts_only.begin())); return !new_hosts_only.empty(); } Commit Message: Prevent extensions from defining homepages with schemes other than valid web extents. BUG=84402 TEST=ExtensionManifestTest.ParseHomepageURLs Review URL: http://codereview.chromium.org/7089014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87722 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: gfx::Size RootWindowHost::GetNativeScreenSize() { ::Display* xdisplay = base::MessagePumpX::GetDefaultXDisplay(); return gfx::Size(DisplayWidth(xdisplay, 0), DisplayHeight(xdisplay, 0)); } Commit Message: Introduce XGetImage() for GrabWindowSnapshot() in ChromeOS. BUG=119492 TEST=manually done Review URL: https://chromiumcodereview.appspot.com/10386124 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137556 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity, char immediate_load) { static const int intoffset[] = { 0, 4, 2, 1 }; static const int intjump[] = { 8, 8, 4, 2 }; int rc; DATA32 *ptr; GifFileType *gif; GifRowType *rows; GifRecordType rec; ColorMapObject *cmap; int i, j, done, bg, r, g, b, w = 0, h = 0; float per = 0.0, per_inc; int last_per = 0, last_y = 0; int transp; int fd; done = 0; rows = NULL; transp = -1; /* if immediate_load is 1, then dont delay image laoding as below, or */ /* already data in this image - dont load it again */ if (im->data) return 0; fd = open(im->real_file, O_RDONLY); if (fd < 0) return 0; #if GIFLIB_MAJOR >= 5 gif = DGifOpenFileHandle(fd, NULL); #else gif = DGifOpenFileHandle(fd); #endif if (!gif) { close(fd); return 0; } rc = 0; /* Failure */ do { if (DGifGetRecordType(gif, &rec) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; } if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done)) { if (DGifGetImageDesc(gif) == GIF_ERROR) { /* PrintGifError(); */ rec = TERMINATE_RECORD_TYPE; break; } w = gif->Image.Width; h = gif->Image.Height; if (!IMAGE_DIMENSIONS_OK(w, h)) goto quit2; rows = calloc(h, sizeof(GifRowType *)); if (!rows) goto quit2; for (i = 0; i < h; i++) { rows[i] = calloc(w, sizeof(GifPixelType)); if (!rows[i]) goto quit; } if (gif->Image.Interlace) { for (i = 0; i < 4; i++) { for (j = intoffset[i]; j < h; j += intjump[i]) { DGifGetLine(gif, rows[j], w); } } } else { for (i = 0; i < h; i++) { DGifGetLine(gif, rows[i], w); } } done = 1; } else if (rec == EXTENSION_RECORD_TYPE) { int ext_code; GifByteType *ext; ext = NULL; DGifGetExtension(gif, &ext_code, &ext); while (ext) { if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0)) { transp = (int)ext[4]; } ext = NULL; DGifGetExtensionNext(gif, &ext); } } } while (rec != TERMINATE_RECORD_TYPE); if (transp >= 0) { SET_FLAG(im->flags, F_HAS_ALPHA); } else { UNSET_FLAG(im->flags, F_HAS_ALPHA); } if (!rows) { goto quit2; } /* set the format string member to the lower-case full extension */ /* name for the format - so example names would be: */ /* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */ im->w = w; im->h = h; if (!im->format) im->format = strdup("gif"); if (im->loader || immediate_load || progress) { bg = gif->SBackGroundColor; cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap); im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h); if (!im->data) goto quit; { r = cmap->Colors[bg].Red; g = cmap->Colors[bg].Green; b = cmap->Colors[bg].Blue; *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; { for (j = 0; j < w; j++) { if (rows[i][j] == transp) { r = cmap->Colors[bg].Red; g = cmap->Colors[bg].Green; b = cmap->Colors[bg].Blue; *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; } per += per_inc; if (progress && (((int)per) != last_per) && (((int)per) % progress_granularity == 0)) { rc = 2; goto quit; } last_y = i; } } } finish: if (progress) progress(im, 100, 0, last_y, w, h); } rc = 1; /* Success */ quit: for (i = 0; i < h; i++) free(rows[i]); free(rows); quit2: #if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1) DGifCloseFile(gif, NULL); #else DGifCloseFile(gif); #endif return rc; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: bool LayerTreeHostQt::showRepaintCounter(const WebCore::GraphicsLayer*) const { return m_webPage->corePage()->settings()->showRepaintCounter(); } Commit Message: [Qt][WK2] Allow transparent WebViews https://bugs.webkit.org/show_bug.cgi?id=80608 Reviewed by Tor Arne Vestbø. Added support for transparentBackground in QQuickWebViewExperimental. This uses the existing drawsTransparentBackground property in WebKit2. Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes, otherwise the change doesn't take effect. A new API test was added. * UIProcess/API/qt/qquickwebview.cpp: (QQuickWebViewPrivate::setTransparentBackground): (QQuickWebViewPrivate::transparentBackground): (QQuickWebViewExperimental::transparentBackground): (QQuickWebViewExperimental::setTransparentBackground): * UIProcess/API/qt/qquickwebview_p.h: * UIProcess/API/qt/qquickwebview_p_p.h: (QQuickWebViewPrivate): * UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp: (tst_QQuickWebView): (tst_QQuickWebView::transparentWebViews): * WebProcess/WebPage/qt/LayerTreeHostQt.cpp: (WebKit::LayerTreeHostQt::LayerTreeHostQt): (WebKit::LayerTreeHostQt::setRootCompositingLayer): git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void Register(const GURL& url, const base::FilePath& root_http, ReportResponseHeadersOnUI report_on_ui) { EXPECT_TRUE( content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); base::FilePath file_path(root_http); file_path = file_path.AppendASCII(url.scheme() + "." + url.host() + ".html"); net::URLRequestFilter::GetInstance()->AddUrlInterceptor( url, base::WrapUnique( new MirrorMockJobInterceptor(file_path, report_on_ui))); } Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <[email protected]> Reviewed-by: Ramin Halavati <[email protected]> Reviewed-by: Maks Orlovich <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#607652} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static NTSTATUS fd_open_atomic(struct connection_struct *conn, files_struct *fsp, int flags, mode_t mode, bool *file_created) { NTSTATUS status = NT_STATUS_UNSUCCESSFUL; bool file_existed = VALID_STAT(fsp->fsp_name->st); *file_created = false; * We're not creating the file, just pass through. */ return fd_open(conn, fsp, flags, mode); } Commit Message: CWE ID: CWE-835 Target: 1 Example 2: Code: static __always_inline u32 vmcs_read32(unsigned long field) { vmcs_check32(field); return __vmcs_readl(field); } Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF) When L2 exits to L0 due to "exception or NMI", software exceptions (#BP and #OF) for which L1 has requested an intercept should be handled by L1 rather than L0. Previously, only hardware exceptions were forwarded to L1. Signed-off-by: Jim Mattson <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-388 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk; if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize); prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (eptr - cptr >= dff_chunk_header.ckDataSize) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } Commit Message: issue #33, sanitize size of unknown chunks before malloc() CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: testing::AssertionResult ScriptAllowedExclusivelyOnTab( const Extension* extension, const std::set<GURL>& allowed_urls, int tab_id) { std::vector<std::string> errors; for (const GURL& url : urls_) { bool allowed = IsAllowedScript(extension, url, tab_id); if (allowed && !allowed_urls.count(url)) errors.push_back("Script unexpectedly disallowed on " + url.spec()); else if (!allowed && allowed_urls.count(url)) errors.push_back("Script unexpectedly allowed on " + url.spec()); } if (!errors.empty()) return testing::AssertionFailure() << base::JoinString(errors, "\n"); return testing::AssertionSuccess(); } Commit Message: [Extensions] Restrict tabs.captureVisibleTab() Modify the permissions for tabs.captureVisibleTab(). Instead of just checking for <all_urls> and assuming its safe, do the following: - If the page is a "normal" web page (e.g., http/https), allow the capture if the extension has activeTab granted or <all_urls>. - If the page is a file page (file:///), allow the capture if the extension has file access *and* either of the <all_urls> or activeTab permissions. - If the page is a chrome:// page, allow the capture only if the extension has activeTab granted. Bug: 810220 Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304 Reviewed-on: https://chromium-review.googlesource.com/981195 Commit-Queue: Devlin <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Cr-Commit-Position: refs/heads/master@{#548891} CWE ID: CWE-20 Target: 1 Example 2: Code: static void scsi_dma_restart_bh(void *opaque) { SCSIDiskState *s = opaque; SCSIRequest *req; SCSIDiskReq *r; qemu_bh_delete(s->bh); s->bh = NULL; QTAILQ_FOREACH(req, &s->qdev.requests, next) { r = DO_UPCAST(SCSIDiskReq, req, req); if (r->status & SCSI_REQ_STATUS_RETRY) { int status = r->status; int ret; r->status &= ~(SCSI_REQ_STATUS_RETRY | SCSI_REQ_STATUS_RETRY_TYPE_MASK); switch (status & SCSI_REQ_STATUS_RETRY_TYPE_MASK) { case SCSI_REQ_STATUS_RETRY_READ: scsi_read_data(&r->req); break; case SCSI_REQ_STATUS_RETRY_WRITE: scsi_write_data(&r->req); break; case SCSI_REQ_STATUS_RETRY_FLUSH: ret = scsi_disk_emulate_command(r, r->iov.iov_base); if (ret == 0) { scsi_req_complete(&r->req, GOOD); } } } } } Commit Message: scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ResetObserverCounts() { token_available_count_ = 0; token_revoked_count_ = 0; tokens_loaded_count_ = 0; start_batch_changes_ = 0; end_batch_changes_ = 0; auth_error_changed_count_ = 0; } Commit Message: [signin] Add metrics to track the source for refresh token updated events This CL add a source for update and revoke credentials operations. It then surfaces the source in the chrome://signin-internals page. This CL also records the following histograms that track refresh token events: * Signin.RefreshTokenUpdated.ToValidToken.Source * Signin.RefreshTokenUpdated.ToInvalidToken.Source * Signin.RefreshTokenRevoked.Source These histograms are needed to validate the assumptions of how often tokens are revoked by the browser and the sources for the token revocations. Bug: 896182 Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90 Reviewed-on: https://chromium-review.googlesource.com/c/1286464 Reviewed-by: Jochen Eisinger <[email protected]> Reviewed-by: David Roger <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Commit-Queue: Mihai Sardarescu <[email protected]> Cr-Commit-Position: refs/heads/master@{#606181} CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: const Cues* Segment::GetCues() const { return m_pCues; } 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 Target: 1 Example 2: Code: static void WriteDDSInfo(Image *image, const size_t pixelFormat, const size_t compression, const size_t mipmaps) { char software[MaxTextExtent]; register ssize_t i; unsigned int format, caps, flags; flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT); caps=(unsigned int) DDSCAPS_TEXTURE; format=(unsigned int) pixelFormat; if (format == DDPF_FOURCC) flags=flags | DDSD_LINEARSIZE; else flags=flags | DDSD_PITCH; if (mipmaps > 0) { flags=flags | (unsigned int) DDSD_MIPMAPCOUNT; caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX); } if (format != DDPF_FOURCC && image->matte) format=format | DDPF_ALPHAPIXELS; (void) WriteBlob(image,4,(unsigned char *) "DDS "); (void) WriteBlobLSBLong(image,124); (void) WriteBlobLSBLong(image,flags); (void) WriteBlobLSBLong(image,(unsigned int) image->rows); (void) WriteBlobLSBLong(image,(unsigned int) image->columns); if (pixelFormat == DDPF_FOURCC) { /* Compressed DDS requires linear compressed size of first image */ if (compression == FOURCC_DXT1) (void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1, (image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*8)); else /* DXT5 */ (void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1, (image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*16)); } else { /* Uncompressed DDS requires byte pitch of first image */ if (image->matte != MagickFalse) (void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 4)); else (void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 3)); } (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1); (void) ResetMagickMemory(software,0,sizeof(software)); (void) CopyMagickString(software,"IMAGEMAGICK",MaxTextExtent); (void) WriteBlob(image,44,(unsigned char *) software); (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,format); if (pixelFormat == DDPF_FOURCC) { (void) WriteBlobLSBLong(image,(unsigned int) compression); for(i=0;i < 5;i++) // bitcount / masks (void) WriteBlobLSBLong(image,0x00); } else { (void) WriteBlobLSBLong(image,0x00); if (image->matte != MagickFalse) { (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0xff000000); } else { (void) WriteBlobLSBLong(image,24); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0x00); } } (void) WriteBlobLSBLong(image,caps); for(i=0;i < 4;i++) // ddscaps2 + reserved region (void) WriteBlobLSBLong(image,0x00); } Commit Message: Added check to prevent image being 0x0 (reported in #489). CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int rds_ib_laddr_check(__be32 addr) { int ret; struct rdma_cm_id *cm_id; struct sockaddr_in sin; /* Create a CMA ID and try to bind it. This catches both * IB and iWARP capable NICs. */ cm_id = rdma_create_id(NULL, NULL, RDMA_PS_TCP, IB_QPT_RC); if (IS_ERR(cm_id)) return PTR_ERR(cm_id); memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = addr; /* rdma_bind_addr will only succeed for IB & iWARP devices */ ret = rdma_bind_addr(cm_id, (struct sockaddr *)&sin); /* due to this, we will claim to support iWARP devices unless we check node_type. */ if (ret || cm_id->device->node_type != RDMA_NODE_IB_CA) ret = -EADDRNOTAVAIL; rdsdebug("addr %pI4 ret %d node type %d\n", &addr, ret, cm_id->device ? cm_id->device->node_type : -1); rdma_destroy_id(cm_id); return ret; } Commit Message: rds: prevent dereference of a NULL device Binding might result in a NULL device, which is dereferenced causing this BUG: [ 1317.260548] BUG: unable to handle kernel NULL pointer dereference at 000000000000097 4 [ 1317.261847] IP: [<ffffffff84225f52>] rds_ib_laddr_check+0x82/0x110 [ 1317.263315] PGD 418bcb067 PUD 3ceb21067 PMD 0 [ 1317.263502] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC [ 1317.264179] Dumping ftrace buffer: [ 1317.264774] (ftrace buffer empty) [ 1317.265220] Modules linked in: [ 1317.265824] CPU: 4 PID: 836 Comm: trinity-child46 Tainted: G W 3.13.0-rc4- next-20131218-sasha-00013-g2cebb9b-dirty #4159 [ 1317.267415] task: ffff8803ddf33000 ti: ffff8803cd31a000 task.ti: ffff8803cd31a000 [ 1317.268399] RIP: 0010:[<ffffffff84225f52>] [<ffffffff84225f52>] rds_ib_laddr_check+ 0x82/0x110 [ 1317.269670] RSP: 0000:ffff8803cd31bdf8 EFLAGS: 00010246 [ 1317.270230] RAX: 0000000000000000 RBX: ffff88020b0dd388 RCX: 0000000000000000 [ 1317.270230] RDX: ffffffff8439822e RSI: 00000000000c000a RDI: 0000000000000286 [ 1317.270230] RBP: ffff8803cd31be38 R08: 0000000000000000 R09: 0000000000000000 [ 1317.270230] R10: 0000000000000000 R11: 0000000000000001 R12: 0000000000000000 [ 1317.270230] R13: 0000000054086700 R14: 0000000000a25de0 R15: 0000000000000031 [ 1317.270230] FS: 00007ff40251d700(0000) GS:ffff88022e200000(0000) knlGS:000000000000 0000 [ 1317.270230] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b [ 1317.270230] CR2: 0000000000000974 CR3: 00000003cd478000 CR4: 00000000000006e0 [ 1317.270230] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 [ 1317.270230] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000090602 [ 1317.270230] Stack: [ 1317.270230] 0000000054086700 5408670000a25de0 5408670000000002 0000000000000000 [ 1317.270230] ffffffff84223542 00000000ea54c767 0000000000000000 ffffffff86d26160 [ 1317.270230] ffff8803cd31be68 ffffffff84223556 ffff8803cd31beb8 ffff8800c6765280 [ 1317.270230] Call Trace: [ 1317.270230] [<ffffffff84223542>] ? rds_trans_get_preferred+0x42/0xa0 [ 1317.270230] [<ffffffff84223556>] rds_trans_get_preferred+0x56/0xa0 [ 1317.270230] [<ffffffff8421c9c3>] rds_bind+0x73/0xf0 [ 1317.270230] [<ffffffff83e4ce62>] SYSC_bind+0x92/0xf0 [ 1317.270230] [<ffffffff812493f8>] ? context_tracking_user_exit+0xb8/0x1d0 [ 1317.270230] [<ffffffff8119313d>] ? trace_hardirqs_on+0xd/0x10 [ 1317.270230] [<ffffffff8107a852>] ? syscall_trace_enter+0x32/0x290 [ 1317.270230] [<ffffffff83e4cece>] SyS_bind+0xe/0x10 [ 1317.270230] [<ffffffff843a6ad0>] tracesys+0xdd/0xe2 [ 1317.270230] Code: 00 8b 45 cc 48 8d 75 d0 48 c7 45 d8 00 00 00 00 66 c7 45 d0 02 00 89 45 d4 48 89 df e8 78 49 76 ff 41 89 c4 85 c0 75 0c 48 8b 03 <80> b8 74 09 00 00 01 7 4 06 41 bc 9d ff ff ff f6 05 2a b6 c2 02 [ 1317.270230] RIP [<ffffffff84225f52>] rds_ib_laddr_check+0x82/0x110 [ 1317.270230] RSP <ffff8803cd31bdf8> [ 1317.270230] CR2: 0000000000000974 Signed-off-by: Sasha Levin <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ChildThread::Shutdown() { file_system_dispatcher_.reset(); quota_dispatcher_.reset(); } Commit Message: [FileAPI] Clean up WebFileSystemImpl before Blink shutdown WebFileSystemImpl should not outlive V8 instance, since it may have references to V8. This CL ensures it deleted before Blink shutdown. BUG=369525 Review URL: https://codereview.chromium.org/270633009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@269345 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_coc_t *coc = &ms->parms.coc; fprintf(out, "compno = %"PRIuFAST16"; csty = 0x%02x; numdlvls = %d;\n", coc->compno, coc->compparms.csty, coc->compparms.numdlvls); fprintf(out, "cblkwidthval = %d; cblkheightval = %d; " "cblksty = 0x%02x; qmfbid = %d;\n", coc->compparms.cblkwidthval, coc->compparms.cblkheightval, coc->compparms.cblksty, coc->compparms.qmfbid); return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static MagickBooleanType PingGIFImage(Image *image,ExceptionInfo *exception) { unsigned char buffer[256], length, data_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (ReadBlob(image,1,&data_size) != 1) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); if (data_size > MaximumLZWBits) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); if (ReadBlob(image,1,&length) != 1) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); while (length != 0) { if (ReadBlob(image,length,buffer) != (ssize_t) length) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); if (ReadBlob(image,1,&length) != 1) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); } return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/592 CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WebsiteSettings* website_settings() { if (!website_settings_.get()) { website_settings_.reset(new WebsiteSettings( mock_ui(), profile(), tab_specific_content_settings(), infobar_service(), url(), ssl(), cert_store())); } return website_settings_.get(); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID: Target: 1 Example 2: Code: void TestingAutomationProvider::LoginAsGuest(DictionaryValue* args, IPC::Message* reply_message) { chromeos::ExistingUserController* controller = chromeos::ExistingUserController::current_controller(); AutomationJSONReply(this, reply_message).SendSuccess(NULL); controller->LoginAsGuest(); } Commit Message: chromeos: Move audio, power, and UI files into subdirs. This moves more files from chrome/browser/chromeos/ into subdirectories. BUG=chromium-os:22896 TEST=did chrome os builds both with and without aura TBR=sky Review URL: http://codereview.chromium.org/9125006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CSSDefaultStyleSheets::loadSimpleDefaultStyle() { ASSERT(!defaultStyle); ASSERT(!simpleDefaultStyleSheet); defaultStyle = RuleSet::create().leakPtr(); defaultPrintStyle = defaultStyle; defaultQuirksStyle = RuleSet::create().leakPtr(); simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet)); defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval()); defaultStyle->addRulesFromSheet(parseUASheet(ViewportStyle::viewportStyleSheet()), screenEval()); } Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun. We've been bitten by the Simple Default Stylesheet being out of sync with the real html.css twice this week. The Simple Default Stylesheet was invented years ago for Mac: http://trac.webkit.org/changeset/36135 It nicely handles the case where you just want to create a single WebView and parse some simple HTML either without styling said HTML, or only to display a small string, etc. Note that this optimization/complexity *only* helps for the very first document, since the default stylesheets are all static (process-global) variables. Since any real page on the internet uses a tag not covered by the simple default stylesheet, not real load benefits from this optimization. Only uses of WebView which were just rendering small bits of text might have benefited from this. about:blank would also have used this sheet. This was a common application for some uses of WebView back in those days. These days, even with WebView on Android, there are likely much larger overheads than parsing the html.css stylesheet, so making it required seems like the right tradeoff of code-simplicity for this case. BUG=319556 Review URL: https://codereview.chromium.org/73723005 git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: DidFinishNavigation(NavigationHandle* handle) { if (handle->GetFrameTreeNodeId() != frame_tree_node_id_) return; if (!handle->HasCommitted()) return; if (handle->GetRenderFrameHost()->GetSiteInstance() != parent_site_instance_) return; if (!handle->GetURL().IsAboutBlank()) return; if (!handle->GetRenderFrameHost()->PrepareForInnerWebContentsAttach()) { filter_->ResumeAttachOrDestroy(element_instance_id_, MSG_ROUTING_NONE /* no plugin frame */); } base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&ExtensionsGuestViewMessageFilter::ResumeAttachOrDestroy, filter_, element_instance_id_, handle->GetRenderFrameHost()->GetRoutingID())); } Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362 Target: 1 Example 2: Code: static void kvp_get_ipconfig_info(char *if_name, struct hv_kvp_ipaddr_value *buffer) { char cmd[512]; char dhcp_info[128]; char *p; FILE *file; /* * Get the address of default gateway (ipv4). */ sprintf(cmd, "%s %s", "ip route show dev", if_name); strcat(cmd, " | awk '/default/ {print $3 }'"); /* * Execute the command to gather gateway info. */ kvp_process_ipconfig_file(cmd, (char *)buffer->gate_way, (MAX_GATEWAY_SIZE * 2), INET_ADDRSTRLEN, 0); /* * Get the address of default gateway (ipv6). */ sprintf(cmd, "%s %s", "ip -f inet6 route show dev", if_name); strcat(cmd, " | awk '/default/ {print $3 }'"); /* * Execute the command to gather gateway info (ipv6). */ kvp_process_ipconfig_file(cmd, (char *)buffer->gate_way, (MAX_GATEWAY_SIZE * 2), INET6_ADDRSTRLEN, 1); /* * Gather the DNS state. * Since there is no standard way to get this information * across various distributions of interest; we just invoke * an external script that needs to be ported across distros * of interest. * * Following is the expected format of the information from the script: * * ipaddr1 (nameserver1) * ipaddr2 (nameserver2) * . * . */ sprintf(cmd, "%s", "hv_get_dns_info"); /* * Execute the command to gather DNS info. */ kvp_process_ipconfig_file(cmd, (char *)buffer->dns_addr, (MAX_IP_ADDR_SIZE * 2), INET_ADDRSTRLEN, 0); /* * Gather the DHCP state. * We will gather this state by invoking an external script. * The parameter to the script is the interface name. * Here is the expected output: * * Enabled: DHCP enabled. */ sprintf(cmd, "%s %s", "hv_get_dhcp_info", if_name); file = popen(cmd, "r"); if (file == NULL) return; p = fgets(dhcp_info, sizeof(dhcp_info), file); if (p == NULL) { pclose(file); return; } if (!strncmp(p, "Enabled", 7)) buffer->dhcp_enabled = 1; else buffer->dhcp_enabled = 0; pclose(file); } Commit Message: tools: hv: Netlink source address validation allows DoS The source code without this patch caused hypervkvpd to exit when it processed a spoofed Netlink packet which has been sent from an untrusted local user. Now Netlink messages with a non-zero nl_pid source address are ignored and a warning is printed into the syslog. Signed-off-by: Tomas Hozza <[email protected]> Acked-by: K. Y. Srinivasan <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ExtensionsGuestViewMessageFilter::ResumeAttachOrDestroy( int32_t element_instance_id, int32_t plugin_frame_routing_id) { auto it = frame_navigation_helpers_.find(element_instance_id); if (it == frame_navigation_helpers_.end()) { return; } auto* plugin_rfh = content::RenderFrameHost::FromID(render_process_id_, plugin_frame_routing_id); auto* helper = it->second.get(); auto* guest_view = helper->GetGuestView(); if (!guest_view) return; if (plugin_rfh) { DCHECK( guest_view->web_contents()->CanAttachToOuterContentsFrame(plugin_rfh)); guest_view->AttachToOuterWebContentsFrame(plugin_rfh, element_instance_id, helper->is_full_page_plugin()); } else { guest_view->GetEmbedderFrame()->Send( new ExtensionsGuestViewMsg_DestroyFrameContainer(element_instance_id)); guest_view->Destroy(true); } frame_navigation_helpers_.erase(element_instance_id); } Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify) { GIOChannel *handle, *ssl_handle; handle = net_connect_ip(ip, port, my_ip); if (handle == NULL) return NULL; ssl_handle = irssi_ssl_get_iochannel(handle, cert, pkey, cafile, capath, verify); if (ssl_handle == NULL) g_io_channel_unref(handle); return ssl_handle; } Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564 CWE ID: CWE-20 Target: 1 Example 2: Code: static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type) { /* if segs_per_sec is large than 1, we need to keep original policy. */ if (sbi->segs_per_sec != 1) return CURSEG_I(sbi, type)->segno; if (type == CURSEG_HOT_DATA || IS_NODESEG(type)) return 0; if (SIT_I(sbi)->last_victim[ALLOC_NEXT]) return SIT_I(sbi)->last_victim[ALLOC_NEXT]; return CURSEG_I(sbi, type)->segno; } Commit Message: f2fs: fix a panic caused by NULL flush_cmd_control Mount fs with option noflush_merge, boot failed for illegal address fcc in function f2fs_issue_flush: if (!test_opt(sbi, FLUSH_MERGE)) { ret = submit_flush_wait(sbi); atomic_inc(&fcc->issued_flush); -> Here, fcc illegal return ret; } Signed-off-by: Yunlei He <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int atusb_get_and_show_build(struct atusb *atusb) { struct usb_device *usb_dev = atusb->usb_dev; char build[ATUSB_BUILD_SIZE + 1]; int ret; ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0), ATUSB_BUILD, ATUSB_REQ_FROM_DEV, 0, 0, build, ATUSB_BUILD_SIZE, 1000); if (ret >= 0) { build[ret] = 0; dev_info(&usb_dev->dev, "Firmware: build %s\n", build); } return ret; } Commit Message: ieee802154: atusb: do not use the stack for buffers to make them DMA able From 4.9 we should really avoid using the stack here as this will not be DMA able on various platforms. This changes the buffers already being present in time of 4.9 being released. This should go into stable as well. Reported-by: Dan Carpenter <[email protected]> Cc: [email protected] Signed-off-by: Stefan Schmidt <[email protected]> Signed-off-by: Marcel Holtmann <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static ogg_uint32_t decpack(long entry,long used_entry,long quantvals, codebook *b,oggpack_buffer *opb,int maptype){ ogg_uint32_t ret=0; int j; switch(b->dec_type){ case 0: return (ogg_uint32_t)entry; case 1: if(maptype==1){ /* vals are already read into temporary column vector here */ for(j=0;j<b->dim;j++){ ogg_uint32_t off=entry%quantvals; entry/=quantvals; ret|=((ogg_uint16_t *)(b->q_val))[off]<<(b->q_bits*j); } }else{ for(j=0;j<b->dim;j++) ret|=oggpack_read(opb,b->q_bits)<<(b->q_bits*j); } return ret; case 2: for(j=0;j<b->dim;j++){ ogg_uint32_t off=entry%quantvals; entry/=quantvals; ret|=off<<(b->q_pack*j); } return ret; case 3: return (ogg_uint32_t)used_entry; } return 0; /* silence compiler */ } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200 Target: 1 Example 2: Code: static int handle_statfs(struct fuse* fuse, struct fuse_handler* handler, const struct fuse_in_header* hdr) { char path[PATH_MAX]; struct statfs stat; struct fuse_statfs_out out; int res; pthread_mutex_lock(&fuse->global->lock); TRACE("[%d] STATFS\n", handler->token); res = get_node_path_locked(&fuse->global->root, path, sizeof(path)); pthread_mutex_unlock(&fuse->global->lock); if (res < 0) { return -ENOENT; } if (statfs(fuse->global->root.name, &stat) < 0) { return -errno; } memset(&out, 0, sizeof(out)); out.st.blocks = stat.f_blocks; out.st.bfree = stat.f_bfree; out.st.bavail = stat.f_bavail; out.st.files = stat.f_files; out.st.ffree = stat.f_ffree; out.st.bsize = stat.f_bsize; out.st.namelen = stat.f_namelen; out.st.frsize = stat.f_frsize; fuse_reply(fuse, hdr->unique, &out, sizeof(out)); return NO_STATUS; } Commit Message: Fix overflow in path building An incorrect size was causing an unsigned value to wrap, causing it to write past the end of the buffer. Bug: 28085658 Change-Id: Ie9625c729cca024d514ba2880ff97209d435a165 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GetMemoryPressureThresholds() { using MemoryPressureMonitor = base::chromeos::MemoryPressureMonitor; if (!base::CommandLine::ForCurrentProcess()->HasSwitch( kMemoryPressureThresholds)) { const std::string group_name = base::FieldTrialList::FindFullName(kMemoryPressureExperimentName); if (group_name == kConservativeThreshold) return MemoryPressureMonitor::THRESHOLD_CONSERVATIVE; if (group_name == kAggressiveCacheDiscardThreshold) return MemoryPressureMonitor::THRESHOLD_AGGRESSIVE_CACHE_DISCARD; if (group_name == kAggressiveTabDiscardThreshold) return MemoryPressureMonitor::THRESHOLD_AGGRESSIVE_TAB_DISCARD; if (group_name == kAggressiveThreshold) return MemoryPressureMonitor::THRESHOLD_AGGRESSIVE; return MemoryPressureMonitor::THRESHOLD_DEFAULT; } const std::string option = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( kMemoryPressureThresholds); if (option == kConservativeThreshold) return MemoryPressureMonitor::THRESHOLD_CONSERVATIVE; if (option == kAggressiveCacheDiscardThreshold) return MemoryPressureMonitor::THRESHOLD_AGGRESSIVE_CACHE_DISCARD; if (option == kAggressiveTabDiscardThreshold) return MemoryPressureMonitor::THRESHOLD_AGGRESSIVE_TAB_DISCARD; if (option == kAggressiveThreshold) return MemoryPressureMonitor::THRESHOLD_AGGRESSIVE; return MemoryPressureMonitor::THRESHOLD_DEFAULT; } Commit Message: Add a fake DriveFS launcher client. Using DriveFS requires building and deploying ChromeOS. Add a client for the fake DriveFS launcher to allow the use of a real DriveFS from a ChromeOS chroot to be used with a target_os="chromeos" build of chrome. This connects to the fake DriveFS launcher using mojo over a unix domain socket named by a command-line flag, using the launcher to create DriveFS instances. Bug: 848126 Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1 Reviewed-on: https://chromium-review.googlesource.com/1098434 Reviewed-by: Xiyuan Xia <[email protected]> Commit-Queue: Sam McNally <[email protected]> Cr-Commit-Position: refs/heads/master@{#567513} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj) { char obj_txt[128]; int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0); BIO_write(bio, obj_txt, len); BIO_write(bio, "\n", 1); return 1; } Commit Message: Fix OOB read in TS_OBJ_print_bio(). TS_OBJ_print_bio() misuses OBJ_txt2obj: it should print the result as a null terminated buffer. The length value returned is the total length the complete text reprsentation would need not the amount of data written. CVE-2016-2180 Thanks to Shi Lei for reporting this bug. Reviewed-by: Matt Caswell <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: static void *pppol2tp_seq_next(struct seq_file *m, void *v, loff_t *pos) { (*pos)++; return NULL; } Commit Message: net/l2tp: don't fall back on UDP [get|set]sockopt The l2tp [get|set]sockopt() code has fallen back to the UDP functions for socket option levels != SOL_PPPOL2TP since day one, but that has never actually worked, since the l2tp socket isn't an inet socket. As David Miller points out: "If we wanted this to work, it'd have to look up the tunnel and then use tunnel->sk, but I wonder how useful that would be" Since this can never have worked so nobody could possibly have depended on that functionality, just remove the broken code and return -EINVAL. Reported-by: Sasha Levin <[email protected]> Acked-by: James Chapman <[email protected]> Acked-by: David Miller <[email protected]> Cc: Phil Turnbull <[email protected]> Cc: Vegard Nossum <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void HTMLCanvasElement::DidDraw(const FloatRect& rect) { if (rect.IsEmpty()) return; canvas_is_clear_ = false; if (GetLayoutObject() && !LowLatencyEnabled()) GetLayoutObject()->SetShouldCheckForPaintInvalidation(); if (Is2d() && context_->ShouldAntialias() && GetPage() && GetPage()->DeviceScaleFactorDeprecated() > 1.0f) { FloatRect inflated_rect = rect; inflated_rect.Inflate(1); dirty_rect_.Unite(inflated_rect); } else { dirty_rect_.Unite(rect); } if (Is2d() && canvas2d_bridge_) canvas2d_bridge_->DidDraw(rect); } Commit Message: Clean up CanvasResourceDispatcher on finalizer We may have pending mojo messages after GC, so we want to drop the dispatcher as soon as possible. Bug: 929757,913964 Change-Id: I5789bcbb55aada4a74c67a28758f07686f8911c0 Reviewed-on: https://chromium-review.googlesource.com/c/1489175 Reviewed-by: Ken Rockot <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Auto-Submit: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#635833} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: kg_unseal_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int *conf_state, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count, int toktype) { krb5_gss_ctx_id_rec *ctx; OM_uint32 code; ctx = (krb5_gss_ctx_id_rec *)context_handle; if (!ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return GSS_S_NO_CONTEXT; } if (kg_locate_iov(iov, iov_count, GSS_IOV_BUFFER_TYPE_STREAM) != NULL) { code = kg_unseal_stream_iov(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } else { code = kg_unseal_iov_token(minor_status, ctx, conf_state, qop_state, iov, iov_count, toktype); } return code; } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID: Target: 1 Example 2: Code: ModuleExport size_t RegisterRLEImage(void) { MagickInfo *entry; entry=SetMagickInfo("RLE"); entry->decoder=(DecodeImageHandler *) ReadRLEImage; entry->magick=(IsImageFormatHandler *) IsRLE; entry->adjoin=MagickFalse; entry->description=ConstantString("Utah Run length encoded image"); entry->module=ConstantString("RLE"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: Check for EOF conditions for RLE image format CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with 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 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void update_db_bp_intercept(struct kvm_vcpu *vcpu) { struct vcpu_svm *svm = to_svm(vcpu); clr_exception_intercept(svm, DB_VECTOR); clr_exception_intercept(svm, BP_VECTOR); if (svm->nmi_singlestep) set_exception_intercept(svm, DB_VECTOR); if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) { if (vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) set_exception_intercept(svm, DB_VECTOR); if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) set_exception_intercept(svm, BP_VECTOR); } else vcpu->guest_debug = 0; } Commit Message: KVM: svm: unconditionally intercept #DB This is needed to avoid the possibility that the guest triggers an infinite stream of #DB exceptions (CVE-2015-8104). VMX is not affected: because it does not save DR6 in the VMCS, it already intercepts #DB unconditionally. Reported-by: Jan Beulich <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: void BrowserCommandController::TabBlockedStateChanged( content::WebContents* contents, int index) { PrintingStateChanged(); FullscreenStateChanged(); UpdateCommandsForFind(); UpdateCommandsForMediaRouter(); } Commit Message: mac: Do not let synthetic events toggle "Allow JavaScript From AppleEvents" Bug: 891697 Change-Id: I49eb77963515637df739c9d2ce83530d4e21cf15 Reviewed-on: https://chromium-review.googlesource.com/c/1308771 Reviewed-by: Elly Fong-Jones <[email protected]> Commit-Queue: Robert Sesek <[email protected]> Cr-Commit-Position: refs/heads/master@{#604268} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: XmpPtr xmp_files_get_new_xmp(XmpFilePtr xf) { CHECK_PTR(xf, NULL); RESET_ERROR; auto txf = reinterpret_cast<SXMPFiles *>(xf); bool result = false; try { auto xmp = std::unique_ptr<SXMPMeta>(new SXMPMeta); result = txf->GetXMP(xmp.get()); if (result) { return reinterpret_cast<XmpPtr>(xmp.release()); } } catch (const XMP_Error &e) { set_error(e); } return NULL; } Commit Message: CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FillRandom(uint8_t *data, int stride) { for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { data[h * stride + w] = rnd_.Rand8(); } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static void CL_CompletePlayerName( char *args, int argNum ) { if( argNum == 2 ) { char names[MAX_CLIENTS][MAX_NAME_LENGTH]; const char *namesPtr[MAX_CLIENTS]; int i; int clientCount; int nameCount; const char *info; const char *name; info = cl.gameState.stringData + cl.gameState.stringOffsets[CS_SERVERINFO]; clientCount = atoi( Info_ValueForKey( info, "sv_maxclients" ) ); nameCount = 0; for( i = 0; i < clientCount; i++ ) { if( i == clc.clientNum ) continue; info = cl.gameState.stringData + cl.gameState.stringOffsets[CS_PLAYERS+i]; name = Info_ValueForKey( info, "n" ); if( name[0] == '\0' ) continue; Q_strncpyz( names[nameCount], name, sizeof(names[nameCount]) ); Q_CleanStr( names[nameCount] ); namesPtr[nameCount] = names[nameCount]; nameCount++; } qsort( (void*)namesPtr, nameCount, sizeof( namesPtr[0] ), Com_strCompare ); Field_CompletePlayerName( namesPtr, nameCount ); } } Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s. CWE ID: CWE-269 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int nfs4_open_expired(struct nfs4_state_owner *sp, struct nfs4_state *state) { struct nfs_open_context *ctx; int ret; ctx = nfs4_state_find_open_context(state); if (IS_ERR(ctx)) return -EAGAIN; ret = nfs4_do_open_expired(ctx, state); put_nfs_open_context(ctx); return ret; } Commit Message: NFS: Fix a NULL pointer dereference of migration recovery ops for v4.2 client ---Steps to Reproduce-- <nfs-server> # cat /etc/exports /nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt) /nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt) <nfs-client> # mount -t nfs nfs-server:/nfs/ /mnt/ # ll /mnt/*/ <nfs-server> # cat /etc/exports /nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt,refer=/nfs/old/@nfs-server) /nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt) # service nfs restart <nfs-client> # ll /mnt/*/ --->>>>> oops here [ 5123.102925] BUG: unable to handle kernel NULL pointer dereference at (null) [ 5123.103363] IP: [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.103752] PGD 587b9067 PUD 3cbf5067 PMD 0 [ 5123.104131] Oops: 0000 [#1] [ 5123.104529] Modules linked in: nfsv4(OE) nfs(OE) fscache(E) nfsd(OE) xfs libcrc32c iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi coretemp crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel ppdev vmw_balloon parport_pc parport i2c_piix4 shpchp auth_rpcgss nfs_acl vmw_vmci lockd grace sunrpc vmwgfx drm_kms_helper ttm drm mptspi serio_raw scsi_transport_spi e1000 mptscsih mptbase ata_generic pata_acpi [last unloaded: nfsd] [ 5123.105887] CPU: 0 PID: 15853 Comm: ::1-manager Tainted: G OE 4.2.0-rc6+ #214 [ 5123.106358] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 05/20/2014 [ 5123.106860] task: ffff88007620f300 ti: ffff88005877c000 task.ti: ffff88005877c000 [ 5123.107363] RIP: 0010:[<ffffffffa03ed38b>] [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.107909] RSP: 0018:ffff88005877fdb8 EFLAGS: 00010246 [ 5123.108435] RAX: ffff880053f3bc00 RBX: ffff88006ce6c908 RCX: ffff880053a0d240 [ 5123.108968] RDX: ffffea0000e6d940 RSI: ffff8800399a0000 RDI: ffff88006ce6c908 [ 5123.109503] RBP: ffff88005877fe28 R08: ffffffff81c708a0 R09: 0000000000000000 [ 5123.110045] R10: 00000000000001a2 R11: ffff88003ba7f5c8 R12: ffff880054c55800 [ 5123.110618] R13: 0000000000000000 R14: ffff880053a0d240 R15: ffff880053a0d240 [ 5123.111169] FS: 0000000000000000(0000) GS:ffffffff81c27000(0000) knlGS:0000000000000000 [ 5123.111726] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 5123.112286] CR2: 0000000000000000 CR3: 0000000054cac000 CR4: 00000000001406f0 [ 5123.112888] Stack: [ 5123.113458] ffffea0000e6d940 ffff8800399a0000 00000000000167d0 0000000000000000 [ 5123.114049] 0000000000000000 0000000000000000 0000000000000000 00000000a7ec82c6 [ 5123.114662] ffff88005877fe18 ffffea0000e6d940 ffff8800399a0000 ffff880054c55800 [ 5123.115264] Call Trace: [ 5123.115868] [<ffffffffa03fb44b>] nfs4_try_migration+0xbb/0x220 [nfsv4] [ 5123.116487] [<ffffffffa03fcb3b>] nfs4_run_state_manager+0x4ab/0x7b0 [nfsv4] [ 5123.117104] [<ffffffffa03fc690>] ? nfs4_do_reclaim+0x510/0x510 [nfsv4] [ 5123.117813] [<ffffffff810a4527>] kthread+0xd7/0xf0 [ 5123.118456] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160 [ 5123.119108] [<ffffffff816d9cdf>] ret_from_fork+0x3f/0x70 [ 5123.119723] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160 [ 5123.120329] Code: 4c 8b 6a 58 74 17 eb 52 48 8d 55 a8 89 c6 4c 89 e7 e8 4a b5 ff ff 8b 45 b0 85 c0 74 1c 4c 89 f9 48 8b 55 90 48 8b 75 98 48 89 df <41> ff 55 00 3d e8 d8 ff ff 41 89 c6 74 cf 48 8b 4d c8 65 48 33 [ 5123.121643] RIP [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.122308] RSP <ffff88005877fdb8> [ 5123.122942] CR2: 0000000000000000 Fixes: ec011fe847 ("NFS: Introduce a vector of migration recovery ops") Cc: [email protected] # v3.13+ Signed-off-by: Kinglong Mee <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: v8::Local<v8::Value> V8Debugger::functionLocation(v8::Local<v8::Context> context, v8::Local<v8::Function> function) { int scriptId = function->ScriptId(); if (scriptId == v8::UnboundScript::kNoScriptId) return v8::Null(m_isolate); int lineNumber = function->GetScriptLineNumber(); int columnNumber = function->GetScriptColumnNumber(); if (lineNumber == v8::Function::kLineOffsetNotFound || columnNumber == v8::Function::kLineOffsetNotFound) return v8::Null(m_isolate); v8::Local<v8::Object> location = v8::Object::New(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "scriptId"), toV8String(m_isolate, String16::fromInteger(scriptId))).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "lineNumber"), v8::Integer::New(m_isolate, lineNumber)).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "columnNumber"), v8::Integer::New(m_isolate, columnNumber)).FromMaybe(false)) return v8::Null(m_isolate); if (!markAsInternal(context, location, V8InternalValueType::kLocation)) return v8::Null(m_isolate); return location; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79 Target: 1 Example 2: Code: static void reflectUrlStringAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Value> v8Value = info[0]; V0CustomElementProcessingStack::CallbackDeliveryScope deliveryScope; TestInterfaceNodeV8Internal::reflectUrlStringAttributeAttributeSetter(v8Value, info); } Commit Message: binding: Removes unused code in templates/attributes.cpp. Faking {{cpp_class}} and {{c8_class}} doesn't make sense. Probably it made sense before the introduction of virtual ScriptWrappable::wrap(). Checking the existence of window->document() doesn't seem making sense to me, and CQ tests seem passing without the check. BUG= Review-Url: https://codereview.chromium.org/2268433002 Cr-Commit-Position: refs/heads/master@{#413375} CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int multipath_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct multipath *m = (struct multipath *) ti->private; struct block_device *bdev = NULL; fmode_t mode = 0; unsigned long flags; int r = 0; spin_lock_irqsave(&m->lock, flags); if (!m->current_pgpath) __choose_pgpath(m, 0); if (m->current_pgpath) { bdev = m->current_pgpath->path.dev->bdev; mode = m->current_pgpath->path.dev->mode; } if (m->queue_io) r = -EAGAIN; else if (!bdev) r = -EIO; spin_unlock_irqrestore(&m->lock, flags); return r ? : __blkdev_driver_ioctl(bdev, mode, cmd, arg); } Commit Message: dm: do not forward ioctls from logical volumes to the underlying device A logical volume can map to just part of underlying physical volume. In this case, it must be treated like a partition. Based on a patch from Alasdair G Kergon. Cc: Alasdair G Kergon <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool MediaControlsProgressView::OnMousePressed(const ui::MouseEvent& event) { gfx::Point location_in_bar(event.location()); ConvertPointToTarget(this, this->progress_bar_, &location_in_bar); if (!event.IsOnlyLeftMouseButton() || !progress_bar_->GetLocalBounds().Contains(location_in_bar)) { return false; } HandleSeeking(location_in_bar); return true; } Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks This CL rearranges the different components of the CrOS lock screen media controls based on the newest mocks. This involves resizing most of the child views and their spacings. The artwork was also resized and re-positioned. Additionally, the close button was moved from the main view to the header row child view. Artist and title data about the current session will eventually be placed to the right of the artwork, but right now this space is empty. See the bug for before and after pictures. Bug: 991647 Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554 Reviewed-by: Xiyuan Xia <[email protected]> Reviewed-by: Becca Hughes <[email protected]> Commit-Queue: Mia Bergeron <[email protected]> Cr-Commit-Position: refs/heads/master@{#686253} CWE ID: CWE-200 Target: 1 Example 2: Code: unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; struct sctp_sock *sp = sctp_sk(sk); unsigned int mask; poll_wait(file, sk->sk_sleep, wait); /* A TCP-style listening socket becomes readable when the accept queue * is not empty. */ if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) return (!list_empty(&sp->ep->asocs)) ? (POLLIN | POLLRDNORM) : 0; mask = 0; /* Is there any exceptional events? */ if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; /* Is it readable? Reconsider this code with TCP-style support. */ if (!skb_queue_empty(&sk->sk_receive_queue) || (sk->sk_shutdown & RCV_SHUTDOWN)) mask |= POLLIN | POLLRDNORM; /* The association is either gone or not ready. */ if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED)) return mask; /* Is it writable? */ if (sctp_writeable(sk)) { mask |= POLLOUT | POLLWRNORM; } else { set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); /* * Since the socket is not locked, the buffer * might be made available after the writeable check and * before the bit is set. This could cause a lost I/O * signal. tcp_poll() has a race breaker for this race * condition. Based on their implementation, we put * in the following code to cover it as well. */ if (sctp_writeable(sk)) mask |= POLLOUT | POLLWRNORM; } return mask; } Commit Message: [SCTP]: Fix assertion (!atomic_read(&sk->sk_rmem_alloc)) failed message In current implementation, LKSCTP does receive buffer accounting for data in sctp_receive_queue and pd_lobby. However, LKSCTP don't do accounting for data in frag_list when data is fragmented. In addition, LKSCTP doesn't do accounting for data in reasm and lobby queue in structure sctp_ulpq. When there are date in these queue, assertion failed message is printed in inet_sock_destruct because sk_rmem_alloc of oldsk does not become 0 when socket is destroyed. Signed-off-by: Tsutomu Fujii <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void set_cfg_option(char *opt_string) { char *sep, *sep2, szSec[1024], szKey[1024], szVal[1024]; sep = strchr(opt_string, ':'); if (!sep) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep - opt_string; strncpy(szSec, opt_string, sepIdx); szSec[sepIdx] = 0; } sep ++; sep2 = strchr(sep, '='); if (!sep2) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep2 - sep; strncpy(szKey, sep, sepIdx); szKey[sepIdx] = 0; strcpy(szVal, sep2+1); } if (!stricmp(szKey, "*")) { if (stricmp(szVal, "null")) { fprintf(stderr, "Badly formatted option %s - expected Section:*=null\n", opt_string); return; } gf_cfg_del_section(cfg_file, szSec); return; } if (!stricmp(szVal, "null")) { szVal[0]=0; } gf_cfg_set_key(cfg_file, szSec, szKey, szVal[0] ? szVal : NULL); } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendingScript, PendingScript::Type pendingScriptType) { bool errorOccurred = false; double loadFinishTime = pendingScript.resource() && pendingScript.resource()->url().protocolIsInHTTPFamily() ? pendingScript.resource()->loadFinishTime() : 0; ScriptSourceCode sourceCode = pendingScript.getSource(documentURLForScriptExecution(m_document), errorOccurred); pendingScript.stopWatchingForLoad(this); if (!isExecutingScript()) { Microtask::performCheckpoint(); if (pendingScriptType == PendingScript::ParsingBlocking) { m_hasScriptsWaitingForResources = !m_document->isScriptExecutionReady(); if (m_hasScriptsWaitingForResources) return; } } RefPtrWillBeRawPtr<Element> element = pendingScript.releaseElementAndClear(); double compilationFinishTime = 0; if (ScriptLoader* scriptLoader = toScriptLoaderIfPossible(element.get())) { NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_document); if (errorOccurred) scriptLoader->dispatchErrorEvent(); else { ASSERT(isExecutingScript()); if (!scriptLoader->executeScript(sourceCode, &compilationFinishTime)) { scriptLoader->dispatchErrorEvent(); } else { element->dispatchEvent(createScriptLoadEvent()); } } } const double epsilon = 1; if (pendingScriptType == PendingScript::ParsingBlocking && !m_parserBlockingScriptAlreadyLoaded && compilationFinishTime > epsilon && loadFinishTime > epsilon) { Platform::current()->histogramCustomCounts("WebCore.Scripts.ParsingBlocking.TimeBetweenLoadedAndCompiled", (compilationFinishTime - loadFinishTime) * 1000, 0, 10000, 50); } ASSERT(!isExecutingScript()); } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254 Target: 1 Example 2: Code: static int crypto_rfc4309_setauthsize(struct crypto_aead *parent, unsigned int authsize) { struct crypto_rfc4309_ctx *ctx = crypto_aead_ctx(parent); switch (authsize) { case 8: case 12: case 16: break; default: return -EINVAL; } return crypto_aead_setauthsize(ctx->child, authsize); } Commit Message: crypto: include crypto- module prefix in template This adds the module loading prefix "crypto-" to the template lookup as well. For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly includes the "crypto-" prefix at every level, correctly rejecting "vfat": net-pf-38 algif-hash crypto-vfat(blowfish) crypto-vfat(blowfish)-all crypto-vfat Reported-by: Mathias Krause <[email protected]> Signed-off-by: Kees Cook <[email protected]> Acked-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void GLES2DecoderImpl::DoDisableVertexAttribArray(GLuint index) { if (state_.vertex_attrib_manager->Enable(index, false)) { if (index != 0 || gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) { glDisableVertexAttribArray(index); } } else { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, "glDisableVertexAttribArray", "index out of range"); } } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance [email protected],[email protected] Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void V8ContextNativeHandler::RunWithNativesEnabledModuleSystem( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK_EQ(args.Length(), 1); CHECK(args[0]->IsFunction()); v8::Local<v8::Value> call_with_args[] = { context()->module_system()->NewInstance()}; ModuleSystem::NativesEnabledScope natives_enabled(context()->module_system()); context()->CallFunction(v8::Local<v8::Function>::Cast(args[0]), 1, call_with_args); } Commit Message: Add a test that getModuleSystem() doesn't work cross origin BUG=504011 [email protected] [email protected] Review URL: https://codereview.chromium.org/1241443004 Cr-Commit-Position: refs/heads/master@{#338663} CWE ID: CWE-79 Target: 1 Example 2: Code: GF_Err mdhd_Size(GF_Box *s) { GF_MediaHeaderBox *ptr = (GF_MediaHeaderBox *)s; ptr->version = (ptr->duration>0xFFFFFFFF) ? 1 : 0; ptr->size += 4; ptr->size += (ptr->version == 1) ? 28 : 16; return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Address LargeObjectArena::doAllocateLargeObjectPage(size_t allocationSize, size_t gcInfoIndex) { size_t largeObjectSize = LargeObjectPage::pageHeaderSize() + allocationSize; #if defined(ADDRESS_SANITIZER) largeObjectSize += allocationGranularity; #endif getThreadState()->shouldFlushHeapDoesNotContainCache(); PageMemory* pageMemory = PageMemory::allocate( largeObjectSize, getThreadState()->heap().getRegionTree()); Address largeObjectAddress = pageMemory->writableStart(); Address headerAddress = largeObjectAddress + LargeObjectPage::pageHeaderSize(); #if DCHECK_IS_ON() for (size_t i = 0; i < largeObjectSize; ++i) ASSERT(!largeObjectAddress[i]); #endif ASSERT(gcInfoIndex > 0); HeapObjectHeader* header = new (NotNull, headerAddress) HeapObjectHeader(largeObjectSizeInHeader, gcInfoIndex); Address result = headerAddress + sizeof(*header); ASSERT(!(reinterpret_cast<uintptr_t>(result) & allocationMask)); LargeObjectPage* largeObject = new (largeObjectAddress) LargeObjectPage(pageMemory, this, allocationSize); ASSERT(header->checkHeader()); ASAN_POISON_MEMORY_REGION(header, sizeof(*header)); ASAN_POISON_MEMORY_REGION(largeObject->getAddress() + largeObject->size(), allocationGranularity); largeObject->link(&m_firstPage); getThreadState()->heap().heapStats().increaseAllocatedSpace( largeObject->size()); getThreadState()->increaseAllocatedObjectSize(largeObject->size()); return result; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WorkerProcessLauncherTest::SetUp() { task_runner_ = new AutoThreadTaskRunner( message_loop_.message_loop_proxy(), base::Bind(&WorkerProcessLauncherTest::QuitMainMessageLoop, base::Unretained(this))); exit_code_ = STILL_ACTIVE; launcher_delegate_.reset(new MockProcessLauncherDelegate()); EXPECT_CALL(*launcher_delegate_, Send(_)) .Times(AnyNumber()) .WillRepeatedly(Return(false)); EXPECT_CALL(*launcher_delegate_, GetExitCode()) .Times(AnyNumber()) .WillRepeatedly(ReturnPointee(&exit_code_)); EXPECT_CALL(*launcher_delegate_, KillProcess(_)) .Times(AnyNumber()) .WillRepeatedly(Invoke(this, &WorkerProcessLauncherTest::KillProcess)); EXPECT_CALL(ipc_delegate_, OnMessageReceived(_)) .Times(AnyNumber()) .WillRepeatedly(Return(false)); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: short *XRRConfigRates (XRRScreenConfiguration *config, int sizeID, int *nrates) { short *r = config->rates; int nents = config->nrates; /* Skip over the intervening rate lists */ while (sizeID > 0 && nents > 0) { int i = (*r + 1); r += i; nents -= i; sizeID--; } if (!nents) { *nrates = 0; return NULL; } *nrates = (int) *r; return r + 1; } Commit Message: CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool GIFImageReader::decode(size_t frameIndex) { m_globalColorMap.buildTable(data(0), m_data->size()); bool frameDecoded = false; GIFFrameContext* currentFrame = m_frames[frameIndex].get(); return currentFrame->decode(data(0), m_data->size(), m_client, &frameDecoded) && (!frameDecoded || m_client->frameComplete(frameIndex)); } Commit Message: Fix handling of broken GIFs with weird frame sizes Code didn't handle well if a GIF frame has dimension greater than the "screen" dimension. This will break deferred image decoding. This change reports the size as final only when the first frame is encountered. Added a test to verify this behavior. Frame size reported by the decoder should be constant. BUG=437651 [email protected], [email protected] Review URL: https://codereview.chromium.org/813943003 git-svn-id: svn://svn.chromium.org/blink/trunk@188423 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WORD32 ihevcd_ref_list(codec_t *ps_codec, pps_t *ps_pps, sps_t *ps_sps, slice_header_t *ps_slice_hdr) { WORD32 i; WORD32 st_rps_idx; WORD32 num_neg_pics, num_pos_pics; WORD8 *pi1_used; WORD16 *pi2_delta_poc; UWORD32 u4_max_poc_lsb; pic_buf_t *ps_pic_buf; mv_buf_t *ps_mv_buf; UWORD32 r_idx; dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr; buf_mgr_t *ps_mv_buf_mgr = (buf_mgr_t *)ps_codec->pv_mv_buf_mgr; WORD32 ai4_poc_st_curr_before[MAX_DPB_SIZE], ai4_poc_st_foll[MAX_DPB_SIZE], ai4_poc_st_curr_after[MAX_DPB_SIZE]; WORD32 ai4_poc_lt_curr[MAX_DPB_SIZE], ai4_poc_lt_foll[MAX_DPB_SIZE]; UWORD32 u4_num_st_curr_before, u4_num_st_foll, u4_num_st_curr_after, u4_num_lt_curr, u4_num_lt_foll; UWORD32 u4_num_total_curr; WORD8 ai1_curr_delta_poc_msb_present_flag[MAX_DPB_SIZE], ai1_foll_delta_poc_msb_present_flag[MAX_DPB_SIZE]; pic_buf_t *as_ref_pic_lt_curr[MAX_DPB_SIZE]; pic_buf_t *as_ref_pic_lt_foll[MAX_DPB_SIZE]; pic_buf_t *as_ref_pic_st_curr_after[MAX_DPB_SIZE]; pic_buf_t *as_ref_pic_st_curr_before[MAX_DPB_SIZE]; pic_buf_t *as_ref_pic_st_foll[MAX_DPB_SIZE]; pic_buf_t *as_ref_pic_list_temp0[MAX_DPB_SIZE], *as_ref_pic_list_temp1[MAX_DPB_SIZE]; UWORD32 u4_num_rps_curr_temp_list0, u4_num_rps_curr_temp_list1; WORD32 i4_pic_order_cnt_val; WORD32 i4_poc_lt; UNUSED(as_ref_pic_lt_foll); UNUSED(as_ref_pic_st_foll); UNUSED(ps_pps); RETURN_IF_NAL_INFO; u4_max_poc_lsb = (1 << ps_sps->i1_log2_max_pic_order_cnt_lsb); i4_pic_order_cnt_val = ps_slice_hdr->i4_abs_pic_order_cnt; if(1 == ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag) { st_rps_idx = ps_slice_hdr->i1_short_term_ref_pic_set_idx; num_neg_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_neg_pics; num_pos_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_pos_pics; pi1_used = ps_sps->as_stref_picset[st_rps_idx].ai1_used; pi2_delta_poc = ps_sps->as_stref_picset[st_rps_idx].ai2_delta_poc; } else { st_rps_idx = ps_sps->i1_num_short_term_ref_pic_sets; num_neg_pics = ps_slice_hdr->s_stref_picset.i1_num_neg_pics; num_pos_pics = ps_slice_hdr->s_stref_picset.i1_num_pos_pics; pi1_used = ps_slice_hdr->s_stref_picset.ai1_used; pi2_delta_poc = ps_slice_hdr->s_stref_picset.ai2_delta_poc; } u4_num_st_curr_before = 0; u4_num_st_foll = 0; for(i = 0; i < num_neg_pics; i++) { if(pi1_used[i]) { ai4_poc_st_curr_before[u4_num_st_curr_before] = i4_pic_order_cnt_val + pi2_delta_poc[i]; u4_num_st_curr_before++; } else { ai4_poc_st_foll[u4_num_st_foll] = i4_pic_order_cnt_val + pi2_delta_poc[i]; u4_num_st_foll++; } } u4_num_st_curr_after = 0; for(i = num_neg_pics; i < num_neg_pics + num_pos_pics; i++) { if(pi1_used[i]) { ai4_poc_st_curr_after[u4_num_st_curr_after] = i4_pic_order_cnt_val + pi2_delta_poc[i]; u4_num_st_curr_after++; } else { ai4_poc_st_foll[u4_num_st_foll] = i4_pic_order_cnt_val + pi2_delta_poc[i]; u4_num_st_foll++; } } u4_num_lt_curr = 0; u4_num_lt_foll = 0; for(i = 0; i < ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics; i++) { i4_poc_lt = ps_slice_hdr->ai4_poc_lsb_lt[i]; if(ps_slice_hdr->ai1_delta_poc_msb_present_flag[i]) { i4_poc_lt += i4_pic_order_cnt_val - ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] * u4_max_poc_lsb - ps_slice_hdr->i4_pic_order_cnt_lsb; } if(ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i]) { ai4_poc_lt_curr[u4_num_lt_curr] = i4_poc_lt; ai1_curr_delta_poc_msb_present_flag[u4_num_lt_curr] = ps_slice_hdr->ai1_delta_poc_msb_present_flag[i]; u4_num_lt_curr++; } else { ai4_poc_lt_foll[u4_num_lt_foll] = i4_poc_lt; ai1_foll_delta_poc_msb_present_flag[u4_num_lt_foll] = ps_slice_hdr->ai1_delta_poc_msb_present_flag[i]; u4_num_lt_foll++; } } u4_num_total_curr = u4_num_lt_curr + u4_num_st_curr_after + u4_num_st_curr_before; /* Bit stream conformance tests */ /* for(i = 0; i < u4_num_lt_curr; i++) { int j; if(ai1_curr_delta_poc_msb_present_flag[i]) { for(j = 0; j < u4_num_st_curr_before; j++) { ASSERT(ai4_poc_st_curr_before[j] != ai4_poc_lt_curr[i]); } for(j = 0; j < u4_num_st_curr_after; j++) { ASSERT(ai4_poc_st_curr_after[j] != ai4_poc_lt_curr[i]); } for(j = 0; j < u4_num_st_foll; j++) { ASSERT(ai4_poc_st_foll[j] != ai4_poc_lt_curr[i]); } for(j = 0; j < u4_num_lt_curr; j++) { ASSERT((ai4_poc_lt_curr[j] != ai4_poc_lt_curr[i]) || (j == i)); } } else { for(j = 0; j < u4_num_st_curr_before; j++) { ASSERT((ai4_poc_st_curr_before[j] & (u4_max_poc_lsb - 1)) != ai4_poc_lt_curr[i]); } for(j = 0; j < u4_num_st_curr_after; j++) { ASSERT((ai4_poc_st_curr_after[j] & (u4_max_poc_lsb - 1)) != ai4_poc_lt_curr[i]); } for(j = 0; j < u4_num_st_foll; j++) { ASSERT((ai4_poc_st_foll[j] & (u4_max_poc_lsb - 1)) != ai4_poc_lt_curr[i]); } for(j = 0; j < u4_num_lt_curr; j++) { ASSERT(((ai4_poc_lt_curr[j] & (u4_max_poc_lsb - 1)) != ai4_poc_lt_curr[i]) || (j == i)); } } } for(i = 0; i < u4_num_lt_foll; i++) { int j; if(ai1_foll_delta_poc_msb_present_flag[i]) { for(j = 0; j < u4_num_st_curr_before; j++) { ASSERT(ai4_poc_st_curr_before[j] != ai4_poc_lt_foll[i]); } for(j = 0; j < u4_num_st_curr_after; j++) { ASSERT(ai4_poc_st_curr_after[j] != ai4_poc_lt_foll[i]); } for(j = 0; j < u4_num_st_foll; j++) { ASSERT(ai4_poc_st_foll[j] != ai4_poc_lt_foll[i]); } for(j = 0; j < u4_num_lt_curr; j++) { ASSERT(ai4_poc_lt_curr[j] != ai4_poc_lt_foll[i]); } for(j = 0; j < u4_num_lt_foll; j++) { ASSERT((ai4_poc_lt_foll[j] != ai4_poc_lt_foll[i]) || (j == i)); } } else { for(j = 0; j < u4_num_st_curr_before; j++) { ASSERT((ai4_poc_st_curr_before[j] & (u4_max_poc_lsb - 1)) != ai4_poc_lt_foll[i]); } for(j = 0; j < u4_num_st_curr_after; j++) { ASSERT((ai4_poc_st_curr_after[j] & (u4_max_poc_lsb - 1)) != ai4_poc_lt_foll[i]); } for(j = 0; j < u4_num_st_foll; j++) { ASSERT((ai4_poc_st_foll[j] & (u4_max_poc_lsb - 1)) != ai4_poc_lt_foll[i]); } for(j = 0; j < u4_num_lt_curr; j++) { ASSERT((ai4_poc_lt_curr[j] & (u4_max_poc_lsb - 1)) != ai4_poc_lt_foll[i]); } for(j = 0; j < u4_num_lt_foll; j++) { ASSERT(((ai4_poc_lt_foll[j] & (u4_max_poc_lsb - 1)) != ai4_poc_lt_foll[i]) || (j == i)); } } } */ /* Reference Pic sets creation */ /* Set all the DPB buffers to UNUSED_FOR_REF */ if(0 == ps_codec->i4_pic_present) { for(i = 0; i < MAX_DPB_BUFS; i++) { if(ps_dpb_mgr->as_dpb_info[i].ps_pic_buf) ps_dpb_mgr->as_dpb_info[i].ps_pic_buf->u1_used_as_ref = UNUSED_FOR_REF; } } for(i = 0; i < (WORD32)u4_num_lt_curr; i++) { if(0 == ai1_curr_delta_poc_msb_present_flag[i]) { ps_pic_buf = ihevc_dpb_mgr_get_ref_by_poc_lsb(ps_dpb_mgr, ai4_poc_lt_curr[i]); if(NULL != ps_pic_buf) ps_pic_buf->u1_used_as_ref = LONG_TERM_REF; as_ref_pic_lt_curr[i] = ps_pic_buf; } else { ps_pic_buf = ihevc_dpb_mgr_get_ref_by_poc(ps_dpb_mgr, ai4_poc_lt_curr[i]); if(NULL != ps_pic_buf) ps_pic_buf->u1_used_as_ref = LONG_TERM_REF; as_ref_pic_lt_curr[i] = ps_pic_buf; } } for(i = 0; i < (WORD32)u4_num_lt_foll; i++) { if(0 == ai1_foll_delta_poc_msb_present_flag[i]) { ps_pic_buf = ihevc_dpb_mgr_get_ref_by_poc_lsb(ps_dpb_mgr, ai4_poc_lt_foll[i]); if(NULL != ps_pic_buf) ps_pic_buf->u1_used_as_ref = LONG_TERM_REF; as_ref_pic_lt_foll[i] = ps_pic_buf; } else { ps_pic_buf = ihevc_dpb_mgr_get_ref_by_poc(ps_dpb_mgr, ai4_poc_lt_foll[i]); if(NULL != ps_pic_buf) ps_pic_buf->u1_used_as_ref = LONG_TERM_REF; as_ref_pic_lt_foll[i] = ps_pic_buf; } } for(i = 0; i < (WORD32)u4_num_st_curr_before; i++) { ps_pic_buf = ihevc_dpb_mgr_get_ref_by_poc(ps_dpb_mgr, ai4_poc_st_curr_before[i]); if(NULL != ps_pic_buf) ps_pic_buf->u1_used_as_ref = SHORT_TERM_REF; as_ref_pic_st_curr_before[i] = ps_pic_buf; } for(i = 0; i < (WORD32)u4_num_st_curr_after; i++) { ps_pic_buf = ihevc_dpb_mgr_get_ref_by_poc(ps_dpb_mgr, ai4_poc_st_curr_after[i]); if(NULL != ps_pic_buf) ps_pic_buf->u1_used_as_ref = SHORT_TERM_REF; as_ref_pic_st_curr_after[i] = ps_pic_buf; } for(i = 0; i < (WORD32)u4_num_st_foll; i++) { ps_pic_buf = ihevc_dpb_mgr_get_ref_by_poc(ps_dpb_mgr, ai4_poc_st_foll[i]); if(NULL != ps_pic_buf) ps_pic_buf->u1_used_as_ref = SHORT_TERM_REF; as_ref_pic_st_foll[i] = ps_pic_buf; } u4_num_rps_curr_temp_list0 = (WORD32)u4_num_total_curr > ps_slice_hdr->i1_num_ref_idx_l0_active ? (WORD32)u4_num_total_curr : ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx = 0; if((PSLICE == ps_slice_hdr->i1_slice_type) || (BSLICE == ps_slice_hdr->i1_slice_type)) { while(r_idx < u4_num_rps_curr_temp_list0) { for(i = 0; (i < (WORD32)u4_num_st_curr_before) && (r_idx < u4_num_rps_curr_temp_list0); r_idx++, i++) { if(NULL == as_ref_pic_st_curr_before[i]) { as_ref_pic_st_curr_before[i] = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ai4_poc_st_curr_before[i]); } as_ref_pic_list_temp0[r_idx] = as_ref_pic_st_curr_before[i]; } for(i = 0; (i < (WORD32)u4_num_st_curr_after) && (r_idx < u4_num_rps_curr_temp_list0); r_idx++, i++) { if(NULL == as_ref_pic_st_curr_after[i]) { as_ref_pic_st_curr_after[i] = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ai4_poc_st_curr_after[i]); } as_ref_pic_list_temp0[r_idx] = as_ref_pic_st_curr_after[i]; } for(i = 0; (i < (WORD32)u4_num_lt_curr) && (r_idx < u4_num_rps_curr_temp_list0); r_idx++, i++) { if(NULL == as_ref_pic_lt_curr[i]) { as_ref_pic_lt_curr[i] = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ai4_poc_lt_curr[i]); } as_ref_pic_list_temp0[r_idx] = as_ref_pic_lt_curr[i]; } } for(r_idx = 0; (WORD32)r_idx < ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx++) { pic_buf_t *ps_pic_buf; ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l0 ? (void *)as_ref_pic_list_temp0[ps_slice_hdr->s_rplm.i1_list_entry_l0[r_idx]] : (void *)as_ref_pic_list_temp0[r_idx]; ps_pic_buf = (pic_buf_t *)ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf; if(ps_pic_buf == NULL) return IHEVCD_REF_PIC_NOT_FOUND; ps_mv_buf = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf->i4_abs_poc); ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = ps_mv_buf; } if(ps_slice_hdr->i1_slice_type == BSLICE) { u4_num_rps_curr_temp_list1 = (WORD32)u4_num_total_curr > ps_slice_hdr->i1_num_ref_idx_l1_active ? (WORD32)u4_num_total_curr : ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx = 0; while(r_idx < u4_num_rps_curr_temp_list1) { for(i = 0; (i < (WORD32)u4_num_st_curr_after) && (r_idx < u4_num_rps_curr_temp_list1); r_idx++, i++) { if(NULL == as_ref_pic_st_curr_after[i]) { as_ref_pic_st_curr_after[i] = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ai4_poc_st_curr_after[i]); } as_ref_pic_list_temp1[r_idx] = as_ref_pic_st_curr_after[i]; } for(i = 0; (i < (WORD32)u4_num_st_curr_before) && (r_idx < u4_num_rps_curr_temp_list1); r_idx++, i++) { if(NULL == as_ref_pic_st_curr_before[i]) { as_ref_pic_st_curr_before[i] = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ai4_poc_st_curr_before[i]); } as_ref_pic_list_temp1[r_idx] = as_ref_pic_st_curr_before[i]; } for(i = 0; (i < (WORD32)u4_num_lt_curr) && (r_idx < u4_num_rps_curr_temp_list1); r_idx++, i++) { if(NULL == as_ref_pic_lt_curr[i]) { as_ref_pic_lt_curr[i] = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ai4_poc_lt_curr[i]); } as_ref_pic_list_temp1[r_idx] = as_ref_pic_lt_curr[i]; } } for(r_idx = 0; (WORD32)r_idx < ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx++) { pic_buf_t *ps_pic_buf; ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l1 ? (void *)as_ref_pic_list_temp1[ps_slice_hdr->s_rplm.i1_list_entry_l1[r_idx]] : (void *)as_ref_pic_list_temp1[r_idx]; ps_pic_buf = (pic_buf_t *)ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf; if(ps_pic_buf == NULL) return IHEVCD_REF_PIC_NOT_FOUND; ps_mv_buf = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf->i4_abs_poc); ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = ps_mv_buf; } } } DEBUG_PRINT_REF_LIST_POCS(i4_pic_order_cnt_val, ps_slice_hdr, ps_dpb_mgr, u4_num_st_curr_before, u4_num_st_curr_after, u4_num_st_foll, u4_num_lt_curr, u4_num_lt_foll, ai4_poc_st_curr_before, ai4_poc_st_curr_after, ai4_poc_st_foll, ai4_poc_lt_curr, ai4_poc_lt_foll); /* Buffers that are still marked as UNUSED_FOR_REF are released from dpb (internally dpb calls release from pic buf manager)*/ for(i = 0; i < MAX_DPB_BUFS; i++) { if((ps_dpb_mgr->as_dpb_info[i].ps_pic_buf) && (UNUSED_FOR_REF == ps_dpb_mgr->as_dpb_info[i].ps_pic_buf->u1_used_as_ref)) { pic_buf_t *ps_pic_buf = ps_dpb_mgr->as_dpb_info[i].ps_pic_buf; mv_buf_t *ps_mv_buf; /* Long term index is set to MAX_DPB_BUFS to ensure it is not added as LT */ ihevc_dpb_mgr_del_ref(ps_dpb_mgr, (buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_pic_buf->i4_abs_poc); /* Find buffer id of the MV bank corresponding to the buffer being freed (Buffer with POC of u4_abs_poc) */ ps_mv_buf = (mv_buf_t *)ps_codec->ps_mv_buf; for(i = 0; i < BUF_MGR_MAX_CNT; i++) { if(ps_mv_buf && ps_mv_buf->i4_abs_poc == ps_pic_buf->i4_abs_poc) { ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, i, BUF_MGR_REF); break; } ps_mv_buf++; } } } return IHEVCD_SUCCESS; } Commit Message: Check only allocated mv bufs for releasing from reference When checking mv bufs for releasing from reference, unallocated mv bufs were also checked. This issue was fixed by restricting the loop count to allocated number of mv bufs. Bug: 34896906 Bug: 34819017 Change-Id: If832f590b301f414d4cd5206414efc61a70c17cb (cherry picked from commit 23bfe3e06d53ea749073a5d7ceda84239742b2c2) CWE ID: Target: 1 Example 2: Code: ofproto_set_cpu_mask(const char *cmask) { free(pmd_cpu_mask); pmd_cpu_mask = nullable_xstrdup(cmask); } Commit Message: ofproto: Fix OVS crash when reverting old flows in bundle commit During bundle commit flows which are added in bundle are applied to ofproto in-order. In case if a flow cannot be added (e.g. flow action is go-to group id which does not exist), OVS tries to revert back all previous flows which were successfully applied from the same bundle. This is possible since OVS maintains list of old flows which were replaced by flows from the bundle. While reinserting old flows ovs asserts due to check on rule state != RULE_INITIALIZED. This will work only for new flows, but for old flow the rule state will be RULE_REMOVED. This is causing an assert and OVS crash. The ovs assert check should be modified to != RULE_INSERTED to prevent any existing rule being re-inserted and allow new rules and old rules (in case of revert) to get inserted. Here is an example to trigger the assert: $ ovs-vsctl add-br br-test -- set Bridge br-test datapath_type=netdev $ cat flows.txt flow add table=1,priority=0,in_port=2,actions=NORMAL flow add table=1,priority=0,in_port=3,actions=NORMAL $ ovs-ofctl dump-flows -OOpenflow13 br-test cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=2 actions=NORMAL cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=3 actions=NORMAL $ cat flow-modify.txt flow modify table=1,priority=0,in_port=2,actions=drop flow modify table=1,priority=0,in_port=3,actions=group:10 $ ovs-ofctl bundle br-test flow-modify.txt -OOpenflow13 First flow rule will be modified since it is a valid rule. However second rule is invalid since no group with id 10 exists. Bundle commit tries to revert (insert) the first rule to old flow which results in ovs_assert at ofproto_rule_insert__() since old rule->state = RULE_REMOVED. Signed-off-by: Vishal Deep Ajmera <[email protected]> Signed-off-by: Ben Pfaff <[email protected]> CWE ID: CWE-617 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Extension::LoadExtent(const DictionaryValue* manifest, const char* key, URLPatternSet* extent, const char* list_error, const char* value_error, URLPattern::ParseOption parse_strictness, std::string* error) { Value* temp = NULL; if (!manifest->Get(key, &temp)) return true; if (temp->GetType() != Value::TYPE_LIST) { *error = list_error; return false; } ListValue* pattern_list = static_cast<ListValue*>(temp); for (size_t i = 0; i < pattern_list->GetSize(); ++i) { std::string pattern_string; if (!pattern_list->GetString(i, &pattern_string)) { *error = ExtensionErrorUtils::FormatErrorMessage(value_error, base::UintToString(i), errors::kExpectString); return false; } URLPattern pattern(kValidWebExtentSchemes); URLPattern::ParseResult parse_result = pattern.Parse(pattern_string, parse_strictness); if (parse_result == URLPattern::PARSE_ERROR_EMPTY_PATH) { pattern_string += "/"; parse_result = pattern.Parse(pattern_string, parse_strictness); } if (parse_result != URLPattern::PARSE_SUCCESS) { *error = ExtensionErrorUtils::FormatErrorMessage( value_error, base::UintToString(i), URLPattern::GetParseResultString(parse_result)); return false; } if (pattern.match_all_urls()) { *error = ExtensionErrorUtils::FormatErrorMessage( value_error, base::UintToString(i), errors::kCannotClaimAllURLsInExtent); return false; } if (pattern.host().empty()) { *error = ExtensionErrorUtils::FormatErrorMessage( value_error, base::UintToString(i), errors::kCannotClaimAllHostsInExtent); return false; } if (pattern.path().find('*') != std::string::npos) { *error = ExtensionErrorUtils::FormatErrorMessage( value_error, base::UintToString(i), errors::kNoWildCardsInPaths); return false; } pattern.SetPath(pattern.path() + '*'); extent->AddPattern(pattern); } return true; } 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 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static struct ip_options *tcp_v4_save_options(struct sock *sk, struct sk_buff *skb) { struct ip_options *opt = &(IPCB(skb)->opt); struct ip_options *dopt = NULL; if (opt && opt->optlen) { int opt_size = optlength(opt); dopt = kmalloc(opt_size, GFP_ATOMIC); if (dopt) { if (ip_options_echo(dopt, skb)) { kfree(dopt); dopt = NULL; } } } return dopt; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: parse_previous_duplicate_name (const char *name, char **name_base, const char **suffix, int *count) { const char *tag; g_assert (name[0] != '\0'); *suffix = eel_filename_get_extension_offset (name); if (*suffix == NULL || (*suffix)[1] == '\0') { /* no suffix */ *suffix = ""; } tag = strstr (name, COPY_DUPLICATE_TAG); if (tag != NULL) { if (tag > *suffix) { /* handle case "foo. (copy)" */ *suffix = ""; } *name_base = extract_string_until (name, tag); *count = 1; return; } tag = strstr (name, ANOTHER_COPY_DUPLICATE_TAG); if (tag != NULL) { if (tag > *suffix) { /* handle case "foo. (another copy)" */ *suffix = ""; } *name_base = extract_string_until (name, tag); *count = 2; return; } /* Check to see if we got one of st, nd, rd, th. */ tag = strstr (name, X11TH_COPY_DUPLICATE_TAG); if (tag == NULL) { tag = strstr (name, X12TH_COPY_DUPLICATE_TAG); } if (tag == NULL) { tag = strstr (name, X13TH_COPY_DUPLICATE_TAG); } if (tag == NULL) { tag = strstr (name, ST_COPY_DUPLICATE_TAG); } if (tag == NULL) { tag = strstr (name, ND_COPY_DUPLICATE_TAG); } if (tag == NULL) { tag = strstr (name, RD_COPY_DUPLICATE_TAG); } if (tag == NULL) { tag = strstr (name, TH_COPY_DUPLICATE_TAG); } /* If we got one of st, nd, rd, th, fish out the duplicate number. */ if (tag != NULL) { /* localizers: opening parentheses to match the "th copy)" string */ tag = strstr (name, _(" (")); if (tag != NULL) { if (tag > *suffix) { /* handle case "foo. (22nd copy)" */ *suffix = ""; } *name_base = extract_string_until (name, tag); /* localizers: opening parentheses of the "th copy)" string */ if (sscanf (tag, _(" (%'d"), count) == 1) { if (*count < 1 || *count > 1000000) { /* keep the count within a reasonable range */ *count = 0; } return; } *count = 0; return; } } *count = 0; if (**suffix != '\0') { *name_base = extract_string_until (name, *suffix); } else { *name_base = g_strdup (name); } } 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 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: init_data(const char *conf_file, vector_t * (*init_keywords) (void)) { /* Init Keywords structure */ keywords = vector_alloc(); (*init_keywords) (); /* Add out standard definitions */ set_std_definitions(); #if DUMP_KEYWORDS /* Dump configuration */ dump_keywords(keywords, 0, NULL); #endif /* Stream handling */ current_keywords = keywords; current_file_name = NULL; current_file_line_no = 0; /* A parent process may have left these set */ block_depth = 0; kw_level = 0; register_null_strvec_handler(null_strvec); read_conf_file(conf_file); unregister_null_strvec_handler(); /* Report if there are missing '}'s. If there are missing '{'s it will already have been reported */ if (block_depth > 0) report_config_error(CONFIG_MISSING_EOB, "There are %d missing '%s's or extra '%s's", block_depth, EOB, BOB); /* We have finished reading the configuration files, so any configuration * errors report from now mustn't include a reference to the config file name */ current_file_line_no = 0; /* Close the password database if it was opened */ endpwent(); free_keywords(keywords); free_parser_data(); #ifdef _WITH_VRRP_ clear_rt_names(); #endif notify_resource_release(); } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59 Output:
0