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: void MediaStreamManager::StopStreamDevice(int render_process_id, int render_frame_id, const std::string& device_id, int session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "StopStreamDevice({render_frame_id = " << render_frame_id << "} " << ", {device_id = " << device_id << "}, session_id = " << session_id << "})"; Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189 Target: 1 Example 2: Code: bool InputType::CanSetValue(const String&) { return 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: 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 snd_timer_global_free(struct snd_timer *timer) { return snd_timer_free(timer); } Commit Message: ALSA: timer: Fix leak in events via snd_timer_user_tinterrupt The stack object “r1” has a total size of 32 bytes. Its field “event” and “val” both contain 4 bytes padding. These 8 bytes padding bytes are sent to user without being initialized. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> 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: static int generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen, u8 *dst, unsigned int dlen) { return crypto_old_rng_alg(tfm)->rng_make_random(tfm, dst, dlen); } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: bsg_map_hdr(struct bsg_device *bd, struct sg_io_v4 *hdr, fmode_t has_write_perm, u8 *sense) { struct request_queue *q = bd->queue; struct request *rq, *next_rq = NULL; int ret, rw; unsigned int dxfer_len; void __user *dxferp = NULL; struct bsg_class_device *bcd = &q->bsg_dev; /* if the LLD has been removed then the bsg_unregister_queue will * eventually be called and the class_dev was freed, so we can no * longer use this request_queue. Return no such address. */ if (!bcd->class_dev) return ERR_PTR(-ENXIO); dprintk("map hdr %llx/%u %llx/%u\n", (unsigned long long) hdr->dout_xferp, hdr->dout_xfer_len, (unsigned long long) hdr->din_xferp, hdr->din_xfer_len); ret = bsg_validate_sgv4_hdr(hdr, &rw); if (ret) return ERR_PTR(ret); /* * map scatter-gather elements separately and string them to request */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) return rq; blk_rq_set_block_pc(rq); ret = blk_fill_sgv4_hdr_rq(q, rq, hdr, bd, has_write_perm); if (ret) goto out; if (rw == WRITE && hdr->din_xfer_len) { if (!test_bit(QUEUE_FLAG_BIDI, &q->queue_flags)) { ret = -EOPNOTSUPP; goto out; } next_rq = blk_get_request(q, READ, GFP_KERNEL); if (IS_ERR(next_rq)) { ret = PTR_ERR(next_rq); next_rq = NULL; goto out; } rq->next_rq = next_rq; next_rq->cmd_type = rq->cmd_type; dxferp = (void __user *)(unsigned long)hdr->din_xferp; ret = blk_rq_map_user(q, next_rq, NULL, dxferp, hdr->din_xfer_len, GFP_KERNEL); if (ret) goto out; } if (hdr->dout_xfer_len) { dxfer_len = hdr->dout_xfer_len; dxferp = (void __user *)(unsigned long)hdr->dout_xferp; } else if (hdr->din_xfer_len) { dxfer_len = hdr->din_xfer_len; dxferp = (void __user *)(unsigned long)hdr->din_xferp; } else dxfer_len = 0; if (dxfer_len) { ret = blk_rq_map_user(q, rq, NULL, dxferp, dxfer_len, GFP_KERNEL); if (ret) goto out; } rq->sense = sense; rq->sense_len = 0; return rq; out: if (rq->cmd != rq->__cmd) kfree(rq->cmd); blk_put_request(rq); if (next_rq) { blk_rq_unmap_user(next_rq->bio); blk_put_request(next_rq); } return ERR_PTR(ret); } Commit Message: sg_write()/bsg_write() is not fit to be called under KERNEL_DS Both damn things interpret userland pointers embedded into the payload; worse, they are actually traversing those. Leaving aside the bad API design, this is very much _not_ safe to call with KERNEL_DS. Bail out early if that happens. Cc: [email protected] Signed-off-by: Al Viro <[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: void __scm_destroy(struct scm_cookie *scm) { struct scm_fp_list *fpl = scm->fp; int i; if (fpl) { scm->fp = NULL; for (i=fpl->count-1; i>=0; i--) fput(fpl->fp[i]); kfree(fpl); } } Commit Message: unix: correctly track in-flight fds in sending process user_struct The commit referenced in the Fixes tag incorrectly accounted the number of in-flight fds over a unix domain socket to the original opener of the file-descriptor. This allows another process to arbitrary deplete the original file-openers resource limit for the maximum of open files. Instead the sending processes and its struct cred should be credited. To do so, we add a reference counted struct user_struct pointer to the scm_fp_list and use it to account for the number of inflight unix fds. Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets") Reported-by: David Herrmann <[email protected]> Cc: David Herrmann <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: Linus Torvalds <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Hannes Frederic Sowa <[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: DECLAREcpFunc(cpSeparate2ContigByRow) { tsize_t scanlinesizein = TIFFScanlineSize(in); tsize_t scanlinesizeout = TIFFScanlineSize(out); tdata_t inbuf; tdata_t outbuf; register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; inbuf = _TIFFmalloc(scanlinesizein); outbuf = _TIFFmalloc(scanlinesizeout); if (!inbuf || !outbuf) goto bad; _TIFFmemset(inbuf, 0, scanlinesizein); _TIFFmemset(outbuf, 0, scanlinesizeout); for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { if (TIFFReadScanline(in, inbuf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = (uint8*)inbuf; outp = ((uint8*)outbuf) + s; for (n = imagewidth; n-- > 0;) { *outp = *inp++; outp += spp; } } if (TIFFWriteScanline(out, outbuf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } Commit Message: * tools/tiffcp.c: error out cleanly in cpContig2SeparateByRow and cpSeparate2ContigByRow if BitsPerSample != 8 to avoid heap based overflow. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2656 and http://bugzilla.maptools.org/show_bug.cgi?id=2657 CWE ID: CWE-119 Target: 1 Example 2: Code: static int slab_mem_going_offline_callback(void *arg) { struct kmem_cache *s; down_read(&slub_lock); list_for_each_entry(s, &slab_caches, list) kmem_cache_shrink(s); up_read(&slub_lock); return 0; } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[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: GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox); if (e) { return e; } if (!((GF_DataInformationBox *)s)->dref) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n")); ((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF); } return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) 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: void UkmPageLoadMetricsObserver::RecordPageLoadExtraInfoMetrics( const page_load_metrics::PageLoadExtraInfo& info, base::TimeTicks app_background_time) { ukm::builders::PageLoad builder(info.source_id); base::Optional<base::TimeDelta> foreground_duration = page_load_metrics::GetInitialForegroundDuration(info, app_background_time); if (foreground_duration) { builder.SetPageTiming_ForegroundDuration( foreground_duration.value().InMilliseconds()); } metrics::SystemProfileProto::Network::EffectiveConnectionType proto_effective_connection_type = metrics::ConvertEffectiveConnectionType(effective_connection_type_); if (proto_effective_connection_type != metrics::SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { builder.SetNet_EffectiveConnectionType2_OnNavigationStart( static_cast<int64_t>(proto_effective_connection_type)); } if (http_response_code_) { builder.SetNet_HttpResponseCode( static_cast<int64_t>(http_response_code_.value())); } if (http_rtt_estimate_) { builder.SetNet_HttpRttEstimate_OnNavigationStart( static_cast<int64_t>(http_rtt_estimate_.value().InMilliseconds())); } if (transport_rtt_estimate_) { builder.SetNet_TransportRttEstimate_OnNavigationStart( static_cast<int64_t>(transport_rtt_estimate_.value().InMilliseconds())); } if (downstream_kbps_estimate_) { builder.SetNet_DownstreamKbpsEstimate_OnNavigationStart( static_cast<int64_t>(downstream_kbps_estimate_.value())); } builder.SetNavigation_PageTransition(static_cast<int64_t>(page_transition_)); builder.SetNavigation_PageEndReason( static_cast<int64_t>(info.page_end_reason)); if (info.did_commit && was_cached_) { builder.SetWasCached(1); } builder.Record(ukm::UkmRecorder::Get()); } Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation. Also refactor UkmPageLoadMetricsObserver to use this new boolean to report the user initiated metric in RecordPageLoadExtraInfoMetrics, so that it works correctly in the case when the page load failed. Bug: 925104 Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff Reviewed-on: https://chromium-review.googlesource.com/c/1450460 Commit-Queue: Annie Sullivan <[email protected]> Reviewed-by: Bryan McQuade <[email protected]> Cr-Commit-Position: refs/heads/master@{#630870} CWE ID: CWE-79 Target: 1 Example 2: Code: int32_t Parcel::readInt32() const { return readAligned<int32_t>(); } Commit Message: Disregard alleged binder entities beyond parcel bounds When appending one parcel's contents to another, ignore binder objects within the source Parcel that appear to lie beyond the formal bounds of that Parcel's data buffer. Bug 17312693 Change-Id: If592a260f3fcd9a56fc160e7feb2c8b44c73f514 (cherry picked from commit 27182be9f20f4f5b48316666429f09b9ecc1f22e) 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: const AtomicString& AXObject::getAttribute( const QualifiedName& attribute) const { Node* elementNode = getNode(); if (!elementNode) return nullAtom; if (!elementNode->isElementNode()) return nullAtom; Element* element = toElement(elementNode); return element->fastGetAttribute(attribute); } 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 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: error::Error GLES2DecoderPassthroughImpl::DoBeginQueryEXT( GLenum target, GLuint id, int32_t sync_shm_id, uint32_t sync_shm_offset) { GLuint service_id = GetQueryServiceID(id, &query_id_map_); QueryInfo* query_info = &query_info_map_[service_id]; scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id); if (!buffer) return error::kInvalidArguments; QuerySync* sync = static_cast<QuerySync*>( buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync))); if (!sync) return error::kOutOfBounds; if (IsEmulatedQueryTarget(target)) { if (active_queries_.find(target) != active_queries_.end()) { InsertError(GL_INVALID_OPERATION, "Query already active on target."); return error::kNoError; } if (id == 0) { InsertError(GL_INVALID_OPERATION, "Query id is 0."); return error::kNoError; } if (query_info->type != GL_NONE && query_info->type != target) { InsertError(GL_INVALID_OPERATION, "Query type does not match the target."); return error::kNoError; } } else { CheckErrorCallbackState(); api()->glBeginQueryFn(target, service_id); if (CheckErrorCallbackState()) { return error::kNoError; } } query_info->type = target; RemovePendingQuery(service_id); ActiveQuery query; query.service_id = service_id; query.shm = std::move(buffer); query.sync = sync; active_queries_[target] = std::move(query); return error::kNoError; } 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 Target: 1 Example 2: Code: __perf_event_account_interrupt(struct perf_event *event, int throttle) { struct hw_perf_event *hwc = &event->hw; int ret = 0; u64 seq; seq = __this_cpu_read(perf_throttled_seq); if (seq != hwc->interrupts_seq) { hwc->interrupts_seq = seq; hwc->interrupts = 1; } else { hwc->interrupts++; if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) { __this_cpu_inc(perf_throttled_count); tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); hwc->interrupts = MAX_INTERRUPTS; perf_log_throttle(event, 0); ret = 1; } } if (event->attr.freq) { u64 now = perf_clock(); s64 delta = now - hwc->freq_time_stamp; hwc->freq_time_stamp = now; if (delta > 0 && delta < 2*TICK_NSEC) perf_adjust_period(event, delta, hwc->last_period, true); } return ret; } 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 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: expand_string_internal(uschar *string, BOOL ket_ends, uschar **left, BOOL skipping, BOOL honour_dollar, BOOL *resetok_p) { int ptr = 0; int size = Ustrlen(string)+ 64; int item_type; uschar *yield = store_get(size); uschar *s = string; uschar *save_expand_nstring[EXPAND_MAXN+1]; int save_expand_nlength[EXPAND_MAXN+1]; BOOL resetok = TRUE; expand_string_forcedfail = FALSE; expand_string_message = US""; while (*s != 0) { uschar *value; uschar name[256]; /* \ escapes the next character, which must exist, or else the expansion fails. There's a special escape, \N, which causes copying of the subject verbatim up to the next \N. Otherwise, the escapes are the standard set. */ if (*s == '\\') { if (s[1] == 0) { expand_string_message = US"\\ at end of string"; goto EXPAND_FAILED; } if (s[1] == 'N') { uschar *t = s + 2; for (s = t; *s != 0; s++) if (*s == '\\' && s[1] == 'N') break; yield = string_cat(yield, &size, &ptr, t, s - t); if (*s != 0) s += 2; } else { uschar ch[1]; ch[0] = string_interpret_escape(&s); s++; yield = string_cat(yield, &size, &ptr, ch, 1); } continue; } /*{*/ /* Anything other than $ is just copied verbatim, unless we are looking for a terminating } character. */ /*{*/ if (ket_ends && *s == '}') break; if (*s != '$' || !honour_dollar) { yield = string_cat(yield, &size, &ptr, s++, 1); continue; } /* No { after the $ - must be a plain name or a number for string match variable. There has to be a fudge for variables that are the names of header fields preceded by "$header_" because header field names can contain any printing characters except space and colon. For those that don't like typing this much, "$h_" is a synonym for "$header_". A non-existent header yields a NULL value; nothing is inserted. */ /*}*/ if (isalpha((*(++s)))) { int len; int newsize = 0; s = read_name(name, sizeof(name), s, US"_"); /* If this is the first thing to be expanded, release the pre-allocated buffer. */ if (ptr == 0 && yield != NULL) { if (resetok) store_reset(yield); yield = NULL; size = 0; } /* Header */ if (Ustrncmp(name, "h_", 2) == 0 || Ustrncmp(name, "rh_", 3) == 0 || Ustrncmp(name, "bh_", 3) == 0 || Ustrncmp(name, "header_", 7) == 0 || Ustrncmp(name, "rheader_", 8) == 0 || Ustrncmp(name, "bheader_", 8) == 0) { BOOL want_raw = (name[0] == 'r')? TRUE : FALSE; uschar *charset = (name[0] == 'b')? NULL : headers_charset; s = read_header_name(name, sizeof(name), s); value = find_header(name, FALSE, &newsize, want_raw, charset); /* If we didn't find the header, and the header contains a closing brace character, this may be a user error where the terminating colon has been omitted. Set a flag to adjust the error message in this case. But there is no error here - nothing gets inserted. */ if (value == NULL) { if (Ustrchr(name, '}') != NULL) malformed_header = TRUE; continue; } } /* Variable */ else { value = find_variable(name, FALSE, skipping, &newsize); if (value == NULL) { expand_string_message = string_sprintf("unknown variable name \"%s\"", name); check_variable_error_message(name); goto EXPAND_FAILED; } } /* If the data is known to be in a new buffer, newsize will be set to the size of that buffer. If this is the first thing in an expansion string, yield will be NULL; just point it at the new store instead of copying. Many expansion strings contain just one reference, so this is a useful optimization, especially for humungous headers. */ len = Ustrlen(value); if (yield == NULL && newsize != 0) { yield = value; size = newsize; ptr = len; } else yield = string_cat(yield, &size, &ptr, value, len); continue; } if (isdigit(*s)) { int n; s = read_number(&n, s); if (n >= 0 && n <= expand_nmax) yield = string_cat(yield, &size, &ptr, expand_nstring[n], expand_nlength[n]); continue; } /* Otherwise, if there's no '{' after $ it's an error. */ /*}*/ if (*s != '{') /*}*/ { expand_string_message = US"$ not followed by letter, digit, or {"; /*}*/ goto EXPAND_FAILED; } /* After { there can be various things, but they all start with an initial word, except for a number for a string match variable. */ if (isdigit((*(++s)))) { int n; s = read_number(&n, s); /*{*/ if (*s++ != '}') { /*{*/ expand_string_message = US"} expected after number"; goto EXPAND_FAILED; } if (n >= 0 && n <= expand_nmax) yield = string_cat(yield, &size, &ptr, expand_nstring[n], expand_nlength[n]); continue; } if (!isalpha(*s)) { expand_string_message = US"letter or digit expected after ${"; /*}*/ goto EXPAND_FAILED; } /* Allow "-" in names to cater for substrings with negative arguments. Since we are checking for known names after { this is OK. */ s = read_name(name, sizeof(name), s, US"_-"); item_type = chop_match(name, item_table, sizeof(item_table)/sizeof(uschar *)); switch(item_type) { /* Call an ACL from an expansion. We feed data in via $acl_arg1 - $acl_arg9. If the ACL returns accept or reject we return content set by "message =" There is currently no limit on recursion; this would have us call acl_check_internal() directly and get a current level from somewhere. See also the acl expansion condition ECOND_ACL and the traditional acl modifier ACLC_ACL. Assume that the function has side-effects on the store that must be preserved. */ case EITEM_ACL: /* ${acl {name} {arg1}{arg2}...} */ { uschar *sub[10]; /* name + arg1-arg9 (which must match number of acl_arg[]) */ uschar *user_msg; switch(read_subs(sub, 10, 1, &s, skipping, TRUE, US"acl", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (skipping) continue; resetok = FALSE; switch(eval_acl(sub, sizeof(sub)/sizeof(*sub), &user_msg)) { case OK: case FAIL: DEBUG(D_expand) debug_printf("acl expansion yield: %s\n", user_msg); if (user_msg) yield = string_cat(yield, &size, &ptr, user_msg, Ustrlen(user_msg)); continue; case DEFER: expand_string_forcedfail = TRUE; default: expand_string_message = string_sprintf("error from acl \"%s\"", sub[0]); goto EXPAND_FAILED; } } /* Handle conditionals - preserve the values of the numerical expansion variables in case they get changed by a regular expression match in the condition. If not, they retain their external settings. At the end of this "if" section, they get restored to their previous values. */ case EITEM_IF: { BOOL cond = FALSE; uschar *next_s; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); while (isspace(*s)) s++; next_s = eval_condition(s, &resetok, skipping? NULL : &cond); if (next_s == NULL) goto EXPAND_FAILED; /* message already set */ DEBUG(D_expand) debug_printf("condition: %.*s\n result: %s\n", (int)(next_s - s), s, cond? "true" : "false"); s = next_s; /* The handling of "yes" and "no" result strings is now in a separate function that is also used by ${lookup} and ${extract} and ${run}. */ switch(process_yesno( skipping, /* were previously skipping */ cond, /* success/failure indicator */ lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"if", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* Restore external setting of expansion variables for continuation at this level. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* Handle database lookups unless locked out. If "skipping" is TRUE, we are expanding an internal string that isn't actually going to be used. All we need to do is check the syntax, so don't do a lookup at all. Preserve the values of the numerical expansion variables in case they get changed by a partial lookup. If not, they retain their external settings. At the end of this "lookup" section, they get restored to their previous values. */ case EITEM_LOOKUP: { int stype, partial, affixlen, starflags; int expand_setup = 0; int nameptr = 0; uschar *key, *filename, *affix; uschar *save_lookup_value = lookup_value; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); if ((expand_forbid & RDO_LOOKUP) != 0) { expand_string_message = US"lookup expansions are not permitted"; goto EXPAND_FAILED; } /* Get the key we are to look up for single-key+file style lookups. Otherwise set the key NULL pro-tem. */ while (isspace(*s)) s++; if (*s == '{') /*}*/ { key = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (key == NULL) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; } else key = NULL; /* Find out the type of database */ if (!isalpha(*s)) { expand_string_message = US"missing lookup type"; goto EXPAND_FAILED; } /* The type is a string that may contain special characters of various kinds. Allow everything except space or { to appear; the actual content is checked by search_findtype_partial. */ /*}*/ while (*s != 0 && *s != '{' && !isspace(*s)) /*}*/ { if (nameptr < sizeof(name) - 1) name[nameptr++] = *s; s++; } name[nameptr] = 0; while (isspace(*s)) s++; /* Now check for the individual search type and any partial or default options. Only those types that are actually in the binary are valid. */ stype = search_findtype_partial(name, &partial, &affix, &affixlen, &starflags); if (stype < 0) { expand_string_message = search_error_message; goto EXPAND_FAILED; } /* Check that a key was provided for those lookup types that need it, and was not supplied for those that use the query style. */ if (!mac_islookup(stype, lookup_querystyle|lookup_absfilequery)) { if (key == NULL) { expand_string_message = string_sprintf("missing {key} for single-" "key \"%s\" lookup", name); goto EXPAND_FAILED; } } else { if (key != NULL) { expand_string_message = string_sprintf("a single key was given for " "lookup type \"%s\", which is not a single-key lookup type", name); goto EXPAND_FAILED; } } /* Get the next string in brackets and expand it. It is the file name for single-key+file lookups, and the whole query otherwise. In the case of queries that also require a file name (e.g. sqlite), the file name comes first. */ if (*s != '{') goto EXPAND_FAILED_CURLY; filename = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (filename == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; /* If this isn't a single-key+file lookup, re-arrange the variables to be appropriate for the search_ functions. For query-style lookups, there is just a "key", and no file name. For the special query-style + file types, the query (i.e. "key") starts with a file name. */ if (key == NULL) { while (isspace(*filename)) filename++; key = filename; if (mac_islookup(stype, lookup_querystyle)) { filename = NULL; } else { if (*filename != '/') { expand_string_message = string_sprintf( "absolute file name expected for \"%s\" lookup", name); goto EXPAND_FAILED; } while (*key != 0 && !isspace(*key)) key++; if (*key != 0) *key++ = 0; } } /* If skipping, don't do the next bit - just lookup_value == NULL, as if the entry was not found. Note that there is no search_close() function. Files are left open in case of re-use. At suitable places in higher logic, search_tidyup() is called to tidy all open files. This can save opening the same file several times. However, files may also get closed when others are opened, if too many are open at once. The rule is that a handle should not be used after a second search_open(). Request that a partial search sets up $1 and maybe $2 by passing expand_setup containing zero. If its value changes, reset expand_nmax, since new variables will have been set. Note that at the end of this "lookup" section, the old numeric variables are restored. */ if (skipping) lookup_value = NULL; else { void *handle = search_open(filename, stype, 0, NULL, NULL); if (handle == NULL) { expand_string_message = search_error_message; goto EXPAND_FAILED; } lookup_value = search_find(handle, filename, key, partial, affix, affixlen, starflags, &expand_setup); if (search_find_defer) { expand_string_message = string_sprintf("lookup of \"%s\" gave DEFER: %s", string_printing2(key, FALSE), search_error_message); goto EXPAND_FAILED; } if (expand_setup > 0) expand_nmax = expand_setup; } /* The handling of "yes" and "no" result strings is now in a separate function that is also used by ${if} and ${extract}. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"lookup", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* Restore external setting of expansion variables for carrying on at this level, and continue. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* If Perl support is configured, handle calling embedded perl subroutines, unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}} or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS arguments (defined below). */ #define EXIM_PERL_MAX_ARGS 8 case EITEM_PERL: #ifndef EXIM_PERL expand_string_message = US"\"${perl\" encountered, but this facility " /*}*/ "is not included in this binary"; goto EXPAND_FAILED; #else /* EXIM_PERL */ { uschar *sub_arg[EXIM_PERL_MAX_ARGS + 2]; uschar *new_yield; if ((expand_forbid & RDO_PERL) != 0) { expand_string_message = US"Perl calls are not permitted"; goto EXPAND_FAILED; } switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE, US"perl", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Start the interpreter if necessary */ if (!opt_perl_started) { uschar *initerror; if (opt_perl_startup == NULL) { expand_string_message = US"A setting of perl_startup is needed when " "using the Perl interpreter"; goto EXPAND_FAILED; } DEBUG(D_any) debug_printf("Starting Perl interpreter\n"); initerror = init_perl(opt_perl_startup); if (initerror != NULL) { expand_string_message = string_sprintf("error in perl_startup code: %s\n", initerror); goto EXPAND_FAILED; } opt_perl_started = TRUE; } /* Call the function */ sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL; new_yield = call_perl_cat(yield, &size, &ptr, &expand_string_message, sub_arg[0], sub_arg + 1); /* NULL yield indicates failure; if the message pointer has been set to NULL, the yield was undef, indicating a forced failure. Otherwise the message will indicate some kind of Perl error. */ if (new_yield == NULL) { if (expand_string_message == NULL) { expand_string_message = string_sprintf("Perl subroutine \"%s\" returned undef to force " "failure", sub_arg[0]); expand_string_forcedfail = TRUE; } goto EXPAND_FAILED; } /* Yield succeeded. Ensure forcedfail is unset, just in case it got set during a callback from Perl. */ expand_string_forcedfail = FALSE; yield = new_yield; continue; } #endif /* EXIM_PERL */ /* Transform email address to "prvs" scheme to use as BATV-signed return path */ case EITEM_PRVS: { uschar *sub_arg[3]; uschar *p,*domain; switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* sub_arg[0] is the address */ domain = Ustrrchr(sub_arg[0],'@'); if ( (domain == NULL) || (domain == sub_arg[0]) || (Ustrlen(domain) == 1) ) { expand_string_message = US"prvs first argument must be a qualified email address"; goto EXPAND_FAILED; } /* Calculate the hash. The second argument must be a single-digit key number, or unset. */ if (sub_arg[2] != NULL && (!isdigit(sub_arg[2][0]) || sub_arg[2][1] != 0)) { expand_string_message = US"prvs second argument must be a single digit"; goto EXPAND_FAILED; } p = prvs_hmac_sha1(sub_arg[0],sub_arg[1],sub_arg[2],prvs_daystamp(7)); if (p == NULL) { expand_string_message = US"prvs hmac-sha1 conversion failed"; goto EXPAND_FAILED; } /* Now separate the domain from the local part */ *domain++ = '\0'; yield = string_cat(yield,&size,&ptr,US"prvs=",5); string_cat(yield,&size,&ptr,(sub_arg[2] != NULL) ? sub_arg[2] : US"0", 1); string_cat(yield,&size,&ptr,prvs_daystamp(7),3); string_cat(yield,&size,&ptr,p,6); string_cat(yield,&size,&ptr,US"=",1); string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0])); string_cat(yield,&size,&ptr,US"@",1); string_cat(yield,&size,&ptr,domain,Ustrlen(domain)); continue; } /* Check a prvs-encoded address for validity */ case EITEM_PRVSCHECK: { uschar *sub_arg[3]; int mysize = 0, myptr = 0; const pcre *re; uschar *p; /* TF: Ugliness: We want to expand parameter 1 first, then set up expansion variables that are used in the expansion of parameter 2. So we clone the string for the first expansion, where we only expand parameter 1. PH: Actually, that isn't necessary. The read_subs() function is designed to work this way for the ${if and ${lookup expansions. I've tidied the code. */ /* Reset expansion variables */ prvscheck_result = NULL; prvscheck_address = NULL; prvscheck_keynum = NULL; switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } re = regex_must_compile(US"^prvs\\=([0-9])([0-9]{3})([A-F0-9]{6})\\=(.+)\\@(.+)$", TRUE,FALSE); if (regex_match_and_setup(re,sub_arg[0],0,-1)) { uschar *local_part = string_copyn(expand_nstring[4],expand_nlength[4]); uschar *key_num = string_copyn(expand_nstring[1],expand_nlength[1]); uschar *daystamp = string_copyn(expand_nstring[2],expand_nlength[2]); uschar *hash = string_copyn(expand_nstring[3],expand_nlength[3]); uschar *domain = string_copyn(expand_nstring[5],expand_nlength[5]); DEBUG(D_expand) debug_printf("prvscheck localpart: %s\n", local_part); DEBUG(D_expand) debug_printf("prvscheck key number: %s\n", key_num); DEBUG(D_expand) debug_printf("prvscheck daystamp: %s\n", daystamp); DEBUG(D_expand) debug_printf("prvscheck hash: %s\n", hash); DEBUG(D_expand) debug_printf("prvscheck domain: %s\n", domain); /* Set up expansion variables */ prvscheck_address = string_cat(NULL, &mysize, &myptr, local_part, Ustrlen(local_part)); string_cat(prvscheck_address,&mysize,&myptr,US"@",1); string_cat(prvscheck_address,&mysize,&myptr,domain,Ustrlen(domain)); prvscheck_address[myptr] = '\0'; prvscheck_keynum = string_copy(key_num); /* Now expand the second argument */ switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Now we have the key and can check the address. */ p = prvs_hmac_sha1(prvscheck_address, sub_arg[0], prvscheck_keynum, daystamp); if (p == NULL) { expand_string_message = US"hmac-sha1 conversion failed"; goto EXPAND_FAILED; } DEBUG(D_expand) debug_printf("prvscheck: received hash is %s\n", hash); DEBUG(D_expand) debug_printf("prvscheck: own hash is %s\n", p); if (Ustrcmp(p,hash) == 0) { /* Success, valid BATV address. Now check the expiry date. */ uschar *now = prvs_daystamp(0); unsigned int inow = 0,iexpire = 1; (void)sscanf(CS now,"%u",&inow); (void)sscanf(CS daystamp,"%u",&iexpire); /* When "iexpire" is < 7, a "flip" has occured. Adjust "inow" accordingly. */ if ( (iexpire < 7) && (inow >= 993) ) inow = 0; if (iexpire >= inow) { prvscheck_result = US"1"; DEBUG(D_expand) debug_printf("prvscheck: success, $pvrs_result set to 1\n"); } else { prvscheck_result = NULL; DEBUG(D_expand) debug_printf("prvscheck: signature expired, $pvrs_result unset\n"); } } else { prvscheck_result = NULL; DEBUG(D_expand) debug_printf("prvscheck: hash failure, $pvrs_result unset\n"); } /* Now expand the final argument. We leave this till now so that it can include $prvscheck_result. */ switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (sub_arg[0] == NULL || *sub_arg[0] == '\0') yield = string_cat(yield,&size,&ptr,prvscheck_address,Ustrlen(prvscheck_address)); else yield = string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0])); /* Reset the "internal" variables afterwards, because they are in dynamic store that will be reclaimed if the expansion succeeded. */ prvscheck_address = NULL; prvscheck_keynum = NULL; } else { /* Does not look like a prvs encoded address, return the empty string. We need to make sure all subs are expanded first, so as to skip over the entire item. */ switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } } continue; } /* Handle "readfile" to insert an entire file */ case EITEM_READFILE: { FILE *f; uschar *sub_arg[2]; if ((expand_forbid & RDO_READFILE) != 0) { expand_string_message = US"file insertions are not permitted"; goto EXPAND_FAILED; } switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"readfile", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Open the file and read it */ f = Ufopen(sub_arg[0], "rb"); if (f == NULL) { expand_string_message = string_open_failed(errno, "%s", sub_arg[0]); goto EXPAND_FAILED; } yield = cat_file(f, yield, &size, &ptr, sub_arg[1]); (void)fclose(f); continue; } /* Handle "readsocket" to insert data from a Unix domain socket */ case EITEM_READSOCK: { int fd; int timeout = 5; int save_ptr = ptr; FILE *f; struct sockaddr_un sockun; /* don't call this "sun" ! */ uschar *arg; uschar *sub_arg[4]; if ((expand_forbid & RDO_READSOCK) != 0) { expand_string_message = US"socket insertions are not permitted"; goto EXPAND_FAILED; } /* Read up to 4 arguments, but don't do the end of item check afterwards, because there may be a string for expansion on failure. */ switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US"readsocket", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: /* Won't occur: no end check */ case 3: goto EXPAND_FAILED; } /* Sort out timeout, if given */ if (sub_arg[2] != NULL) { timeout = readconf_readtime(sub_arg[2], 0, FALSE); if (timeout < 0) { expand_string_message = string_sprintf("bad time value %s", sub_arg[2]); goto EXPAND_FAILED; } } else sub_arg[3] = NULL; /* No eol if no timeout */ /* If skipping, we don't actually do anything. Otherwise, arrange to connect to either an IP or a Unix socket. */ if (!skipping) { /* Handle an IP (internet) domain */ if (Ustrncmp(sub_arg[0], "inet:", 5) == 0) { int port; uschar *server_name = sub_arg[0] + 5; uschar *port_name = Ustrrchr(server_name, ':'); /* Sort out the port */ if (port_name == NULL) { expand_string_message = string_sprintf("missing port for readsocket %s", sub_arg[0]); goto EXPAND_FAILED; } *port_name++ = 0; /* Terminate server name */ if (isdigit(*port_name)) { uschar *end; port = Ustrtol(port_name, &end, 0); if (end != port_name + Ustrlen(port_name)) { expand_string_message = string_sprintf("invalid port number %s", port_name); goto EXPAND_FAILED; } } else { struct servent *service_info = getservbyname(CS port_name, "tcp"); if (service_info == NULL) { expand_string_message = string_sprintf("unknown port \"%s\"", port_name); goto EXPAND_FAILED; } port = ntohs(service_info->s_port); } if ((fd = ip_connectedsocket(SOCK_STREAM, server_name, port, port, timeout, NULL, &expand_string_message)) < 0) goto SOCK_FAIL; } /* Handle a Unix domain socket */ else { int rc; if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) { expand_string_message = string_sprintf("failed to create socket: %s", strerror(errno)); goto SOCK_FAIL; } sockun.sun_family = AF_UNIX; sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1), sub_arg[0]); sigalrm_seen = FALSE; alarm(timeout); rc = connect(fd, (struct sockaddr *)(&sockun), sizeof(sockun)); alarm(0); if (sigalrm_seen) { expand_string_message = US "socket connect timed out"; goto SOCK_FAIL; } if (rc < 0) { expand_string_message = string_sprintf("failed to connect to socket " "%s: %s", sub_arg[0], strerror(errno)); goto SOCK_FAIL; } } DEBUG(D_expand) debug_printf("connected to socket %s\n", sub_arg[0]); /* Allow sequencing of test actions */ if (running_in_test_harness) millisleep(100); /* Write the request string, if not empty */ if (sub_arg[1][0] != 0) { int len = Ustrlen(sub_arg[1]); DEBUG(D_expand) debug_printf("writing \"%s\" to socket\n", sub_arg[1]); if (write(fd, sub_arg[1], len) != len) { expand_string_message = string_sprintf("request write to socket " "failed: %s", strerror(errno)); goto SOCK_FAIL; } } /* Shut down the sending side of the socket. This helps some servers to recognise that it is their turn to do some work. Just in case some system doesn't have this function, make it conditional. */ #ifdef SHUT_WR shutdown(fd, SHUT_WR); #endif if (running_in_test_harness) millisleep(100); /* Now we need to read from the socket, under a timeout. The function that reads a file can be used. */ f = fdopen(fd, "rb"); sigalrm_seen = FALSE; alarm(timeout); yield = cat_file(f, yield, &size, &ptr, sub_arg[3]); alarm(0); (void)fclose(f); /* After a timeout, we restore the pointer in the result, that is, make sure we add nothing from the socket. */ if (sigalrm_seen) { ptr = save_ptr; expand_string_message = US "socket read timed out"; goto SOCK_FAIL; } } /* The whole thing has worked (or we were skipping). If there is a failure string following, we need to skip it. */ if (*s == '{') { if (expand_string_internal(s+1, TRUE, &s, TRUE, TRUE, &resetok) == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; } if (*s++ != '}') goto EXPAND_FAILED_CURLY; continue; /* Come here on failure to create socket, connect socket, write to the socket, or timeout on reading. If another substring follows, expand and use it. Otherwise, those conditions give expand errors. */ SOCK_FAIL: if (*s != '{') goto EXPAND_FAILED; DEBUG(D_any) debug_printf("%s\n", expand_string_message); arg = expand_string_internal(s+1, TRUE, &s, FALSE, TRUE, &resetok); if (arg == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, arg, Ustrlen(arg)); if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; if (*s++ != '}') goto EXPAND_FAILED_CURLY; continue; } /* Handle "run" to execute a program. */ case EITEM_RUN: { FILE *f; uschar *arg; uschar **argv; pid_t pid; int fd_in, fd_out; int lsize = 0; int lptr = 0; if ((expand_forbid & RDO_RUN) != 0) { expand_string_message = US"running a command is not permitted"; goto EXPAND_FAILED; } while (isspace(*s)) s++; if (*s != '{') goto EXPAND_FAILED_CURLY; arg = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (arg == NULL) goto EXPAND_FAILED; while (isspace(*s)) s++; if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (skipping) /* Just pretend it worked when we're skipping */ { runrc = 0; } else { if (!transport_set_up_command(&argv, /* anchor for arg list */ arg, /* raw command */ FALSE, /* don't expand the arguments */ 0, /* not relevant when... */ NULL, /* no transporting address */ US"${run} expansion", /* for error messages */ &expand_string_message)) /* where to put error message */ { goto EXPAND_FAILED; } /* Create the child process, making it a group leader. */ pid = child_open(argv, NULL, 0077, &fd_in, &fd_out, TRUE); if (pid < 0) { expand_string_message = string_sprintf("couldn't create child process: %s", strerror(errno)); goto EXPAND_FAILED; } /* Nothing is written to the standard input. */ (void)close(fd_in); /* Read the pipe to get the command's output into $value (which is kept in lookup_value). Read during execution, so that if the output exceeds the OS pipe buffer limit, we don't block forever. */ f = fdopen(fd_out, "rb"); sigalrm_seen = FALSE; alarm(60); lookup_value = cat_file(f, lookup_value, &lsize, &lptr, NULL); alarm(0); (void)fclose(f); /* Wait for the process to finish, applying the timeout, and inspect its return code for serious disasters. Simple non-zero returns are passed on. */ if (sigalrm_seen == TRUE || (runrc = child_close(pid, 30)) < 0) { if (sigalrm_seen == TRUE || runrc == -256) { expand_string_message = string_sprintf("command timed out"); killpg(pid, SIGKILL); /* Kill the whole process group */ } else if (runrc == -257) expand_string_message = string_sprintf("wait() failed: %s", strerror(errno)); else expand_string_message = string_sprintf("command killed by signal %d", -runrc); goto EXPAND_FAILED; } } /* Process the yes/no strings; $value may be useful in both cases */ switch(process_yesno( skipping, /* were previously skipping */ runrc == 0, /* success/failure indicator */ lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"run", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } continue; } /* Handle character translation for "tr" */ case EITEM_TR: { int oldptr = ptr; int o2m; uschar *sub[3]; switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"tr", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, sub[0], Ustrlen(sub[0])); o2m = Ustrlen(sub[2]) - 1; if (o2m >= 0) for (; oldptr < ptr; oldptr++) { uschar *m = Ustrrchr(sub[1], yield[oldptr]); if (m != NULL) { int o = m - sub[1]; yield[oldptr] = sub[2][(o < o2m)? o : o2m]; } } continue; } /* Handle "hash", "length", "nhash", and "substr" when they are given with expanded arguments. */ case EITEM_HASH: case EITEM_LENGTH: case EITEM_NHASH: case EITEM_SUBSTR: { int i; int len; uschar *ret; int val[2] = { 0, -1 }; uschar *sub[3]; /* "length" takes only 2 arguments whereas the others take 2 or 3. Ensure that sub[2] is set in the ${length } case. */ sub[2] = NULL; switch(read_subs(sub, (item_type == EITEM_LENGTH)? 2:3, 2, &s, skipping, TRUE, name, &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Juggle the arguments if there are only two of them: always move the string to the last position and make ${length{n}{str}} equivalent to ${substr{0}{n}{str}}. See the defaults for val[] above. */ if (sub[2] == NULL) { sub[2] = sub[1]; sub[1] = NULL; if (item_type == EITEM_LENGTH) { sub[1] = sub[0]; sub[0] = NULL; } } for (i = 0; i < 2; i++) { if (sub[i] == NULL) continue; val[i] = (int)Ustrtol(sub[i], &ret, 10); if (*ret != 0 || (i != 0 && val[i] < 0)) { expand_string_message = string_sprintf("\"%s\" is not a%s number " "(in \"%s\" expansion)", sub[i], (i != 0)? " positive" : "", name); goto EXPAND_FAILED; } } ret = (item_type == EITEM_HASH)? compute_hash(sub[2], val[0], val[1], &len) : (item_type == EITEM_NHASH)? compute_nhash(sub[2], val[0], val[1], &len) : extract_substr(sub[2], val[0], val[1], &len); if (ret == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, ret, len); continue; } /* Handle HMAC computation: ${hmac{<algorithm>}{<secret>}{<text>}} This code originally contributed by Steve Haslam. It currently supports the use of MD5 and SHA-1 hashes. We need some workspace that is large enough to handle all the supported hash types. Use macros to set the sizes rather than be too elaborate. */ #define MAX_HASHLEN 20 #define MAX_HASHBLOCKLEN 64 case EITEM_HMAC: { uschar *sub[3]; md5 md5_base; sha1 sha1_base; void *use_base; int type, i; int hashlen; /* Number of octets for the hash algorithm's output */ int hashblocklen; /* Number of octets the hash algorithm processes */ uschar *keyptr, *p; unsigned int keylen; uschar keyhash[MAX_HASHLEN]; uschar innerhash[MAX_HASHLEN]; uschar finalhash[MAX_HASHLEN]; uschar finalhash_hex[2*MAX_HASHLEN]; uschar innerkey[MAX_HASHBLOCKLEN]; uschar outerkey[MAX_HASHBLOCKLEN]; switch (read_subs(sub, 3, 3, &s, skipping, TRUE, name, &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (Ustrcmp(sub[0], "md5") == 0) { type = HMAC_MD5; use_base = &md5_base; hashlen = 16; hashblocklen = 64; } else if (Ustrcmp(sub[0], "sha1") == 0) { type = HMAC_SHA1; use_base = &sha1_base; hashlen = 20; hashblocklen = 64; } else { expand_string_message = string_sprintf("hmac algorithm \"%s\" is not recognised", sub[0]); goto EXPAND_FAILED; } keyptr = sub[1]; keylen = Ustrlen(keyptr); /* If the key is longer than the hash block length, then hash the key first */ if (keylen > hashblocklen) { chash_start(type, use_base); chash_end(type, use_base, keyptr, keylen, keyhash); keyptr = keyhash; keylen = hashlen; } /* Now make the inner and outer key values */ memset(innerkey, 0x36, hashblocklen); memset(outerkey, 0x5c, hashblocklen); for (i = 0; i < keylen; i++) { innerkey[i] ^= keyptr[i]; outerkey[i] ^= keyptr[i]; } /* Now do the hashes */ chash_start(type, use_base); chash_mid(type, use_base, innerkey); chash_end(type, use_base, sub[2], Ustrlen(sub[2]), innerhash); chash_start(type, use_base); chash_mid(type, use_base, outerkey); chash_end(type, use_base, innerhash, hashlen, finalhash); /* Encode the final hash as a hex string */ p = finalhash_hex; for (i = 0; i < hashlen; i++) { *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4]; *p++ = hex_digits[finalhash[i] & 0x0f]; } DEBUG(D_any) debug_printf("HMAC[%s](%.*s,%.*s)=%.*s\n", sub[0], (int)keylen, keyptr, Ustrlen(sub[2]), sub[2], hashlen*2, finalhash_hex); yield = string_cat(yield, &size, &ptr, finalhash_hex, hashlen*2); } continue; /* Handle global substitution for "sg" - like Perl's s/xxx/yyy/g operator. We have to save the numerical variables and restore them afterwards. */ case EITEM_SG: { const pcre *re; int moffset, moffsetextra, slen; int roffset; int emptyopt; const uschar *rerror; uschar *subject; uschar *sub[3]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"sg", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Compile the regular expression */ re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset, NULL); if (re == NULL) { expand_string_message = string_sprintf("regular expression error in " "\"%s\": %s at offset %d", sub[1], rerror, roffset); goto EXPAND_FAILED; } /* Now run a loop to do the substitutions as often as necessary. It ends when there are no more matches. Take care over matches of the null string; do the same thing as Perl does. */ subject = sub[0]; slen = Ustrlen(sub[0]); moffset = moffsetextra = 0; emptyopt = 0; for (;;) { int ovector[3*(EXPAND_MAXN+1)]; int n = pcre_exec(re, NULL, CS subject, slen, moffset + moffsetextra, PCRE_EOPT | emptyopt, ovector, sizeof(ovector)/sizeof(int)); int nn; uschar *insert; /* No match - if we previously set PCRE_NOTEMPTY after a null match, this is not necessarily the end. We want to repeat the match from one character further along, but leaving the basic offset the same (for copying below). We can't be at the end of the string - that was checked before setting PCRE_NOTEMPTY. If PCRE_NOTEMPTY is not set, we are finished; copy the remaining string and end the loop. */ if (n < 0) { if (emptyopt != 0) { moffsetextra = 1; emptyopt = 0; continue; } yield = string_cat(yield, &size, &ptr, subject+moffset, slen-moffset); break; } /* Match - set up for expanding the replacement. */ if (n == 0) n = EXPAND_MAXN + 1; expand_nmax = 0; for (nn = 0; nn < n*2; nn += 2) { expand_nstring[expand_nmax] = subject + ovector[nn]; expand_nlength[expand_nmax++] = ovector[nn+1] - ovector[nn]; } expand_nmax--; /* Copy the characters before the match, plus the expanded insertion. */ yield = string_cat(yield, &size, &ptr, subject + moffset, ovector[0] - moffset); insert = expand_string(sub[2]); if (insert == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, insert, Ustrlen(insert)); moffset = ovector[1]; moffsetextra = 0; emptyopt = 0; /* If we have matched an empty string, first check to see if we are at the end of the subject. If so, the loop is over. Otherwise, mimic what Perl's /g options does. This turns out to be rather cunning. First we set PCRE_NOTEMPTY and PCRE_ANCHORED and try the match a non-empty string at the same point. If this fails (picked up above) we advance to the next character. */ if (ovector[0] == ovector[1]) { if (ovector[0] == slen) break; emptyopt = PCRE_NOTEMPTY | PCRE_ANCHORED; } } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* Handle keyed and numbered substring extraction. If the first argument consists entirely of digits, then a numerical extraction is assumed. */ case EITEM_EXTRACT: { int i; int j = 2; int field_number = 1; BOOL field_number_set = FALSE; uschar *save_lookup_value = lookup_value; uschar *sub[3]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the arguments */ for (i = 0; i < j; i++) { while (isspace(*s)) s++; if (*s == '{') /*}*/ { sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (sub[i] == NULL) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* After removal of leading and trailing white space, the first argument must not be empty; if it consists entirely of digits (optionally preceded by a minus sign), this is a numerical extraction, and we expect 3 arguments. */ if (i == 0) { int len; int x = 0; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; if (*p == 0 && !skipping) { expand_string_message = US"first argument of \"extract\" must " "not be empty"; goto EXPAND_FAILED; } if (*p == '-') { field_number = -1; p++; } while (*p != 0 && isdigit(*p)) x = x * 10 + *p++ - '0'; if (*p == 0) { field_number *= x; j = 3; /* Need 3 args */ field_number_set = TRUE; } } } else goto EXPAND_FAILED_CURLY; } /* Extract either the numbered or the keyed substring into $value. If skipping, just pretend the extraction failed. */ lookup_value = skipping? NULL : field_number_set? expand_gettokened(field_number, sub[1], sub[2]) : expand_getkeyed(sub[0], sub[1]); /* If no string follows, $value gets substituted; otherwise there can be yes/no strings, as for lookup or if. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* return the Nth item from a list */ case EITEM_LISTEXTRACT: { int i; int field_number = 1; uschar *save_lookup_value = lookup_value; uschar *sub[2]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the field & list arguments */ for (i = 0; i < 2; i++) { while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub[i]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* After removal of leading and trailing white space, the first argument must be numeric and nonempty. */ if (i == 0) { int len; int x = 0; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; if (!*p && !skipping) { expand_string_message = US"first argument of \"listextract\" must " "not be empty"; goto EXPAND_FAILED; } if (*p == '-') { field_number = -1; p++; } while (*p && isdigit(*p)) x = x * 10 + *p++ - '0'; if (*p) { expand_string_message = US"first argument of \"listextract\" must " "be numeric"; goto EXPAND_FAILED; } field_number *= x; } } /* Extract the numbered element into $value. If skipping, just pretend the extraction failed. */ lookup_value = skipping? NULL : expand_getlistele(field_number, sub[1]); /* If no string follows, $value gets substituted; otherwise there can be yes/no strings, as for lookup or if. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } #ifdef SUPPORT_TLS case EITEM_CERTEXTRACT: { uschar *save_lookup_value = lookup_value; uschar *sub[2]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the field argument */ while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; sub[0] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub[0]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* strip spaces fore & aft */ { int len; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; } /* inspect the cert argument */ while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; if (*++s != '$') { expand_string_message = US"second argument of \"certextract\" must " "be a certificate variable"; goto EXPAND_FAILED; } sub[1] = expand_string_internal(s+1, TRUE, &s, skipping, FALSE, &resetok); if (!sub[1]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (skipping) lookup_value = NULL; else { lookup_value = expand_getcertele(sub[0], sub[1]); if (*expand_string_message) goto EXPAND_FAILED; } switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } #endif /*SUPPORT_TLS*/ /* Handle list operations */ case EITEM_FILTER: case EITEM_MAP: case EITEM_REDUCE: { int sep = 0; int save_ptr = ptr; uschar outsep[2] = { '\0', '\0' }; uschar *list, *expr, *temp; uschar *save_iterate_item = iterate_item; uschar *save_lookup_value = lookup_value; while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; list = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok); if (list == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (item_type == EITEM_REDUCE) { while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; temp = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok); if (temp == NULL) goto EXPAND_FAILED; lookup_value = temp; if (*s++ != '}') goto EXPAND_FAILED_CURLY; } while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; expr = s; /* For EITEM_FILTER, call eval_condition once, with result discarded (as if scanning a "false" part). This allows us to find the end of the condition, because if the list is empty, we won't actually evaluate the condition for real. For EITEM_MAP and EITEM_REDUCE, do the same, using the normal internal expansion function. */ if (item_type == EITEM_FILTER) { temp = eval_condition(expr, &resetok, NULL); if (temp != NULL) s = temp; } else { temp = expand_string_internal(s, TRUE, &s, TRUE, TRUE, &resetok); } if (temp == NULL) { expand_string_message = string_sprintf("%s inside \"%s\" item", expand_string_message, name); goto EXPAND_FAILED; } while (isspace(*s)) s++; if (*s++ != '}') { /*{*/ expand_string_message = string_sprintf("missing } at end of condition " "or expression inside \"%s\"", name); goto EXPAND_FAILED; } while (isspace(*s)) s++; /*{*/ if (*s++ != '}') { /*{*/ expand_string_message = string_sprintf("missing } at end of \"%s\"", name); goto EXPAND_FAILED; } /* If we are skipping, we can now just move on to the next item. When processing for real, we perform the iteration. */ if (skipping) continue; while ((iterate_item = string_nextinlist(&list, &sep, NULL, 0)) != NULL) { *outsep = (uschar)sep; /* Separator as a string */ DEBUG(D_expand) debug_printf("%s: $item = \"%s\"\n", name, iterate_item); if (item_type == EITEM_FILTER) { BOOL condresult; if (eval_condition(expr, &resetok, &condresult) == NULL) { iterate_item = save_iterate_item; lookup_value = save_lookup_value; expand_string_message = string_sprintf("%s inside \"%s\" condition", expand_string_message, name); goto EXPAND_FAILED; } DEBUG(D_expand) debug_printf("%s: condition is %s\n", name, condresult? "true":"false"); if (condresult) temp = iterate_item; /* TRUE => include this item */ else continue; /* FALSE => skip this item */ } /* EITEM_MAP and EITEM_REDUCE */ else { temp = expand_string_internal(expr, TRUE, NULL, skipping, TRUE, &resetok); if (temp == NULL) { iterate_item = save_iterate_item; expand_string_message = string_sprintf("%s inside \"%s\" item", expand_string_message, name); goto EXPAND_FAILED; } if (item_type == EITEM_REDUCE) { lookup_value = temp; /* Update the value of $value */ continue; /* and continue the iteration */ } } /* We reach here for FILTER if the condition is true, always for MAP, and never for REDUCE. The value in "temp" is to be added to the output list that is being created, ensuring that any occurrences of the separator character are doubled. Unless we are dealing with the first item of the output list, add in a space if the new item begins with the separator character, or is an empty string. */ if (ptr != save_ptr && (temp[0] == *outsep || temp[0] == 0)) yield = string_cat(yield, &size, &ptr, US" ", 1); /* Add the string in "temp" to the output list that we are building, This is done in chunks by searching for the separator character. */ for (;;) { size_t seglen = Ustrcspn(temp, outsep); yield = string_cat(yield, &size, &ptr, temp, seglen + 1); /* If we got to the end of the string we output one character too many; backup and end the loop. Otherwise arrange to double the separator. */ if (temp[seglen] == '\0') { ptr--; break; } yield = string_cat(yield, &size, &ptr, outsep, 1); temp += seglen + 1; } /* Output a separator after the string: we will remove the redundant final one at the end. */ yield = string_cat(yield, &size, &ptr, outsep, 1); } /* End of iteration over the list loop */ /* REDUCE has generated no output above: output the final value of $value. */ if (item_type == EITEM_REDUCE) { yield = string_cat(yield, &size, &ptr, lookup_value, Ustrlen(lookup_value)); lookup_value = save_lookup_value; /* Restore $value */ } /* FILTER and MAP generate lists: if they have generated anything, remove the redundant final separator. Even though an empty item at the end of a list does not count, this is tidier. */ else if (ptr != save_ptr) ptr--; /* Restore preserved $item */ iterate_item = save_iterate_item; continue; } /* If ${dlfunc } support is configured, handle calling dynamically-loaded functions, unless locked out at this time. Syntax is ${dlfunc{file}{func}} or ${dlfunc{file}{func}{arg}} or ${dlfunc{file}{func}{arg1}{arg2}} or up to a maximum of EXPAND_DLFUNC_MAX_ARGS arguments (defined below). */ #define EXPAND_DLFUNC_MAX_ARGS 8 case EITEM_DLFUNC: #ifndef EXPAND_DLFUNC expand_string_message = US"\"${dlfunc\" encountered, but this facility " /*}*/ "is not included in this binary"; goto EXPAND_FAILED; #else /* EXPAND_DLFUNC */ { tree_node *t; exim_dlfunc_t *func; uschar *result; int status, argc; uschar *argv[EXPAND_DLFUNC_MAX_ARGS + 3]; if ((expand_forbid & RDO_DLFUNC) != 0) { expand_string_message = US"dynamically-loaded functions are not permitted"; goto EXPAND_FAILED; } switch(read_subs(argv, EXPAND_DLFUNC_MAX_ARGS + 2, 2, &s, skipping, TRUE, US"dlfunc", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Look up the dynamically loaded object handle in the tree. If it isn't found, dlopen() the file and put the handle in the tree for next time. */ t = tree_search(dlobj_anchor, argv[0]); if (t == NULL) { void *handle = dlopen(CS argv[0], RTLD_LAZY); if (handle == NULL) { expand_string_message = string_sprintf("dlopen \"%s\" failed: %s", argv[0], dlerror()); log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message); goto EXPAND_FAILED; } t = store_get_perm(sizeof(tree_node) + Ustrlen(argv[0])); Ustrcpy(t->name, argv[0]); t->data.ptr = handle; (void)tree_insertnode(&dlobj_anchor, t); } /* Having obtained the dynamically loaded object handle, look up the function pointer. */ func = (exim_dlfunc_t *)dlsym(t->data.ptr, CS argv[1]); if (func == NULL) { expand_string_message = string_sprintf("dlsym \"%s\" in \"%s\" failed: " "%s", argv[1], argv[0], dlerror()); log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message); goto EXPAND_FAILED; } /* Call the function and work out what to do with the result. If it returns OK, we have a replacement string; if it returns DEFER then expansion has failed in a non-forced manner; if it returns FAIL then failure was forced; if it returns ERROR or any other value there's a problem, so panic slightly. In any case, assume that the function has side-effects on the store that must be preserved. */ resetok = FALSE; result = NULL; for (argc = 0; argv[argc] != NULL; argc++); status = func(&result, argc - 2, &argv[2]); if(status == OK) { if (result == NULL) result = US""; yield = string_cat(yield, &size, &ptr, result, Ustrlen(result)); continue; } else { expand_string_message = result == NULL ? US"(no message)" : result; if(status == FAIL_FORCED) expand_string_forcedfail = TRUE; else if(status != FAIL) log_write(0, LOG_MAIN|LOG_PANIC, "dlfunc{%s}{%s} failed (%d): %s", argv[0], argv[1], status, expand_string_message); goto EXPAND_FAILED; } } #endif /* EXPAND_DLFUNC */ } /* EITEM_* switch */ /* Control reaches here if the name is not recognized as one of the more complicated expansion items. Check for the "operator" syntax (name terminated by a colon). Some of the operators have arguments, separated by _ from the name. */ if (*s == ':') { int c; uschar *arg = NULL; uschar *sub; var_entry *vp = NULL; /* Owing to an historical mis-design, an underscore may be part of the operator name, or it may introduce arguments. We therefore first scan the table of names that contain underscores. If there is no match, we cut off the arguments and then scan the main table. */ if ((c = chop_match(name, op_table_underscore, sizeof(op_table_underscore)/sizeof(uschar *))) < 0) { arg = Ustrchr(name, '_'); if (arg != NULL) *arg = 0; c = chop_match(name, op_table_main, sizeof(op_table_main)/sizeof(uschar *)); if (c >= 0) c += sizeof(op_table_underscore)/sizeof(uschar *); if (arg != NULL) *arg++ = '_'; /* Put back for error messages */ } /* Deal specially with operators that might take a certificate variable as we do not want to do the usual expansion. For most, expand the string.*/ switch(c) { #ifdef SUPPORT_TLS case EOP_MD5: case EOP_SHA1: case EOP_SHA256: if (s[1] == '$') { uschar * s1 = s; sub = expand_string_internal(s+2, TRUE, &s1, skipping, FALSE, &resetok); if (!sub) goto EXPAND_FAILED; /*{*/ if (*s1 != '}') goto EXPAND_FAILED_CURLY; if ((vp = find_var_ent(sub)) && vp->type == vtype_cert) { s = s1+1; break; } vp = NULL; } /*FALLTHROUGH*/ #endif default: sub = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub) goto EXPAND_FAILED; s++; break; } /* If we are skipping, we don't need to perform the operation at all. This matters for operations like "mask", because the data may not be in the correct format when skipping. For example, the expression may test for the existence of $sender_host_address before trying to mask it. For other operations, doing them may not fail, but it is a waste of time. */ if (skipping && c >= 0) continue; /* Otherwise, switch on the operator type */ switch(c) { case EOP_BASE62: { uschar *t; unsigned long int n = Ustrtoul(sub, &t, 10); if (*t != 0) { expand_string_message = string_sprintf("argument for base62 " "operator is \"%s\", which is not a decimal number", sub); goto EXPAND_FAILED; } t = string_base62(n); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Note that for Darwin and Cygwin, BASE_62 actually has the value 36 */ case EOP_BASE62D: { uschar buf[16]; uschar *tt = sub; unsigned long int n = 0; while (*tt != 0) { uschar *t = Ustrchr(base62_chars, *tt++); if (t == NULL) { expand_string_message = string_sprintf("argument for base62d " "operator is \"%s\", which is not a base %d number", sub, BASE_62); goto EXPAND_FAILED; } n = n * BASE_62 + (t - base62_chars); } (void)sprintf(CS buf, "%ld", n); yield = string_cat(yield, &size, &ptr, buf, Ustrlen(buf)); continue; } case EOP_EXPAND: { uschar *expanded = expand_string_internal(sub, FALSE, NULL, skipping, TRUE, &resetok); if (expanded == NULL) { expand_string_message = string_sprintf("internal expansion of \"%s\" failed: %s", sub, expand_string_message); goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, expanded, Ustrlen(expanded)); continue; } case EOP_LC: { int count = 0; uschar *t = sub - 1; while (*(++t) != 0) { *t = tolower(*t); count++; } yield = string_cat(yield, &size, &ptr, sub, count); continue; } case EOP_UC: { int count = 0; uschar *t = sub - 1; while (*(++t) != 0) { *t = toupper(*t); count++; } yield = string_cat(yield, &size, &ptr, sub, count); continue; } case EOP_MD5: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_md5(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); } else #endif { md5 base; uschar digest[16]; int j; char st[33]; md5_start(&base); md5_end(&base, sub, Ustrlen(sub), digest); for(j = 0; j < 16; j++) sprintf(st+2*j, "%02x", digest[j]); yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st)); } continue; case EOP_SHA1: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_sha1(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); } else #endif { sha1 base; uschar digest[20]; int j; char st[41]; sha1_start(&base); sha1_end(&base, sub, Ustrlen(sub), digest); for(j = 0; j < 20; j++) sprintf(st+2*j, "%02X", digest[j]); yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st)); } continue; case EOP_SHA256: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_sha256(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, (int)Ustrlen(cp)); } else #endif expand_string_message = US"sha256 only supported for certificates"; continue; /* Convert hex encoding to base64 encoding */ case EOP_HEX2B64: { int c = 0; int b = -1; uschar *in = sub; uschar *out = sub; uschar *enc; for (enc = sub; *enc != 0; enc++) { if (!isxdigit(*enc)) { expand_string_message = string_sprintf("\"%s\" is not a hex " "string", sub); goto EXPAND_FAILED; } c++; } if ((c & 1) != 0) { expand_string_message = string_sprintf("\"%s\" contains an odd " "number of characters", sub); goto EXPAND_FAILED; } while ((c = *in++) != 0) { if (isdigit(c)) c -= '0'; else c = toupper(c) - 'A' + 10; if (b == -1) { b = c << 4; } else { *out++ = b | c; b = -1; } } enc = auth_b64encode(sub, out - sub); yield = string_cat(yield, &size, &ptr, enc, Ustrlen(enc)); continue; } /* Convert octets outside 0x21..0x7E to \xXX form */ case EOP_HEXQUOTE: { uschar *t = sub - 1; while (*(++t) != 0) { if (*t < 0x21 || 0x7E < *t) yield = string_cat(yield, &size, &ptr, string_sprintf("\\x%02x", *t), 4); else yield = string_cat(yield, &size, &ptr, t, 1); } continue; } /* count the number of list elements */ case EOP_LISTCOUNT: { int cnt = 0; int sep = 0; uschar * cp; uschar buffer[256]; while (string_nextinlist(&sub, &sep, buffer, sizeof(buffer)) != NULL) cnt++; cp = string_sprintf("%d", cnt); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); continue; } /* expand a named list given the name */ /* handles nested named lists; requotes as colon-sep list */ case EOP_LISTNAMED: { tree_node *t = NULL; uschar * list; int sep = 0; uschar * item; uschar * suffix = US""; BOOL needsep = FALSE; uschar buffer[256]; if (*sub == '+') sub++; if (arg == NULL) /* no-argument version */ { if (!(t = tree_search(addresslist_anchor, sub)) && !(t = tree_search(domainlist_anchor, sub)) && !(t = tree_search(hostlist_anchor, sub))) t = tree_search(localpartlist_anchor, sub); } else switch(*arg) /* specific list-type version */ { case 'a': t = tree_search(addresslist_anchor, sub); suffix = US"_a"; break; case 'd': t = tree_search(domainlist_anchor, sub); suffix = US"_d"; break; case 'h': t = tree_search(hostlist_anchor, sub); suffix = US"_h"; break; case 'l': t = tree_search(localpartlist_anchor, sub); suffix = US"_l"; break; default: expand_string_message = string_sprintf("bad suffix on \"list\" operator"); goto EXPAND_FAILED; } if(!t) { expand_string_message = string_sprintf("\"%s\" is not a %snamed list", sub, !arg?"" : *arg=='a'?"address " : *arg=='d'?"domain " : *arg=='h'?"host " : *arg=='l'?"localpart " : 0); goto EXPAND_FAILED; } list = ((namedlist_block *)(t->data.ptr))->string; while ((item = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL) { uschar * buf = US" : "; if (needsep) yield = string_cat(yield, &size, &ptr, buf, 3); else needsep = TRUE; if (*item == '+') /* list item is itself a named list */ { uschar * sub = string_sprintf("${listnamed%s:%s}", suffix, item); item = expand_string_internal(sub, FALSE, NULL, FALSE, TRUE, &resetok); } else if (sep != ':') /* item from non-colon-sep list, re-quote for colon list-separator */ { char * cp; char tok[3]; tok[0] = sep; tok[1] = ':'; tok[2] = 0; while ((cp= strpbrk((const char *)item, tok))) { yield = string_cat(yield, &size, &ptr, item, cp-(char *)item); if (*cp++ == ':') /* colon in a non-colon-sep list item, needs doubling */ { yield = string_cat(yield, &size, &ptr, US"::", 2); item = (uschar *)cp; } else /* sep in item; should already be doubled; emit once */ { yield = string_cat(yield, &size, &ptr, (uschar *)tok, 1); if (*cp == sep) cp++; item = (uschar *)cp; } } } yield = string_cat(yield, &size, &ptr, item, Ustrlen(item)); } continue; } /* mask applies a mask to an IP address; for example the result of ${mask:131.111.10.206/28} is 131.111.10.192/28. */ case EOP_MASK: { int count; uschar *endptr; int binary[4]; int mask, maskoffset; int type = string_is_ip_address(sub, &maskoffset); uschar buffer[64]; if (type == 0) { expand_string_message = string_sprintf("\"%s\" is not an IP address", sub); goto EXPAND_FAILED; } if (maskoffset == 0) { expand_string_message = string_sprintf("missing mask value in \"%s\"", sub); goto EXPAND_FAILED; } mask = Ustrtol(sub + maskoffset + 1, &endptr, 10); if (*endptr != 0 || mask < 0 || mask > ((type == 4)? 32 : 128)) { expand_string_message = string_sprintf("mask value too big in \"%s\"", sub); goto EXPAND_FAILED; } /* Convert the address to binary integer(s) and apply the mask */ sub[maskoffset] = 0; count = host_aton(sub, binary); host_mask(count, binary, mask); /* Convert to masked textual format and add to output. */ yield = string_cat(yield, &size, &ptr, buffer, host_nmtoa(count, binary, mask, buffer, '.')); continue; } case EOP_ADDRESS: case EOP_LOCAL_PART: case EOP_DOMAIN: { uschar *error; int start, end, domain; uschar *t = parse_extract_address(sub, &error, &start, &end, &domain, FALSE); if (t != NULL) { if (c != EOP_DOMAIN) { if (c == EOP_LOCAL_PART && domain != 0) end = start + domain - 1; yield = string_cat(yield, &size, &ptr, sub+start, end-start); } else if (domain != 0) { domain += start; yield = string_cat(yield, &size, &ptr, sub+domain, end-domain); } } continue; } case EOP_ADDRESSES: { uschar outsep[2] = { ':', '\0' }; uschar *address, *error; int save_ptr = ptr; int start, end, domain; /* Not really used */ while (isspace(*sub)) sub++; if (*sub == '>') { *outsep = *++sub; ++sub; } parse_allow_group = TRUE; for (;;) { uschar *p = parse_find_address_end(sub, FALSE); uschar saveend = *p; *p = '\0'; address = parse_extract_address(sub, &error, &start, &end, &domain, FALSE); *p = saveend; /* Add the address to the output list that we are building. This is done in chunks by searching for the separator character. At the start, unless we are dealing with the first address of the output list, add in a space if the new address begins with the separator character, or is an empty string. */ if (address != NULL) { if (ptr != save_ptr && address[0] == *outsep) yield = string_cat(yield, &size, &ptr, US" ", 1); for (;;) { size_t seglen = Ustrcspn(address, outsep); yield = string_cat(yield, &size, &ptr, address, seglen + 1); /* If we got to the end of the string we output one character too many. */ if (address[seglen] == '\0') { ptr--; break; } yield = string_cat(yield, &size, &ptr, outsep, 1); address += seglen + 1; } /* Output a separator after the string: we will remove the redundant final one at the end. */ yield = string_cat(yield, &size, &ptr, outsep, 1); } if (saveend == '\0') break; sub = p + 1; } /* If we have generated anything, remove the redundant final separator. */ if (ptr != save_ptr) ptr--; parse_allow_group = FALSE; continue; } /* quote puts a string in quotes if it is empty or contains anything other than alphamerics, underscore, dot, or hyphen. quote_local_part puts a string in quotes if RFC 2821/2822 requires it to be quoted in order to be a valid local part. In both cases, newlines and carriage returns are converted into \n and \r respectively */ case EOP_QUOTE: case EOP_QUOTE_LOCAL_PART: if (arg == NULL) { BOOL needs_quote = (*sub == 0); /* TRUE for empty string */ uschar *t = sub - 1; if (c == EOP_QUOTE) { while (!needs_quote && *(++t) != 0) needs_quote = !isalnum(*t) && !strchr("_-.", *t); } else /* EOP_QUOTE_LOCAL_PART */ { while (!needs_quote && *(++t) != 0) needs_quote = !isalnum(*t) && strchr("!#$%&'*+-/=?^_`{|}~", *t) == NULL && (*t != '.' || t == sub || t[1] == 0); } if (needs_quote) { yield = string_cat(yield, &size, &ptr, US"\"", 1); t = sub - 1; while (*(++t) != 0) { if (*t == '\n') yield = string_cat(yield, &size, &ptr, US"\\n", 2); else if (*t == '\r') yield = string_cat(yield, &size, &ptr, US"\\r", 2); else { if (*t == '\\' || *t == '"') yield = string_cat(yield, &size, &ptr, US"\\", 1); yield = string_cat(yield, &size, &ptr, t, 1); } } yield = string_cat(yield, &size, &ptr, US"\"", 1); } else yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub)); continue; } /* quote_lookuptype does lookup-specific quoting */ else { int n; uschar *opt = Ustrchr(arg, '_'); if (opt != NULL) *opt++ = 0; n = search_findtype(arg, Ustrlen(arg)); if (n < 0) { expand_string_message = search_error_message; goto EXPAND_FAILED; } if (lookup_list[n]->quote != NULL) sub = (lookup_list[n]->quote)(sub, opt); else if (opt != NULL) sub = NULL; if (sub == NULL) { expand_string_message = string_sprintf( "\"%s\" unrecognized after \"${quote_%s\"", opt, arg); goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub)); continue; } /* rx quote sticks in \ before any non-alphameric character so that the insertion works in a regular expression. */ case EOP_RXQUOTE: { uschar *t = sub - 1; while (*(++t) != 0) { if (!isalnum(*t)) yield = string_cat(yield, &size, &ptr, US"\\", 1); yield = string_cat(yield, &size, &ptr, t, 1); } continue; } /* RFC 2047 encodes, assuming headers_charset (default ISO 8859-1) as prescribed by the RFC, if there are characters that need to be encoded */ case EOP_RFC2047: { uschar buffer[2048]; uschar *string = parse_quote_2047(sub, Ustrlen(sub), headers_charset, buffer, sizeof(buffer), FALSE); yield = string_cat(yield, &size, &ptr, string, Ustrlen(string)); continue; } /* RFC 2047 decode */ case EOP_RFC2047D: { int len; uschar *error; uschar *decoded = rfc2047_decode(sub, check_rfc2047_length, headers_charset, '?', &len, &error); if (error != NULL) { expand_string_message = error; goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, decoded, len); continue; } /* from_utf8 converts UTF-8 to 8859-1, turning non-existent chars into underscores */ case EOP_FROM_UTF8: { while (*sub != 0) { int c; uschar buff[4]; GETUTF8INC(c, sub); if (c > 255) c = '_'; buff[0] = c; yield = string_cat(yield, &size, &ptr, buff, 1); } continue; } /* replace illegal UTF-8 sequences by replacement character */ #define UTF8_REPLACEMENT_CHAR US"?" case EOP_UTF8CLEAN: { int seq_len, index = 0; int bytes_left = 0; uschar seq_buff[4]; /* accumulate utf-8 here */ while (*sub != 0) { int complete; long codepoint; uschar c; complete = 0; c = *sub++; if (bytes_left) { if ((c & 0xc0) != 0x80) { /* wrong continuation byte; invalidate all bytes */ complete = 1; /* error */ } else { codepoint = (codepoint << 6) | (c & 0x3f); seq_buff[index++] = c; if (--bytes_left == 0) /* codepoint complete */ { if(codepoint > 0x10FFFF) /* is it too large? */ complete = -1; /* error */ else { /* finished; output utf-8 sequence */ yield = string_cat(yield, &size, &ptr, seq_buff, seq_len); index = 0; } } } } else /* no bytes left: new sequence */ { if((c & 0x80) == 0) /* 1-byte sequence, US-ASCII, keep it */ { yield = string_cat(yield, &size, &ptr, &c, 1); continue; } if((c & 0xe0) == 0xc0) /* 2-byte sequence */ { if(c == 0xc0 || c == 0xc1) /* 0xc0 and 0xc1 are illegal */ complete = -1; else { bytes_left = 1; codepoint = c & 0x1f; } } else if((c & 0xf0) == 0xe0) /* 3-byte sequence */ { bytes_left = 2; codepoint = c & 0x0f; } else if((c & 0xf8) == 0xf0) /* 4-byte sequence */ { bytes_left = 3; codepoint = c & 0x07; } else /* invalid or too long (RFC3629 allows only 4 bytes) */ complete = -1; seq_buff[index++] = c; seq_len = bytes_left + 1; } /* if(bytes_left) */ if (complete != 0) { bytes_left = index = 0; yield = string_cat(yield, &size, &ptr, UTF8_REPLACEMENT_CHAR, 1); } if ((complete == 1) && ((c & 0x80) == 0)) { /* ASCII character follows incomplete sequence */ yield = string_cat(yield, &size, &ptr, &c, 1); } } continue; } /* escape turns all non-printing characters into escape sequences. */ case EOP_ESCAPE: { uschar *t = string_printing(sub); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Handle numeric expression evaluation */ case EOP_EVAL: case EOP_EVAL10: { uschar *save_sub = sub; uschar *error = NULL; int_eximarith_t n = eval_expr(&sub, (c == EOP_EVAL10), &error, FALSE); if (error != NULL) { expand_string_message = string_sprintf("error in expression " "evaluation: %s (after processing \"%.*s\")", error, sub-save_sub, save_sub); goto EXPAND_FAILED; } sprintf(CS var_buffer, PR_EXIM_ARITH, n); yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer)); continue; } /* Handle time period formating */ case EOP_TIME_EVAL: { int n = readconf_readtime(sub, 0, FALSE); if (n < 0) { expand_string_message = string_sprintf("string \"%s\" is not an " "Exim time interval in \"%s\" operator", sub, name); goto EXPAND_FAILED; } sprintf(CS var_buffer, "%d", n); yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer)); continue; } case EOP_TIME_INTERVAL: { int n; uschar *t = read_number(&n, sub); if (*t != 0) /* Not A Number*/ { expand_string_message = string_sprintf("string \"%s\" is not a " "positive number in \"%s\" operator", sub, name); goto EXPAND_FAILED; } t = readconf_printtime(n); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Convert string to base64 encoding */ case EOP_STR2B64: { uschar *encstr = auth_b64encode(sub, Ustrlen(sub)); yield = string_cat(yield, &size, &ptr, encstr, Ustrlen(encstr)); continue; } /* strlen returns the length of the string */ case EOP_STRLEN: { uschar buff[24]; (void)sprintf(CS buff, "%d", Ustrlen(sub)); yield = string_cat(yield, &size, &ptr, buff, Ustrlen(buff)); continue; } /* length_n or l_n takes just the first n characters or the whole string, whichever is the shorter; substr_m_n, and s_m_n take n characters from offset m; negative m take from the end; l_n is synonymous with s_0_n. If n is omitted in substr it takes the rest, either to the right or to the left. hash_n or h_n makes a hash of length n from the string, yielding n characters from the set a-z; hash_n_m makes a hash of length n, but uses m characters from the set a-zA-Z0-9. nhash_n returns a single number between 0 and n-1 (in text form), while nhash_n_m returns a div/mod hash as two numbers "a/b". The first lies between 0 and n-1 and the second between 0 and m-1. */ case EOP_LENGTH: case EOP_L: case EOP_SUBSTR: case EOP_S: case EOP_HASH: case EOP_H: case EOP_NHASH: case EOP_NH: { int sign = 1; int value1 = 0; int value2 = -1; int *pn; int len; uschar *ret; if (arg == NULL) { expand_string_message = string_sprintf("missing values after %s", name); goto EXPAND_FAILED; } /* "length" has only one argument, effectively being synonymous with substr_0_n. */ if (c == EOP_LENGTH || c == EOP_L) { pn = &value2; value2 = 0; } /* The others have one or two arguments; for "substr" the first may be negative. The second being negative means "not supplied". */ else { pn = &value1; if (name[0] == 's' && *arg == '-') { sign = -1; arg++; } } /* Read up to two numbers, separated by underscores */ ret = arg; while (*arg != 0) { if (arg != ret && *arg == '_' && pn == &value1) { pn = &value2; value2 = 0; if (arg[1] != 0) arg++; } else if (!isdigit(*arg)) { expand_string_message = string_sprintf("non-digit after underscore in \"%s\"", name); goto EXPAND_FAILED; } else *pn = (*pn)*10 + *arg++ - '0'; } value1 *= sign; /* Perform the required operation */ ret = (c == EOP_HASH || c == EOP_H)? compute_hash(sub, value1, value2, &len) : (c == EOP_NHASH || c == EOP_NH)? compute_nhash(sub, value1, value2, &len) : extract_substr(sub, value1, value2, &len); if (ret == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, ret, len); continue; } /* Stat a path */ case EOP_STAT: { uschar *s; uschar smode[12]; uschar **modetable[3]; int i; mode_t mode; struct stat st; if ((expand_forbid & RDO_EXISTS) != 0) { expand_string_message = US"Use of the stat() expansion is not permitted"; goto EXPAND_FAILED; } if (stat(CS sub, &st) < 0) { expand_string_message = string_sprintf("stat(%s) failed: %s", sub, strerror(errno)); goto EXPAND_FAILED; } mode = st.st_mode; switch (mode & S_IFMT) { case S_IFIFO: smode[0] = 'p'; break; case S_IFCHR: smode[0] = 'c'; break; case S_IFDIR: smode[0] = 'd'; break; case S_IFBLK: smode[0] = 'b'; break; case S_IFREG: smode[0] = '-'; break; default: smode[0] = '?'; break; } modetable[0] = ((mode & 01000) == 0)? mtable_normal : mtable_sticky; modetable[1] = ((mode & 02000) == 0)? mtable_normal : mtable_setid; modetable[2] = ((mode & 04000) == 0)? mtable_normal : mtable_setid; for (i = 0; i < 3; i++) { memcpy(CS(smode + 7 - i*3), CS(modetable[i][mode & 7]), 3); mode >>= 3; } smode[10] = 0; s = string_sprintf("mode=%04lo smode=%s inode=%ld device=%ld links=%ld " "uid=%ld gid=%ld size=" OFF_T_FMT " atime=%ld mtime=%ld ctime=%ld", (long)(st.st_mode & 077777), smode, (long)st.st_ino, (long)st.st_dev, (long)st.st_nlink, (long)st.st_uid, (long)st.st_gid, st.st_size, (long)st.st_atime, (long)st.st_mtime, (long)st.st_ctime); yield = string_cat(yield, &size, &ptr, s, Ustrlen(s)); continue; } /* vaguely random number less than N */ case EOP_RANDINT: { int_eximarith_t max; uschar *s; max = expand_string_integer(sub, TRUE); if (expand_string_message != NULL) goto EXPAND_FAILED; s = string_sprintf("%d", vaguely_random_number((int)max)); yield = string_cat(yield, &size, &ptr, s, Ustrlen(s)); continue; } /* Reverse IP, including IPv6 to dotted-nibble */ case EOP_REVERSE_IP: { int family, maskptr; uschar reversed[128]; family = string_is_ip_address(sub, &maskptr); if (family == 0) { expand_string_message = string_sprintf( "reverse_ip() not given an IP address [%s]", sub); goto EXPAND_FAILED; } invert_address(reversed, sub); yield = string_cat(yield, &size, &ptr, reversed, Ustrlen(reversed)); continue; } /* Unknown operator */ default: expand_string_message = string_sprintf("unknown expansion operator \"%s\"", name); goto EXPAND_FAILED; } } /* Handle a plain name. If this is the first thing in the expansion, release the pre-allocated buffer. If the result data is known to be in a new buffer, newsize will be set to the size of that buffer, and we can just point at that store instead of copying. Many expansion strings contain just one reference, so this is a useful optimization, especially for humungous headers ($message_headers). */ /*{*/ if (*s++ == '}') { int len; int newsize = 0; if (ptr == 0) { if (resetok) store_reset(yield); yield = NULL; size = 0; } value = find_variable(name, FALSE, skipping, &newsize); if (value == NULL) { expand_string_message = string_sprintf("unknown variable in \"${%s}\"", name); check_variable_error_message(name); goto EXPAND_FAILED; } len = Ustrlen(value); if (yield == NULL && newsize != 0) { yield = value; size = newsize; ptr = len; } else yield = string_cat(yield, &size, &ptr, value, len); continue; } /* Else there's something wrong */ expand_string_message = string_sprintf("\"${%s\" is not a known operator (or a } is missing " "in a variable reference)", name); goto EXPAND_FAILED; } /* If we hit the end of the string when ket_ends is set, there is a missing terminating brace. */ if (ket_ends && *s == 0) { expand_string_message = malformed_header? US"missing } at end of string - could be header name not terminated by colon" : US"missing } at end of string"; goto EXPAND_FAILED; } /* Expansion succeeded; yield may still be NULL here if nothing was actually added to the string. If so, set up an empty string. Add a terminating zero. If left != NULL, return a pointer to the terminator. */ if (yield == NULL) yield = store_get(1); yield[ptr] = 0; if (left != NULL) *left = s; /* Any stacking store that was used above the final string is no longer needed. In many cases the final string will be the first one that was got and so there will be optimal store usage. */ if (resetok) store_reset(yield + ptr + 1); else if (resetok_p) *resetok_p = FALSE; DEBUG(D_expand) { debug_printf("expanding: %.*s\n result: %s\n", (int)(s - string), string, yield); if (skipping) debug_printf("skipping: result is not used\n"); } return yield; /* This is the failure exit: easiest to program with a goto. We still need to update the pointer to the terminator, for cases of nested calls with "fail". */ EXPAND_FAILED_CURLY: expand_string_message = malformed_header? US"missing or misplaced { or } - could be header name not terminated by colon" : US"missing or misplaced { or }"; /* At one point, Exim reset the store to yield (if yield was not NULL), but that is a bad idea, because expand_string_message is in dynamic store. */ EXPAND_FAILED: if (left != NULL) *left = s; DEBUG(D_expand) { debug_printf("failed to expand: %s\n", string); debug_printf(" error message: %s\n", expand_string_message); if (expand_string_forcedfail) debug_printf("failure was forced\n"); } if (resetok_p) *resetok_p = resetok; return NULL; } Commit Message: CWE ID: CWE-189 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 LauncherView::UpdateFirstButtonPadding() { if (view_model_->view_size() > 0) { view_model_->view_at(0)->set_border(views::Border::CreateEmptyBorder( primary_axis_coordinate(0, kLeadingInset), primary_axis_coordinate(kLeadingInset, 0), 0, 0)); } } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par) { codec->codec_type = par->codec_type; codec->codec_id = par->codec_id; codec->codec_tag = par->codec_tag; codec->bit_rate = par->bit_rate; codec->bits_per_coded_sample = par->bits_per_coded_sample; codec->bits_per_raw_sample = par->bits_per_raw_sample; codec->profile = par->profile; codec->level = par->level; switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: codec->pix_fmt = par->format; codec->width = par->width; codec->height = par->height; codec->field_order = par->field_order; codec->color_range = par->color_range; codec->color_primaries = par->color_primaries; codec->color_trc = par->color_trc; codec->colorspace = par->color_space; codec->chroma_sample_location = par->chroma_location; codec->sample_aspect_ratio = par->sample_aspect_ratio; codec->has_b_frames = par->video_delay; break; case AVMEDIA_TYPE_AUDIO: codec->sample_fmt = par->format; codec->channel_layout = par->channel_layout; codec->channels = par->channels; codec->sample_rate = par->sample_rate; codec->block_align = par->block_align; codec->frame_size = par->frame_size; codec->delay = codec->initial_padding = par->initial_padding; codec->trailing_padding = par->trailing_padding; codec->seek_preroll = par->seek_preroll; break; case AVMEDIA_TYPE_SUBTITLE: codec->width = par->width; codec->height = par->height; break; } if (par->extradata) { av_freep(&codec->extradata); codec->extradata = av_mallocz(par->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!codec->extradata) return AVERROR(ENOMEM); memcpy(codec->extradata, par->extradata, par->extradata_size); codec->extradata_size = par->extradata_size; } return 0; } Commit Message: avcodec/utils: correct align value for interplay Fixes out of array access Fixes: 452/fuzz-1-ffmpeg_VIDEO_AV_CODEC_ID_INTERPLAY_VIDEO_fuzzer Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> 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: static uint8_t excluded_channels(bitfile *ld, drc_info *drc) { uint8_t i, n = 0; uint8_t num_excl_chan = 7; for (i = 0; i < 7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,103,"excluded_channels(): exclude_mask")); } n++; while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld DEBUGVAR(1,104,"excluded_channels(): additional_excluded_chns"))) == 1) { for (i = num_excl_chan; i < num_excl_chan+7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,105,"excluded_channels(): exclude_mask")); } n++; num_excl_chan += 7; } return n; } Commit Message: Fix a couple buffer overflows https://hackerone.com/reports/502816 https://hackerone.com/reports/507858 https://github.com/videolan/vlc/blob/master/contrib/src/faad2/faad2-fix-overflows.patch 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 WarmupURLFetcher::FetchWarmupURL( size_t previous_attempt_counts, const DataReductionProxyServer& proxy_server) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); previous_attempt_counts_ = previous_attempt_counts; DCHECK_LE(0u, previous_attempt_counts_); DCHECK_GE(2u, previous_attempt_counts_); fetch_delay_timer_.Stop(); if (previous_attempt_counts_ == 0) { FetchWarmupURLNow(proxy_server); return; } fetch_delay_timer_.Start( FROM_HERE, GetFetchWaitTime(), base::BindOnce(&WarmupURLFetcher::FetchWarmupURLNow, base::Unretained(this), proxy_server)); } 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: int snd_timer_new(struct snd_card *card, char *id, struct snd_timer_id *tid, struct snd_timer **rtimer) { struct snd_timer *timer; int err; static struct snd_device_ops ops = { .dev_free = snd_timer_dev_free, .dev_register = snd_timer_dev_register, .dev_disconnect = snd_timer_dev_disconnect, }; if (snd_BUG_ON(!tid)) return -EINVAL; if (rtimer) *rtimer = NULL; timer = kzalloc(sizeof(*timer), GFP_KERNEL); if (!timer) return -ENOMEM; timer->tmr_class = tid->dev_class; timer->card = card; timer->tmr_device = tid->device; timer->tmr_subdevice = tid->subdevice; if (id) strlcpy(timer->id, id, sizeof(timer->id)); timer->sticks = 1; INIT_LIST_HEAD(&timer->device_list); INIT_LIST_HEAD(&timer->open_list_head); INIT_LIST_HEAD(&timer->active_list_head); INIT_LIST_HEAD(&timer->ack_list_head); INIT_LIST_HEAD(&timer->sack_list_head); spin_lock_init(&timer->lock); tasklet_init(&timer->task_queue, snd_timer_tasklet, (unsigned long)timer); if (card != NULL) { timer->module = card->module; err = snd_device_new(card, SNDRV_DEV_TIMER, timer, &ops); if (err < 0) { snd_timer_free(timer); return err; } } if (rtimer) *rtimer = timer; return 0; } Commit Message: ALSA: timer: Fix missing queue indices reset at SNDRV_TIMER_IOCTL_SELECT snd_timer_user_tselect() reallocates the queue buffer dynamically, but it forgot to reset its indices. Since the read may happen concurrently with ioctl and snd_timer_user_tselect() allocates the buffer via kmalloc(), this may lead to the leak of uninitialized kernel-space data, as spotted via KMSAN: BUG: KMSAN: use of unitialized memory in snd_timer_user_read+0x6c4/0xa10 CPU: 0 PID: 1037 Comm: probe Not tainted 4.11.0-rc5+ #2739 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 Call Trace: __dump_stack lib/dump_stack.c:16 dump_stack+0x143/0x1b0 lib/dump_stack.c:52 kmsan_report+0x12a/0x180 mm/kmsan/kmsan.c:1007 kmsan_check_memory+0xc2/0x140 mm/kmsan/kmsan.c:1086 copy_to_user ./arch/x86/include/asm/uaccess.h:725 snd_timer_user_read+0x6c4/0xa10 sound/core/timer.c:2004 do_loop_readv_writev fs/read_write.c:716 __do_readv_writev+0x94c/0x1380 fs/read_write.c:864 do_readv_writev fs/read_write.c:894 vfs_readv fs/read_write.c:908 do_readv+0x52a/0x5d0 fs/read_write.c:934 SYSC_readv+0xb6/0xd0 fs/read_write.c:1021 SyS_readv+0x87/0xb0 fs/read_write.c:1018 This patch adds the missing reset of queue indices. Together with the previous fix for the ioctl/read race, we cover the whole problem. Reported-by: Alexander Potapenko <[email protected]> Tested-by: Alexander Potapenko <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[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: GLuint GLES2Implementation::CreateGpuFenceCHROMIUM() { GLuint client_id = GetIdAllocator(IdNamespaces::kGpuFences) ->AllocateIDAtOrAbove(last_gpu_fence_id_ + 1); CHECK(client_id > last_gpu_fence_id_) << "ID wrap prevented"; last_gpu_fence_id_ = client_id; helper_->CreateGpuFenceINTERNAL(client_id); GPU_CLIENT_LOG("returned " << client_id); CheckGLError(); return client_id; } 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: cib_remote_signon(cib_t * cib, const char *name, enum cib_conn_type type) { int rc = pcmk_ok; cib_remote_opaque_t *private = cib->variant_opaque; if (private->passwd == NULL) { struct termios settings; int rc; rc = tcgetattr(0, &settings); settings.c_lflag &= ~ECHO; rc = tcsetattr(0, TCSANOW, &settings); fprintf(stderr, "Password: "); private->passwd = calloc(1, 1024); rc = scanf("%s", private->passwd); fprintf(stdout, "\n"); /* fprintf(stderr, "entered: '%s'\n", buffer); */ if (rc < 1) { private->passwd = NULL; } settings.c_lflag |= ECHO; rc = tcsetattr(0, TCSANOW, &settings); } if (private->server == NULL || private->user == NULL) { rc = -EINVAL; } if (rc == pcmk_ok) { rc = cib_tls_signon(cib, &(private->command)); } if (rc == pcmk_ok) { rc = cib_tls_signon(cib, &(private->callback)); } if (rc == pcmk_ok) { xmlNode *hello = cib_create_op(0, private->callback.token, CRM_OP_REGISTER, NULL, NULL, NULL, 0, NULL); crm_xml_add(hello, F_CIB_CLIENTNAME, name); crm_send_remote_msg(private->command.session, hello, private->command.encrypted); free_xml(hello); } if (rc == pcmk_ok) { fprintf(stderr, "%s: Opened connection to %s:%d\n", name, private->server, private->port); cib->state = cib_connected_command; cib->type = cib_command; } else { fprintf(stderr, "%s: Connection to %s:%d failed: %s\n", name, private->server, private->port, pcmk_strerror(rc)); } return rc; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399 Target: 1 Example 2: Code: xfs_dir_open( struct inode *inode, struct file *file) { struct xfs_inode *ip = XFS_I(inode); int mode; int error; error = xfs_file_open(inode, file); if (error) return error; /* * If there are any blocks, read-ahead block 0 as we're almost * certain to have the next operation be a read there. */ mode = xfs_ilock_data_map_shared(ip); if (ip->i_d.di_nextents > 0) xfs_dir3_data_readahead(NULL, ip, 0, -1); xfs_iunlock(ip, mode); return 0; } Commit Message: ->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] Signed-off-by: Al Viro <[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 SelectionEditor::AssertSelectionValid() const { #if DCHECK_IS_ON() const_cast<SelectionEditor*>(this)->selection_.dom_tree_version_ = GetDocument().DomTreeVersion(); #endif selection_.AssertValidFor(GetDocument()); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} 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: static ssize_t eth_rx(NetClientState *nc, const uint8_t *buf, size_t size) { struct xlx_ethlite *s = qemu_get_nic_opaque(nc); unsigned int rxbase = s->rxbuf * (0x800 / 4); /* DA filter. */ if (!(buf[0] & 0x80) && memcmp(&s->conf.macaddr.a[0], buf, 6)) return size; if (s->regs[rxbase + R_RX_CTRL0] & CTRL_S) { D(qemu_log("ethlite lost packet %x\n", s->regs[R_RX_CTRL0])); return -1; } D(qemu_log("%s %zd rxbase=%x\n", __func__, size, rxbase)); memcpy(&s->regs[rxbase + R_RX_BUF0], buf, size); s->regs[rxbase + R_RX_CTRL0] |= CTRL_S; /* If c_rx_pingpong was set flip buffers. */ s->rxbuf ^= s->c_rx_pingpong; return size; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: IntRect Editor::FirstRectForRange(const EphemeralRange& range) const { DCHECK(!GetFrame().GetDocument()->NeedsLayoutTreeUpdate()); DocumentLifecycle::DisallowTransitionScope disallow_transition( GetFrame().GetDocument()->Lifecycle()); LayoutUnit extra_width_to_end_of_line; DCHECK(range.IsNotNull()); IntRect start_caret_rect = RenderedPosition( CreateVisiblePosition(range.StartPosition()).DeepEquivalent(), TextAffinity::kDownstream) .AbsoluteRect(&extra_width_to_end_of_line); if (start_caret_rect.IsEmpty()) return IntRect(); IntRect end_caret_rect = RenderedPosition( CreateVisiblePosition(range.EndPosition()).DeepEquivalent(), TextAffinity::kUpstream) .AbsoluteRect(); if (end_caret_rect.IsEmpty()) return IntRect(); if (start_caret_rect.Y() == end_caret_rect.Y()) { return IntRect( std::min(start_caret_rect.X(), end_caret_rect.X()), start_caret_rect.Y(), abs(end_caret_rect.X() - start_caret_rect.X()), std::max(start_caret_rect.Height(), end_caret_rect.Height())); } return IntRect( start_caret_rect.X(), start_caret_rect.Y(), (start_caret_rect.Width() + extra_width_to_end_of_line).ToInt(), start_caret_rect.Height()); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} 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 inline void of_mdiobus_link_mdiodev(struct mii_bus *mdio, struct mdio_device *mdiodev) { } Commit Message: mdio_bus: Fix use-after-free on device_register fails KASAN has found use-after-free in fixed_mdio_bus_init, commit 0c692d07842a ("drivers/net/phy/mdio_bus.c: call put_device on device_register() failure") call put_device() while device_register() fails,give up the last reference to the device and allow mdiobus_release to be executed ,kfreeing the bus. However in most drives, mdiobus_free be called to free the bus while mdiobus_register fails. use-after-free occurs when access bus again, this patch revert it to let mdiobus_free free the bus. KASAN report details as below: BUG: KASAN: use-after-free in mdiobus_free+0x85/0x90 drivers/net/phy/mdio_bus.c:482 Read of size 4 at addr ffff8881dc824d78 by task syz-executor.0/3524 CPU: 1 PID: 3524 Comm: syz-executor.0 Not tainted 5.0.0-rc7+ #45 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xfa/0x1ce lib/dump_stack.c:113 print_address_description+0x65/0x270 mm/kasan/report.c:187 kasan_report+0x149/0x18d mm/kasan/report.c:317 mdiobus_free+0x85/0x90 drivers/net/phy/mdio_bus.c:482 fixed_mdio_bus_init+0x283/0x1000 [fixed_phy] ? 0xffffffffc0e40000 ? 0xffffffffc0e40000 ? 0xffffffffc0e40000 do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f6215c19c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000080 RDI: 0000000000000003 RBP: 00007f6215c19c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f6215c1a6bc R13: 00000000004bcefb R14: 00000000006f7030 R15: 0000000000000004 Allocated by task 3524: set_track mm/kasan/common.c:85 [inline] __kasan_kmalloc.constprop.3+0xa0/0xd0 mm/kasan/common.c:496 kmalloc include/linux/slab.h:545 [inline] kzalloc include/linux/slab.h:740 [inline] mdiobus_alloc_size+0x54/0x1b0 drivers/net/phy/mdio_bus.c:143 fixed_mdio_bus_init+0x163/0x1000 [fixed_phy] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe Freed by task 3524: set_track mm/kasan/common.c:85 [inline] __kasan_slab_free+0x130/0x180 mm/kasan/common.c:458 slab_free_hook mm/slub.c:1409 [inline] slab_free_freelist_hook mm/slub.c:1436 [inline] slab_free mm/slub.c:2986 [inline] kfree+0xe1/0x270 mm/slub.c:3938 device_release+0x78/0x200 drivers/base/core.c:919 kobject_cleanup lib/kobject.c:662 [inline] kobject_release lib/kobject.c:691 [inline] kref_put include/linux/kref.h:67 [inline] kobject_put+0x146/0x240 lib/kobject.c:708 put_device+0x1c/0x30 drivers/base/core.c:2060 __mdiobus_register+0x483/0x560 drivers/net/phy/mdio_bus.c:382 fixed_mdio_bus_init+0x26b/0x1000 [fixed_phy] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe The buggy address belongs to the object at ffff8881dc824c80 which belongs to the cache kmalloc-2k of size 2048 The buggy address is located 248 bytes inside of 2048-byte region [ffff8881dc824c80, ffff8881dc825480) The buggy address belongs to the page: page:ffffea0007720800 count:1 mapcount:0 mapping:ffff8881f6c02800 index:0x0 compound_mapcount: 0 flags: 0x2fffc0000010200(slab|head) raw: 02fffc0000010200 0000000000000000 0000000500000001 ffff8881f6c02800 raw: 0000000000000000 00000000800f000f 00000001ffffffff 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff8881dc824c00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc ffff8881dc824c80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff8881dc824d00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff8881dc824d80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8881dc824e00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb Fixes: 0c692d07842a ("drivers/net/phy/mdio_bus.c: call put_device on device_register() failure") Signed-off-by: YueHaibing <[email protected]> Reviewed-by: Andrew Lunn <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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: static int mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset * to 0 as we leave), and comefrom to save source hook bitmask. */ for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct arpt_entry *e = (struct arpt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)arpt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) { pr_notice("arptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct arpt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->arp)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last * big jump. */ do { e->comefrom ^= (1<<NF_ARP_NUMHOOKS); oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct arpt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct arpt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct arpt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct arpt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } Commit Message: netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void DirectoryEntrySync::trace(Visitor* visitor) { EntrySync::trace(visitor); } 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: void PrintViewManagerBase::SendPrintingEnabled(bool enabled, content::RenderFrameHost* rfh) { rfh->Send(new PrintMsg_SetPrintingEnabled(rfh->GetRoutingID(), enabled)); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} 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: static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, int iv_len, int argc, int dencrypt, zval* return_value TSRMLS_DC) /* {{{ */ { char *cipher_dir_string; char *module_dir_string; int block_size, max_key_length, use_key_length, i, count, iv_size; unsigned long int data_size; int *key_length_sizes; char *key_s = NULL, *iv_s; char *data_s; MCRYPT td; MCRYPT_GET_INI td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } /* Checking for key-length */ max_key_length = mcrypt_enc_get_key_size(td); if (key_len > max_key_length) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size of key is too large for this algorithm"); } key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count); if (count == 0 && key_length_sizes == NULL) { /* all lengths 1 - k_l_s = OK */ use_key_length = key_len; key_s = emalloc(use_key_length); memset(key_s, 0, use_key_length); memcpy(key_s, key, use_key_length); } else if (count == 1) { /* only m_k_l = OK */ key_s = emalloc(key_length_sizes[0]); memset(key_s, 0, key_length_sizes[0]); memcpy(key_s, key, MIN(key_len, key_length_sizes[0])); use_key_length = key_length_sizes[0]; } else { /* dertermine smallest supported key > length of requested key */ use_key_length = max_key_length; /* start with max key length */ for (i = 0; i < count; i++) { if (key_length_sizes[i] >= key_len && key_length_sizes[i] < use_key_length) { use_key_length = key_length_sizes[i]; } } key_s = emalloc(use_key_length); memset(key_s, 0, use_key_length); memcpy(key_s, key, MIN(key_len, use_key_length)); } mcrypt_free (key_length_sizes); /* Check IV */ iv_s = NULL; iv_size = mcrypt_enc_get_iv_size (td); /* IV is required */ if (mcrypt_enc_mode_has_iv(td) == 1) { if (argc == 5) { if (iv_size != iv_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE); } else { iv_s = emalloc(iv_size + 1); memcpy(iv_s, iv, iv_size); } } else if (argc == 4) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to use an empty IV, which is NOT recommend"); iv_s = emalloc(iv_size + 1); memset(iv_s, 0, iv_size + 1); } } /* Check blocksize */ if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed"); RETURN_FALSE; } if (dencrypt == MCRYPT_ENCRYPT) { mcrypt_generic(td, data_s, data_size); } else { mdecrypt_generic(td, data_s, data_size); } RETVAL_STRINGL(data_s, data_size, 1); /* freeing vars */ mcrypt_generic_end(td); if (key_s != NULL) { efree (key_s); } if (iv_s != NULL) { efree (iv_s); } efree (data_s); } /* }}} */ Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190 Target: 1 Example 2: Code: bool GLES2DecoderPassthroughImpl::ResizeOffscreenFramebuffer( const gfx::Size& size) { DCHECK(offscreen_); if (!emulated_back_buffer_) { LOG(ERROR) << "GLES2DecoderPassthroughImpl::ResizeOffscreenFramebuffer called " << " with an onscreen framebuffer."; return false; } if (emulated_back_buffer_->size == size) { return true; } if (size.width() < 0 || size.height() < 0 || size.width() > max_offscreen_framebuffer_size_ || size.height() > max_offscreen_framebuffer_size_) { LOG(ERROR) << "GLES2DecoderPassthroughImpl::ResizeOffscreenFramebuffer " "failed to allocate storage due to excessive dimensions."; return false; } CheckErrorCallbackState(); if (!emulated_back_buffer_->Resize(size, feature_info_.get())) { LOG(ERROR) << "GLES2DecoderPassthroughImpl::ResizeOffscreenFramebuffer " "failed to resize the emulated framebuffer."; return false; } if (CheckErrorCallbackState()) { LOG(ERROR) << "GLES2DecoderPassthroughImpl::ResizeOffscreenFramebuffer " "failed to resize the emulated framebuffer because errors " "were generated."; return false; } for (auto& available_color_texture : available_color_textures_) { DCHECK(available_color_texture->size != size); available_color_texture->Destroy(true); } available_color_textures_.clear(); return true; } 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 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: Ins_NROUND( TT_ExecContext exc, FT_Long* args ) { args[0] = Round_None( exc, args[0], exc->tt_metrics.compensations[exc->opcode - 0x6C] ); } Commit Message: 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: OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s) { OJPEGState* sp=(OJPEGState*)tif->tif_data; (void)s; if (sp->libjpeg_jpeg_query_style==0) { if (OJPEGDecodeRaw(tif,buf,cc)==0) return(0); } else { if (OJPEGDecodeScanlines(tif,buf,cc)==0) return(0); } return(1); } Commit Message: * libtiff/tif_ojpeg.c: make OJPEGDecode() early exit in case of failure in OJPEGPreDecode(). This will avoid a divide by zero, and potential other issues. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2611 CWE ID: CWE-369 Target: 1 Example 2: Code: ppp_set_compress(struct ppp *ppp, unsigned long arg) { int err; struct compressor *cp, *ocomp; struct ppp_option_data data; void *state, *ostate; unsigned char ccp_option[CCP_MAX_OPTION_LENGTH]; err = -EFAULT; if (copy_from_user(&data, (void __user *) arg, sizeof(data))) goto out; if (data.length > CCP_MAX_OPTION_LENGTH) goto out; if (copy_from_user(ccp_option, (void __user *) data.ptr, data.length)) goto out; err = -EINVAL; if (data.length < 2 || ccp_option[1] < 2 || ccp_option[1] > data.length) goto out; cp = try_then_request_module( find_compressor(ccp_option[0]), "ppp-compress-%d", ccp_option[0]); if (!cp) goto out; err = -ENOBUFS; if (data.transmit) { state = cp->comp_alloc(ccp_option, data.length); if (state) { ppp_xmit_lock(ppp); ppp->xstate &= ~SC_COMP_RUN; ocomp = ppp->xcomp; ostate = ppp->xc_state; ppp->xcomp = cp; ppp->xc_state = state; ppp_xmit_unlock(ppp); if (ostate) { ocomp->comp_free(ostate); module_put(ocomp->owner); } err = 0; } else module_put(cp->owner); } else { state = cp->decomp_alloc(ccp_option, data.length); if (state) { ppp_recv_lock(ppp); ppp->rstate &= ~SC_DECOMP_RUN; ocomp = ppp->rcomp; ostate = ppp->rc_state; ppp->rcomp = cp; ppp->rc_state = state; ppp_recv_unlock(ppp); if (ostate) { ocomp->decomp_free(ostate); module_put(ocomp->owner); } err = 0; } else module_put(cp->owner); } out: return err; } Commit Message: ppp: take reference on channels netns Let channels hold a reference on their network namespace. Some channel types, like ppp_async and ppp_synctty, can have their userspace controller running in a different namespace. Therefore they can't rely on them to preclude their netns from being removed from under them. ================================================================== BUG: KASAN: use-after-free in ppp_unregister_channel+0x372/0x3a0 at addr ffff880064e217e0 Read of size 8 by task syz-executor/11581 ============================================================================= BUG net_namespace (Not tainted): kasan: bad access detected ----------------------------------------------------------------------------- Disabling lock debugging due to kernel taint INFO: Allocated in copy_net_ns+0x6b/0x1a0 age=92569 cpu=3 pid=6906 [< none >] ___slab_alloc+0x4c7/0x500 kernel/mm/slub.c:2440 [< none >] __slab_alloc+0x4c/0x90 kernel/mm/slub.c:2469 [< inline >] slab_alloc_node kernel/mm/slub.c:2532 [< inline >] slab_alloc kernel/mm/slub.c:2574 [< none >] kmem_cache_alloc+0x23a/0x2b0 kernel/mm/slub.c:2579 [< inline >] kmem_cache_zalloc kernel/include/linux/slab.h:597 [< inline >] net_alloc kernel/net/core/net_namespace.c:325 [< none >] copy_net_ns+0x6b/0x1a0 kernel/net/core/net_namespace.c:360 [< none >] create_new_namespaces+0x2f6/0x610 kernel/kernel/nsproxy.c:95 [< none >] copy_namespaces+0x297/0x320 kernel/kernel/nsproxy.c:150 [< none >] copy_process.part.35+0x1bf4/0x5760 kernel/kernel/fork.c:1451 [< inline >] copy_process kernel/kernel/fork.c:1274 [< none >] _do_fork+0x1bc/0xcb0 kernel/kernel/fork.c:1723 [< inline >] SYSC_clone kernel/kernel/fork.c:1832 [< none >] SyS_clone+0x37/0x50 kernel/kernel/fork.c:1826 [< none >] entry_SYSCALL_64_fastpath+0x16/0x7a kernel/arch/x86/entry/entry_64.S:185 INFO: Freed in net_drop_ns+0x67/0x80 age=575 cpu=2 pid=2631 [< none >] __slab_free+0x1fc/0x320 kernel/mm/slub.c:2650 [< inline >] slab_free kernel/mm/slub.c:2805 [< none >] kmem_cache_free+0x2a0/0x330 kernel/mm/slub.c:2814 [< inline >] net_free kernel/net/core/net_namespace.c:341 [< none >] net_drop_ns+0x67/0x80 kernel/net/core/net_namespace.c:348 [< none >] cleanup_net+0x4e5/0x600 kernel/net/core/net_namespace.c:448 [< none >] process_one_work+0x794/0x1440 kernel/kernel/workqueue.c:2036 [< none >] worker_thread+0xdb/0xfc0 kernel/kernel/workqueue.c:2170 [< none >] kthread+0x23f/0x2d0 kernel/drivers/block/aoe/aoecmd.c:1303 [< none >] ret_from_fork+0x3f/0x70 kernel/arch/x86/entry/entry_64.S:468 INFO: Slab 0xffffea0001938800 objects=3 used=0 fp=0xffff880064e20000 flags=0x5fffc0000004080 INFO: Object 0xffff880064e20000 @offset=0 fp=0xffff880064e24200 CPU: 1 PID: 11581 Comm: syz-executor Tainted: G B 4.4.0+ Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014 00000000ffffffff ffff8800662c7790 ffffffff8292049d ffff88003e36a300 ffff880064e20000 ffff880064e20000 ffff8800662c77c0 ffffffff816f2054 ffff88003e36a300 ffffea0001938800 ffff880064e20000 0000000000000000 Call Trace: [< inline >] __dump_stack kernel/lib/dump_stack.c:15 [<ffffffff8292049d>] dump_stack+0x6f/0xa2 kernel/lib/dump_stack.c:50 [<ffffffff816f2054>] print_trailer+0xf4/0x150 kernel/mm/slub.c:654 [<ffffffff816f875f>] object_err+0x2f/0x40 kernel/mm/slub.c:661 [< inline >] print_address_description kernel/mm/kasan/report.c:138 [<ffffffff816fb0c5>] kasan_report_error+0x215/0x530 kernel/mm/kasan/report.c:236 [< inline >] kasan_report kernel/mm/kasan/report.c:259 [<ffffffff816fb4de>] __asan_report_load8_noabort+0x3e/0x40 kernel/mm/kasan/report.c:280 [< inline >] ? ppp_pernet kernel/include/linux/compiler.h:218 [<ffffffff83ad71b2>] ? ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392 [< inline >] ppp_pernet kernel/include/linux/compiler.h:218 [<ffffffff83ad71b2>] ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392 [< inline >] ? ppp_pernet kernel/drivers/net/ppp/ppp_generic.c:293 [<ffffffff83ad6f26>] ? ppp_unregister_channel+0xe6/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392 [<ffffffff83ae18f3>] ppp_asynctty_close+0xa3/0x130 kernel/drivers/net/ppp/ppp_async.c:241 [<ffffffff83ae1850>] ? async_lcp_peek+0x5b0/0x5b0 kernel/drivers/net/ppp/ppp_async.c:1000 [<ffffffff82c33239>] tty_ldisc_close.isra.1+0x99/0xe0 kernel/drivers/tty/tty_ldisc.c:478 [<ffffffff82c332c0>] tty_ldisc_kill+0x40/0x170 kernel/drivers/tty/tty_ldisc.c:744 [<ffffffff82c34943>] tty_ldisc_release+0x1b3/0x260 kernel/drivers/tty/tty_ldisc.c:772 [<ffffffff82c1ef21>] tty_release+0xac1/0x13e0 kernel/drivers/tty/tty_io.c:1901 [<ffffffff82c1e460>] ? release_tty+0x320/0x320 kernel/drivers/tty/tty_io.c:1688 [<ffffffff8174de36>] __fput+0x236/0x780 kernel/fs/file_table.c:208 [<ffffffff8174e405>] ____fput+0x15/0x20 kernel/fs/file_table.c:244 [<ffffffff813595ab>] task_work_run+0x16b/0x200 kernel/kernel/task_work.c:115 [< inline >] exit_task_work kernel/include/linux/task_work.h:21 [<ffffffff81307105>] do_exit+0x8b5/0x2c60 kernel/kernel/exit.c:750 [<ffffffff813fdd20>] ? debug_check_no_locks_freed+0x290/0x290 kernel/kernel/locking/lockdep.c:4123 [<ffffffff81306850>] ? mm_update_next_owner+0x6f0/0x6f0 kernel/kernel/exit.c:357 [<ffffffff813215e6>] ? __dequeue_signal+0x136/0x470 kernel/kernel/signal.c:550 [<ffffffff8132067b>] ? recalc_sigpending_tsk+0x13b/0x180 kernel/kernel/signal.c:145 [<ffffffff81309628>] do_group_exit+0x108/0x330 kernel/kernel/exit.c:880 [<ffffffff8132b9d4>] get_signal+0x5e4/0x14f0 kernel/kernel/signal.c:2307 [< inline >] ? kretprobe_table_lock kernel/kernel/kprobes.c:1113 [<ffffffff8151d355>] ? kprobe_flush_task+0xb5/0x450 kernel/kernel/kprobes.c:1158 [<ffffffff8115f7d3>] do_signal+0x83/0x1c90 kernel/arch/x86/kernel/signal.c:712 [<ffffffff8151d2a0>] ? recycle_rp_inst+0x310/0x310 kernel/include/linux/list.h:655 [<ffffffff8115f750>] ? setup_sigcontext+0x780/0x780 kernel/arch/x86/kernel/signal.c:165 [<ffffffff81380864>] ? finish_task_switch+0x424/0x5f0 kernel/kernel/sched/core.c:2692 [< inline >] ? finish_lock_switch kernel/kernel/sched/sched.h:1099 [<ffffffff81380560>] ? finish_task_switch+0x120/0x5f0 kernel/kernel/sched/core.c:2678 [< inline >] ? context_switch kernel/kernel/sched/core.c:2807 [<ffffffff85d794e9>] ? __schedule+0x919/0x1bd0 kernel/kernel/sched/core.c:3283 [<ffffffff81003901>] exit_to_usermode_loop+0xf1/0x1a0 kernel/arch/x86/entry/common.c:247 [< inline >] prepare_exit_to_usermode kernel/arch/x86/entry/common.c:282 [<ffffffff810062ef>] syscall_return_slowpath+0x19f/0x210 kernel/arch/x86/entry/common.c:344 [<ffffffff85d88022>] int_ret_from_sys_call+0x25/0x9f kernel/arch/x86/entry/entry_64.S:281 Memory state around the buggy address: ffff880064e21680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff880064e21700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff880064e21780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff880064e21800: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff880064e21880: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ================================================================== Fixes: 273ec51dd7ce ("net: ppp_generic - introduce net-namespace functionality v2") Reported-by: Baozeng Ding <[email protected]> Signed-off-by: Guillaume Nault <[email protected]> Reviewed-by: Cyrill Gorcunov <[email protected]> Signed-off-by: David S. Miller <[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: static int ext4_file_mmap(struct file *file, struct vm_area_struct *vma) { struct inode *inode = file->f_mapping->host; if (ext4_encrypted_inode(inode)) { int err = ext4_get_encryption_info(inode); if (err) return 0; if (ext4_encryption_info(inode) == NULL) return -ENOKEY; } file_accessed(file); if (IS_DAX(file_inode(file))) { vma->vm_ops = &ext4_dax_vm_ops; vma->vm_flags |= VM_MIXEDMAP | VM_HUGEPAGE; } else { vma->vm_ops = &ext4_file_vm_ops; } return 0; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[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: static Image *ReadWEBPImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; int webp_status; MagickBooleanType status; register unsigned char *p; size_t length; ssize_t count, y; unsigned char header[12], *stream; WebPDecoderConfig configure; WebPDecBuffer *magick_restrict webp_image = &configure.output; WebPBitstreamFeatures *magick_restrict features = &configure.input; /* 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); } if (WebPInitDecoderConfig(&configure) == 0) ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile"); webp_image->colorspace=MODE_RGBA; count=ReadBlob(image,12,header); if (count != 12) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); status=IsWEBP(header,count); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"CorruptImage"); length=(size_t) (ReadWebPLSBWord(header+4)+8); if (length < 12) ThrowReaderException(CorruptImageError,"CorruptImage"); stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream)); if (stream == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) memcpy(stream,header,12); count=ReadBlob(image,length-12,stream+12); if (count != (ssize_t) (length-12)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); webp_status=WebPGetFeatures(stream,length,features); if (webp_status == VP8_STATUS_OK) { image->columns=(size_t) features->width; image->rows=(size_t) features->height; image->depth=8; image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse; if (IsWEBPImageLossless(stream,length) != MagickFalse) image->quality=100; if (image_info->ping != MagickFalse) { stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } webp_status=WebPDecode(stream,length,&configure); } if (webp_status != VP8_STATUS_OK) { stream=(unsigned char*) RelinquishMagickMemory(stream); switch (webp_status) { case VP8_STATUS_OUT_OF_MEMORY: { ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); break; } case VP8_STATUS_INVALID_PARAM: { ThrowReaderException(CorruptImageError,"invalid parameter"); break; } case VP8_STATUS_BITSTREAM_ERROR: { ThrowReaderException(CorruptImageError,"CorruptImage"); break; } case VP8_STATUS_UNSUPPORTED_FEATURE: { ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported"); break; } case VP8_STATUS_SUSPENDED: { ThrowReaderException(CorruptImageError,"decoder suspended"); break; } case VP8_STATUS_USER_ABORT: { ThrowReaderException(CorruptImageError,"user abort"); break; } case VP8_STATUS_NOT_ENOUGH_DATA: { ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); break; } default: ThrowReaderException(CorruptImageError,"CorruptImage"); } } p=(unsigned char *) webp_image->u.RGBA.rgba; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *q; register ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } WebPFreeDecBuffer(webp_image); stream=(unsigned char*) RelinquishMagickMemory(stream); return(image); } Commit Message: Fixed fd leak for webp coder (patch from #382) CWE ID: CWE-119 Target: 1 Example 2: Code: fst_enable_intr(struct fst_card_info *card) { if (card->family == FST_FAMILY_TXU) { outl(0x0f0c0900, card->pci_conf + INTCSR_9054); } else { outw(0x0543, card->pci_conf + INTCSR_9052); } } Commit Message: farsync: fix info leak in ioctl The fst_get_iface() code fails to initialize the two padding bytes of struct sync_serial_settings after the ->loopback member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Dan Carpenter <[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: AtomicString PerformanceNavigationTiming::AlpnNegotiatedProtocol() const { return resource_timing_info_->FinalResponse().AlpnNegotiatedProtocol(); } Commit Message: Fix the |name| of PerformanceNavigationTiming Previously, the |name| of a PerformanceNavigationTiming entry was the initial URL (the request URL). After this CL, it is the response URL, so for example a url of the form 'redirect?location=newLoc' will have 'newLoc' as the |name|. Bug: 797465 Change-Id: Icab53ad8027d066422562c82bcf0354c264fea40 Reviewed-on: https://chromium-review.googlesource.com/996579 Reviewed-by: Yoav Weiss <[email protected]> Commit-Queue: Nicolás Peña Moreno <[email protected]> Cr-Commit-Position: refs/heads/master@{#548773} 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: void TypingCommand::insertText(Document& document, const String& text, Options options, TextCompositionType composition, const bool isIncrementalInsertion) { LocalFrame* frame = document.frame(); DCHECK(frame); if (!text.isEmpty()) document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing( isSpaceOrNewline(text[0])); insertText(document, text, frame->selection().computeVisibleSelectionInDOMTreeDeprecated(), options, composition, isIncrementalInsertion); } Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree| instead of |VisibleSelection| to reduce usage of |VisibleSelection| for improving code health. BUG=657237 TEST=n/a Review-Url: https://codereview.chromium.org/2733183002 Cr-Commit-Position: refs/heads/master@{#455368} CWE ID: Target: 1 Example 2: Code: static int vrend_decode_set_framebuffer_state(struct vrend_decode_ctx *ctx, int length) { if (length < 2) return EINVAL; uint32_t nr_cbufs = get_buf_entry(ctx, VIRGL_SET_FRAMEBUFFER_STATE_NR_CBUFS); uint32_t zsurf_handle = get_buf_entry(ctx, VIRGL_SET_FRAMEBUFFER_STATE_NR_ZSURF_HANDLE); uint32_t surf_handle[8]; int i; if (length != (2 + nr_cbufs)) return EINVAL; for (i = 0; i < nr_cbufs; i++) surf_handle[i] = get_buf_entry(ctx, VIRGL_SET_FRAMEBUFFER_STATE_CBUF_HANDLE(i)); vrend_set_framebuffer_state(ctx->grctx, nr_cbufs, surf_handle, zsurf_handle); return 0; } 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: bool PrintRenderFrameHelper::PrintPagesNative(blink::WebLocalFrame* frame, int page_count) { const PrintMsg_PrintPages_Params& params = *print_pages_params_; const PrintMsg_Print_Params& print_params = params.params; std::vector<int> printed_pages = GetPrintedPages(params, page_count); if (printed_pages.empty()) return false; PdfMetafileSkia metafile(print_params.printed_doc_type); CHECK(metafile.Init()); PrintHostMsg_DidPrintDocument_Params page_params; PrintPageInternal(print_params, printed_pages[0], page_count, frame, &metafile, &page_params.page_size, &page_params.content_area); for (size_t i = 1; i < printed_pages.size(); ++i) { PrintPageInternal(print_params, printed_pages[i], page_count, frame, &metafile, nullptr, nullptr); } FinishFramePrinting(); metafile.FinishDocument(); if (!CopyMetafileDataToSharedMem(metafile, &page_params.metafile_data_handle)) { return false; } page_params.data_size = metafile.GetDataSize(); page_params.document_cookie = print_params.document_cookie; #if defined(OS_WIN) page_params.physical_offsets = printer_printable_area_.origin(); #endif Send(new PrintHostMsg_DidPrintDocument(routing_id(), page_params)); return true; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Jianzhou Feng <[email protected]> Cr-Commit-Position: refs/heads/master@{#523966} 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 Maybe<int64_t> IndexOfValueImpl(Isolate* isolate, Handle<JSObject> receiver, Handle<Object> value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver)); Handle<SeededNumberDictionary> dictionary( SeededNumberDictionary::cast(receiver->elements()), isolate); for (uint32_t k = start_from; k < length; ++k) { int entry = dictionary->FindEntry(isolate, k); if (entry == SeededNumberDictionary::kNotFound) { continue; } PropertyDetails details = GetDetailsImpl(*dictionary, entry); switch (details.kind()) { case kData: { Object* element_k = dictionary->ValueAt(entry); if (value->StrictEquals(element_k)) { return Just<int64_t>(k); } break; } case kAccessor: { LookupIterator it(isolate, receiver, k, LookupIterator::OWN_SKIP_INTERCEPTOR); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); Handle<Object> element_k; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, element_k, JSObject::GetPropertyWithAccessor(&it), Nothing<int64_t>()); if (value->StrictEquals(*element_k)) return Just<int64_t>(k); if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) { return IndexOfValueSlowPath(isolate, receiver, value, k + 1, length); } if (*dictionary == receiver->elements()) continue; if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) { return IndexOfValueSlowPath(isolate, receiver, value, k + 1, length); } dictionary = handle( SeededNumberDictionary::cast(receiver->elements()), isolate); break; } } } return Just<int64_t>(-1); } Commit Message: Backport: Fix Object.entries/values with changing elements Bug: 111274046 Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \ /data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb (cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99) CWE ID: CWE-704 Target: 1 Example 2: Code: void CachedFileStream::reset() { savePos = (Guint)cc->tell(); cc->seek(start, SEEK_SET); saved = gTrue; bufPtr = bufEnd = buf; bufPos = start; } 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: HashTable *php_http_url_to_struct(const php_http_url_t *url, zval *strct TSRMLS_DC) { zval arr; if (strct) { switch (Z_TYPE_P(strct)) { default: zval_dtor(strct); array_init(strct); /* no break */ case IS_ARRAY: case IS_OBJECT: INIT_PZVAL_ARRAY((&arr), HASH_OF(strct)); break; } } else { INIT_PZVAL(&arr); array_init(&arr); } if (url) { if (url->scheme) { add_assoc_string(&arr, "scheme", url->scheme, 1); } if (url->user) { add_assoc_string(&arr, "user", url->user, 1); } if (url->pass) { add_assoc_string(&arr, "pass", url->pass, 1); } if (url->host) { add_assoc_string(&arr, "host", url->host, 1); } if (url->port) { add_assoc_long(&arr, "port", (long) url->port); } if (url->path) { add_assoc_string(&arr, "path", url->path, 1); } if (url->query) { add_assoc_string(&arr, "query", url->query, 1); } if (url->fragment) { add_assoc_string(&arr, "fragment", url->fragment, 1); } } return Z_ARRVAL(arr); } Commit Message: fix bug #71719 (Buffer overflow in HTTP url parsing functions) The parser's offset was not reset when we softfail in scheme parsing and continue to parse a path. Thanks to hlt99 at blinkenshell dot org for the report. 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: get_strings_2_svc(gstrings_arg *arg, struct svc_req *rqstp) { static gstrings_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_gstrings_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (! cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) && (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_INQUIRE, arg->princ, NULL))) { ret.code = KADM5_AUTH_GET; log_unauth("kadm5_get_strings", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_get_strings((void *)handle, arg->princ, &ret.strings, &ret.count); if (ret.code != 0) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_get_strings", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119 Target: 1 Example 2: Code: static void alterCurrentValue(PlatformUIElement element, int factor) { if (!element || !ATK_IS_VALUE(element)) return; GValue currentValue = G_VALUE_INIT; atk_value_get_current_value(ATK_VALUE(element), &currentValue); GValue increment = G_VALUE_INIT; atk_value_get_minimum_increment(ATK_VALUE(element), &increment); GValue newValue = G_VALUE_INIT; g_value_init(&newValue, G_TYPE_DOUBLE); g_value_set_float(&newValue, g_value_get_float(&currentValue) + factor * g_value_get_float(&increment)); atk_value_set_current_value(ATK_VALUE(element), &newValue); g_value_unset(&newValue); g_value_unset(&increment); g_value_unset(&currentValue); } Commit Message: [GTK][WTR] Implement AccessibilityUIElement::stringValue https://bugs.webkit.org/show_bug.cgi?id=102951 Reviewed by Martin Robinson. Implement AccessibilityUIElement::stringValue in the ATK backend in the same manner it is implemented in DumpRenderTree. * WebKitTestRunner/InjectedBundle/atk/AccessibilityUIElementAtk.cpp: (WTR::replaceCharactersForResults): (WTR): (WTR::AccessibilityUIElement::stringValue): git-svn-id: svn://svn.chromium.org/blink/trunk@135485 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: static int process_one_ticket(struct ceph_auth_client *ac, struct ceph_crypto_key *secret, void **p, void *end, void *dbuf, void *ticket_buf) { struct ceph_x_info *xi = ac->private; int type; u8 tkt_struct_v, blob_struct_v; struct ceph_x_ticket_handler *th; void *dp, *dend; int dlen; char is_enc; struct timespec validity; struct ceph_crypto_key old_key; void *tp, *tpend; struct ceph_timespec new_validity; struct ceph_crypto_key new_session_key; struct ceph_buffer *new_ticket_blob; unsigned long new_expires, new_renew_after; u64 new_secret_id; int ret; ceph_decode_need(p, end, sizeof(u32) + 1, bad); type = ceph_decode_32(p); dout(" ticket type %d %s\n", type, ceph_entity_type_name(type)); tkt_struct_v = ceph_decode_8(p); if (tkt_struct_v != 1) goto bad; th = get_ticket_handler(ac, type); if (IS_ERR(th)) { ret = PTR_ERR(th); goto out; } /* blob for me */ dlen = ceph_x_decrypt(secret, p, end, dbuf, TEMP_TICKET_BUF_LEN); if (dlen <= 0) { ret = dlen; goto out; } dout(" decrypted %d bytes\n", dlen); dp = dbuf; dend = dp + dlen; tkt_struct_v = ceph_decode_8(&dp); if (tkt_struct_v != 1) goto bad; memcpy(&old_key, &th->session_key, sizeof(old_key)); ret = ceph_crypto_key_decode(&new_session_key, &dp, dend); if (ret) goto out; ceph_decode_copy(&dp, &new_validity, sizeof(new_validity)); ceph_decode_timespec(&validity, &new_validity); new_expires = get_seconds() + validity.tv_sec; new_renew_after = new_expires - (validity.tv_sec / 4); dout(" expires=%lu renew_after=%lu\n", new_expires, new_renew_after); /* ticket blob for service */ ceph_decode_8_safe(p, end, is_enc, bad); tp = ticket_buf; if (is_enc) { /* encrypted */ dout(" encrypted ticket\n"); dlen = ceph_x_decrypt(&old_key, p, end, ticket_buf, TEMP_TICKET_BUF_LEN); if (dlen < 0) { ret = dlen; goto out; } dlen = ceph_decode_32(&tp); } else { /* unencrypted */ ceph_decode_32_safe(p, end, dlen, bad); ceph_decode_need(p, end, dlen, bad); ceph_decode_copy(p, ticket_buf, dlen); } tpend = tp + dlen; dout(" ticket blob is %d bytes\n", dlen); ceph_decode_need(&tp, tpend, 1 + sizeof(u64), bad); blob_struct_v = ceph_decode_8(&tp); new_secret_id = ceph_decode_64(&tp); ret = ceph_decode_buffer(&new_ticket_blob, &tp, tpend); if (ret) goto out; /* all is well, update our ticket */ ceph_crypto_key_destroy(&th->session_key); if (th->ticket_blob) ceph_buffer_put(th->ticket_blob); th->session_key = new_session_key; th->ticket_blob = new_ticket_blob; th->validity = new_validity; th->secret_id = new_secret_id; th->expires = new_expires; th->renew_after = new_renew_after; dout(" got ticket service %d (%s) secret_id %lld len %d\n", type, ceph_entity_type_name(type), th->secret_id, (int)th->ticket_blob->vec.iov_len); xi->have_keys |= th->service; out: return ret; bad: ret = -EINVAL; goto out; } Commit Message: libceph: do not hard code max auth ticket len We hard code cephx auth ticket buffer size to 256 bytes. This isn't enough for any moderate setups and, in case tickets themselves are not encrypted, leads to buffer overflows (ceph_x_decrypt() errors out, but ceph_decode_copy() doesn't - it's just a memcpy() wrapper). Since the buffer is allocated dynamically anyway, allocated it a bit later, at the point where we know how much is going to be needed. Fixes: http://tracker.ceph.com/issues/8979 Cc: [email protected] Signed-off-by: Ilya Dryomov <[email protected]> Reviewed-by: Sage Weil <[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: static struct svc_rdma_req_map *alloc_req_map(gfp_t flags) { struct svc_rdma_req_map *map; map = kmalloc(sizeof(*map), flags); if (map) INIT_LIST_HEAD(&map->free); return map; } 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: 1 Example 2: Code: mm_answer_bsdauthrespond(int sock, Buffer *m) { char *response; int authok; if (!options.kbd_interactive_authentication) fatal("%s: kbd-int authentication not enabled", __func__); if (authctxt->as == NULL) fatal("%s: no bsd auth session", __func__); response = buffer_get_string(m, NULL); authok = options.challenge_response_authentication && auth_userresponse(authctxt->as, response, 0); authctxt->as = NULL; debug3("%s: <%s> = <%d>", __func__, response, authok); free(response); buffer_clear(m); buffer_put_int(m, authok); debug3("%s: sending authenticated: %d", __func__, authok); mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m); auth_method = "keyboard-interactive"; auth_submethod = "bsdauth"; return (authok != 0); } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. 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: PHP_FUNCTION(locale_accept_from_http) { UEnumeration *available; char *http_accept = NULL; int http_accept_len; UErrorCode status = 0; int len; char resultLocale[INTL_MAX_LOCALE_LEN+1]; UAcceptResult outResult; if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &http_accept, &http_accept_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_accept_from_http: unable to parse input parameters", 0 TSRMLS_CC ); RETURN_FALSE; } available = ures_openAvailableLocales(NULL, &status); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to retrieve locale list"); len = uloc_acceptLanguageFromHTTP(resultLocale, INTL_MAX_LOCALE_LEN, &outResult, http_accept, available, &status); uenum_close(available); INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to find acceptable locale"); if (len < 0 || outResult == ULOC_ACCEPT_FAILED) { RETURN_FALSE; } RETURN_STRINGL(resultLocale, len, 1); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125 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 CreateTwoTabs(bool focus_tab_strip, LifecycleUnit** first_lifecycle_unit, LifecycleUnit** second_lifecycle_unit) { if (focus_tab_strip) source_->SetFocusedTabStripModelForTesting(tab_strip_model_.get()); task_runner_->FastForwardBy(kShortDelay); auto time_before_first_tab = NowTicks(); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)) .WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) { *first_lifecycle_unit = lifecycle_unit; if (focus_tab_strip) { EXPECT_TRUE(IsFocused(*first_lifecycle_unit)); } else { EXPECT_EQ(time_before_first_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); } })); std::unique_ptr<content::WebContents> first_web_contents = CreateAndNavigateWebContents(); content::WebContents* raw_first_web_contents = first_web_contents.get(); tab_strip_model_->AppendWebContents(std::move(first_web_contents), true); testing::Mock::VerifyAndClear(&source_observer_); EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_first_web_contents)); task_runner_->FastForwardBy(kShortDelay); auto time_before_second_tab = NowTicks(); EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_)) .WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) { *second_lifecycle_unit = lifecycle_unit; if (focus_tab_strip) { EXPECT_EQ(time_before_second_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); EXPECT_TRUE(IsFocused(*second_lifecycle_unit)); } else { EXPECT_EQ(time_before_first_tab, (*first_lifecycle_unit)->GetLastFocusedTime()); EXPECT_EQ(time_before_second_tab, (*second_lifecycle_unit)->GetLastFocusedTime()); } })); std::unique_ptr<content::WebContents> second_web_contents = CreateAndNavigateWebContents(); content::WebContents* raw_second_web_contents = second_web_contents.get(); tab_strip_model_->AppendWebContents(std::move(second_web_contents), true); testing::Mock::VerifyAndClear(&source_observer_); EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_second_web_contents)); raw_first_web_contents->WasHidden(); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID: Target: 1 Example 2: Code: bool first_word(const char *s, const char *word) { size_t sl, wl; assert(s); assert(word); sl = strlen(s); wl = strlen(word); if (sl < wl) return false; if (wl == 0) return true; if (memcmp(s, word, wl) != 0) return false; return s[wl] == 0 || strchr(WHITESPACE, s[wl]); } Commit Message: 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: long btrfs_ioctl_trans_end(struct file *file) { struct inode *inode = fdentry(file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; trans = file->private_data; if (!trans) return -EINVAL; file->private_data = NULL; btrfs_end_transaction(trans, root); atomic_dec(&root->fs_info->open_ioctl_trans); mnt_drop_write_file(file); return 0; } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <[email protected]> Reported-by: Pascal Junod <[email protected]> CWE ID: CWE-310 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: cJSON *cJSON_CreateArray( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_Array; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void addrconf_prefix_rcv(struct net_device *dev, u8 *opt, int len, bool sllao) { struct prefix_info *pinfo; __u32 valid_lft; __u32 prefered_lft; int addr_type; struct inet6_dev *in6_dev; struct net *net = dev_net(dev); pinfo = (struct prefix_info *) opt; if (len < sizeof(struct prefix_info)) { ADBG("addrconf: prefix option too short\n"); return; } /* * Validation checks ([ADDRCONF], page 19) */ addr_type = ipv6_addr_type(&pinfo->prefix); if (addr_type & (IPV6_ADDR_MULTICAST|IPV6_ADDR_LINKLOCAL)) return; valid_lft = ntohl(pinfo->valid); prefered_lft = ntohl(pinfo->prefered); if (prefered_lft > valid_lft) { net_warn_ratelimited("addrconf: prefix option has invalid lifetime\n"); return; } in6_dev = in6_dev_get(dev); if (in6_dev == NULL) { net_dbg_ratelimited("addrconf: device %s not configured\n", dev->name); return; } /* * Two things going on here: * 1) Add routes for on-link prefixes * 2) Configure prefixes with the auto flag set */ if (pinfo->onlink) { struct rt6_info *rt; unsigned long rt_expires; /* Avoid arithmetic overflow. Really, we could * save rt_expires in seconds, likely valid_lft, * but it would require division in fib gc, that it * not good. */ if (HZ > USER_HZ) rt_expires = addrconf_timeout_fixup(valid_lft, HZ); else rt_expires = addrconf_timeout_fixup(valid_lft, USER_HZ); if (addrconf_finite_timeout(rt_expires)) rt_expires *= HZ; rt = addrconf_get_prefix_route(&pinfo->prefix, pinfo->prefix_len, dev, RTF_ADDRCONF | RTF_PREFIX_RT, RTF_GATEWAY | RTF_DEFAULT); if (rt) { /* Autoconf prefix route */ if (valid_lft == 0) { ip6_del_rt(rt); rt = NULL; } else if (addrconf_finite_timeout(rt_expires)) { /* not infinity */ rt6_set_expires(rt, jiffies + rt_expires); } else { rt6_clean_expires(rt); } } else if (valid_lft) { clock_t expires = 0; int flags = RTF_ADDRCONF | RTF_PREFIX_RT; if (addrconf_finite_timeout(rt_expires)) { /* not infinity */ flags |= RTF_EXPIRES; expires = jiffies_to_clock_t(rt_expires); } addrconf_prefix_route(&pinfo->prefix, pinfo->prefix_len, dev, expires, flags); } ip6_rt_put(rt); } /* Try to figure out our local address for this prefix */ if (pinfo->autoconf && in6_dev->cnf.autoconf) { struct inet6_ifaddr *ifp; struct in6_addr addr; int create = 0, update_lft = 0; bool tokenized = false; if (pinfo->prefix_len == 64) { memcpy(&addr, &pinfo->prefix, 8); if (!ipv6_addr_any(&in6_dev->token)) { read_lock_bh(&in6_dev->lock); memcpy(addr.s6_addr + 8, in6_dev->token.s6_addr + 8, 8); read_unlock_bh(&in6_dev->lock); tokenized = true; } else if (ipv6_generate_eui64(addr.s6_addr + 8, dev) && ipv6_inherit_eui64(addr.s6_addr + 8, in6_dev)) { in6_dev_put(in6_dev); return; } goto ok; } net_dbg_ratelimited("IPv6 addrconf: prefix with wrong length %d\n", pinfo->prefix_len); in6_dev_put(in6_dev); return; ok: ifp = ipv6_get_ifaddr(net, &addr, dev, 1); if (ifp == NULL && valid_lft) { int max_addresses = in6_dev->cnf.max_addresses; u32 addr_flags = 0; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD if (in6_dev->cnf.optimistic_dad && !net->ipv6.devconf_all->forwarding && sllao) addr_flags = IFA_F_OPTIMISTIC; #endif /* Do not allow to create too much of autoconfigured * addresses; this would be too easy way to crash kernel. */ if (!max_addresses || ipv6_count_addresses(in6_dev) < max_addresses) ifp = ipv6_add_addr(in6_dev, &addr, NULL, pinfo->prefix_len, addr_type&IPV6_ADDR_SCOPE_MASK, addr_flags, valid_lft, prefered_lft); if (IS_ERR_OR_NULL(ifp)) { in6_dev_put(in6_dev); return; } update_lft = 0; create = 1; spin_lock_bh(&ifp->lock); ifp->flags |= IFA_F_MANAGETEMPADDR; ifp->cstamp = jiffies; ifp->tokenized = tokenized; spin_unlock_bh(&ifp->lock); addrconf_dad_start(ifp); } if (ifp) { u32 flags; unsigned long now; u32 stored_lft; /* update lifetime (RFC2462 5.5.3 e) */ spin_lock(&ifp->lock); now = jiffies; if (ifp->valid_lft > (now - ifp->tstamp) / HZ) stored_lft = ifp->valid_lft - (now - ifp->tstamp) / HZ; else stored_lft = 0; if (!update_lft && !create && stored_lft) { const u32 minimum_lft = min_t(u32, stored_lft, MIN_VALID_LIFETIME); valid_lft = max(valid_lft, minimum_lft); /* RFC4862 Section 5.5.3e: * "Note that the preferred lifetime of the * corresponding address is always reset to * the Preferred Lifetime in the received * Prefix Information option, regardless of * whether the valid lifetime is also reset or * ignored." * * So we should always update prefered_lft here. */ update_lft = 1; } if (update_lft) { ifp->valid_lft = valid_lft; ifp->prefered_lft = prefered_lft; ifp->tstamp = now; flags = ifp->flags; ifp->flags &= ~IFA_F_DEPRECATED; spin_unlock(&ifp->lock); if (!(flags&IFA_F_TENTATIVE)) ipv6_ifa_notify(0, ifp); } else spin_unlock(&ifp->lock); manage_tempaddrs(in6_dev, ifp, valid_lft, prefered_lft, create, now); in6_ifa_put(ifp); addrconf_verify(); } } inet6_prefix_notify(RTM_NEWPREFIX, in6_dev, pinfo); in6_dev_put(in6_dev); } Commit Message: ipv6: addrconf: validate new MTU before applying it Currently we don't check if the new MTU is valid or not and this allows one to configure a smaller than minimum allowed by RFCs or even bigger than interface own MTU, which is a problem as it may lead to packet drops. If you have a daemon like NetworkManager running, this may be exploited by remote attackers by forging RA packets with an invalid MTU, possibly leading to a DoS. (NetworkManager currently only validates for values too small, but not for too big ones.) The fix is just to make sure the new value is valid. That is, between IPV6_MIN_MTU and interface's MTU. Note that similar check is already performed at ndisc_router_discovery(), for when kernel itself parses the RA. Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: Sabrina Dubroca <[email protected]> Signed-off-by: David S. Miller <[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: u32 blk_mq_unique_tag(struct request *rq) { struct request_queue *q = rq->q; struct blk_mq_hw_ctx *hctx; int hwq = 0; if (q->mq_ops) { hctx = q->mq_ops->map_queue(q, rq->mq_ctx->cpu); hwq = hctx->queue_num; } return (hwq << BLK_MQ_UNIQUE_TAG_BITS) | (rq->tag & BLK_MQ_UNIQUE_TAG_MASK); } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[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: bool GetNetworkList(NetworkInterfaceList* networks, int policy) { int s = socket(AF_INET, SOCK_DGRAM, 0); if (s <= 0) { PLOG(ERROR) << "socket"; return false; } uint32_t num_ifs = 0; if (ioctl_netc_get_num_ifs(s, &num_ifs) < 0) { PLOG(ERROR) << "ioctl_netc_get_num_ifs"; PCHECK(close(s) == 0); return false; } for (uint32_t i = 0; i < num_ifs; ++i) { netc_if_info_t interface; if (ioctl_netc_get_if_info_at(s, &i, &interface) < 0) { PLOG(WARNING) << "ioctl_netc_get_if_info_at"; continue; } if (internal::IsLoopbackOrUnspecifiedAddress( reinterpret_cast<sockaddr*>(&(interface.addr)))) { continue; } IPEndPoint address; if (!address.FromSockAddr(reinterpret_cast<sockaddr*>(&(interface.addr)), sizeof(interface.addr))) { DLOG(WARNING) << "ioctl_netc_get_if_info returned invalid address."; continue; } int prefix_length = 0; IPEndPoint netmask; if (netmask.FromSockAddr(reinterpret_cast<sockaddr*>(&(interface.netmask)), sizeof(interface.netmask))) { prefix_length = MaskPrefixLength(netmask.address()); } int attributes = 0; networks->push_back( NetworkInterface(interface.name, interface.name, interface.index, NetworkChangeNotifier::CONNECTION_UNKNOWN, address.address(), prefix_length, attributes)); } PCHECK(close(s) == 0); return true; } Commit Message: Reland "[Fuchsia] Use Netstack FIDL interface to get network interfaces." This is a reland of b29fc269716e556be6b4e999bb4b24332cc43c6e Original change's description: > [Fuchsia] Use Netstack FIDL interface to get network interfaces. > > 1. Updated FILD GN template to generate and compile tables file, FIDL > generated code was failing to link without them. > 2. Updated GetNetworkList() for Fuchsia to FIDL API instead of ioctl(). > > Bug: 831384 > Change-Id: Ib90303a5110a465ea5f2bad787a7b63a2bf13f61 > Reviewed-on: https://chromium-review.googlesource.com/1023124 > Commit-Queue: Sergey Ulanov <[email protected]> > Reviewed-by: James Robinson <[email protected]> > Reviewed-by: Matt Menke <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554868} [email protected] Bug: 831384 Change-Id: Iabb29661680b835b947b2780d169e204fd5e2559 Reviewed-on: https://chromium-review.googlesource.com/1036484 Commit-Queue: Sergey Ulanov <[email protected]> Reviewed-by: Kevin Marshall <[email protected]> Cr-Commit-Position: refs/heads/master@{#554946} CWE ID: CWE-119 Target: 1 Example 2: Code: bool DoPort(const CHAR* spec, const Component& port, int default_port_for_scheme, CanonOutput* output, Component* out_port) { int port_num = ParsePort(spec, port); if (port_num == PORT_UNSPECIFIED || port_num == default_port_for_scheme) { *out_port = Component(); return true; // Leave port empty. } if (port_num == PORT_INVALID) { output->push_back(':'); out_port->begin = output->length(); AppendInvalidNarrowString(spec, port.begin, port.end(), output); out_port->len = output->length() - out_port->begin; return false; } const int buf_size = 6; char buf[buf_size]; WritePortInt(buf, buf_size, port_num); output->push_back(':'); out_port->begin = output->length(); for (int i = 0; i < buf_size && buf[i]; i++) output->push_back(buf[i]); out_port->len = output->length() - out_port->begin; return true; } Commit Message: Percent-encode UTF8 characters in URL fragment identifiers. This brings us into line with Firefox, Safari, and the spec. Bug: 758523 Change-Id: I7e354ab441222d9fd08e45f0e70f91ad4e35fafe Reviewed-on: https://chromium-review.googlesource.com/668363 Commit-Queue: Mike West <[email protected]> Reviewed-by: Jochen Eisinger <[email protected]> Reviewed-by: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#507481} CWE ID: CWE-79 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: inline void ImageLoader::dispatchErrorEvent() { m_hasPendingErrorEvent = true; errorEventSender().dispatchEventSoon(this); } Commit Message: Move ImageLoader timer to frame-specific TaskRunnerTimer. Move ImageLoader timer m_derefElementTimer to frame-specific TaskRunnerTimer. This associates it with the frame's Networking timer task queue. BUG=624694 Review-Url: https://codereview.chromium.org/2642103002 Cr-Commit-Position: refs/heads/master@{#444927} 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: SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Target: 1 Example 2: Code: static void kvm_vcpu_check_singlestep(struct kvm_vcpu *vcpu, unsigned long rflags, int *r) { struct kvm_run *kvm_run = vcpu->run; /* * rflags is the old, "raw" value of the flags. The new value has * not been saved yet. * * This is correct even for TF set by the guest, because "the * processor will not generate this exception after the instruction * that sets the TF flag". */ if (unlikely(rflags & X86_EFLAGS_TF)) { if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) { kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1 | DR6_RTM; kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip; kvm_run->debug.arch.exception = DB_VECTOR; kvm_run->exit_reason = KVM_EXIT_DEBUG; *r = EMULATE_USER_EXIT; } else { vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF; /* * "Certain debug exceptions may clear bit 0-3. The * remaining contents of the DR6 register are never * cleared by the processor". */ vcpu->arch.dr6 &= ~15; vcpu->arch.dr6 |= DR6_BS | DR6_RTM; kvm_queue_exception(vcpu, DB_VECTOR); } } } Commit Message: KVM: x86: Don't report guest userspace emulation error to userspace Commit fc3a9157d314 ("KVM: X86: Don't report L2 emulation failures to user-space") disabled the reporting of L2 (nested guest) emulation failures to userspace due to race-condition between a vmexit and the instruction emulator. The same rational applies also to userspace applications that are permitted by the guest OS to access MMIO area or perform PIO. This patch extends the current behavior - of injecting a #UD instead of reporting it to userspace - also for guest userspace code. Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[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: xid_map_enter(netdissect_options *ndo, const struct sunrpc_msg *rp, const u_char *bp) { const struct ip *ip = NULL; const struct ip6_hdr *ip6 = NULL; struct xid_map_entry *xmep; if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; break; case 6: ip6 = (const struct ip6_hdr *)bp; break; default: return (1); } xmep = &xid_map[xid_map_next]; if (++xid_map_next >= XIDMAPSIZE) xid_map_next = 0; UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid)); if (ip) { xmep->ipver = 4; UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src)); UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst)); } else if (ip6) { xmep->ipver = 6; UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src)); UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst)); } xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers); return (1); } Commit Message: CVE-2017-13005/NFS: Add two bounds checks before fetching data This fixes a buffer over-read discovered by Kamil Frankowicz. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 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: PHP_FUNCTION(imageaffine) { zval *IM; gdImagePtr src; gdImagePtr dst; gdRect rect; gdRectPtr pRect = NULL; zval *z_rect = NULL; zval *z_affine; zval **tmp; double affine[6]; int i, nelems; zval **zval_affine_elem = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|a", &IM, &z_affine, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, "Image", le_gd); if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine array must have six elements"); RETURN_FALSE; } for (i = 0; i < nelems; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) { switch (Z_TYPE_PP(zval_affine_elem)) { case IS_LONG: affine[i] = Z_LVAL_PP(zval_affine_elem); break; case IS_DOUBLE: affine[i] = Z_DVAL_PP(zval_affine_elem); break; case IS_STRING: convert_to_double_ex(zval_affine_elem); affine[i] = Z_DVAL_PP(zval_affine_elem); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (z_rect != NULL) { if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.x = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.y = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.width = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.height = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height"); RETURN_FALSE; } pRect = &rect; } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = NULL; } if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) { RETURN_FALSE; } if (dst == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, dst, le_gd); } } Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls CWE ID: CWE-189 Target: 1 Example 2: Code: void __exit rfcomm_cleanup_sockets(void) { bt_procfs_cleanup(&init_net, "rfcomm"); debugfs_remove(rfcomm_sock_debugfs); if (bt_sock_unregister(BTPROTO_RFCOMM) < 0) BT_ERR("RFCOMM socket layer unregistration failed"); proto_unregister(&rfcomm_proto); } Commit Message: Bluetooth: RFCOMM - Fix missing msg_namelen update in rfcomm_sock_recvmsg() If RFCOMM_DEFER_SETUP is set in the flags, rfcomm_sock_recvmsg() returns early with 0 without updating the possibly set msg_namelen member. This, in turn, leads to a 128 byte kernel stack leak in net/socket.c. Fix this by updating msg_namelen in this case. For all other cases it will be handled in bt_sock_stream_recvmsg(). Cc: Marcel Holtmann <[email protected]> Cc: Gustavo Padovan <[email protected]> Cc: Johan Hedberg <[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: gstd_get_export_name(gss_name_t client) { OM_uint32 maj; OM_uint32 min; gss_buffer_desc buf; unsigned char *bufp; unsigned char nibble; char *ret; size_t i, k; maj = gss_export_name(&min, client, &buf); GSTD_GSS_ERROR(maj, min, NULL, "gss_export_name"); if ((ret = (char *)malloc(buf.length * 2 + 1)) == NULL) { LOG(LOG_ERR, ("unable to malloc")); gss_release_buffer(&min, &buf); return NULL; } for (bufp = buf.value, i = 0, k = 0; i < buf.length; i++) { nibble = bufp[i] >> 4; ret[k++] = "0123456789ABCDEF"[nibble]; nibble = bufp[i] & 0x0f; ret[k++] = "0123456789ABCDEF"[nibble]; } ret[k] = '\0'; gss_release_buffer(&min, &buf); return ret; } Commit Message: knc: fix a couple of memory leaks. One of these can be remotely triggered during the authentication phase which leads to a remote DoS possibility. Pointed out by: Imre Rad <[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: v8::Local<v8::Object> V8Console::createConsole(InspectedContext* inspectedContext, bool hasMemoryAttribute) { v8::Local<v8::Context> context = inspectedContext->context(); v8::Context::Scope contextScope(context); v8::Isolate* isolate = context->GetIsolate(); v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Object> console = v8::Object::New(isolate); createBoundFunctionProperty(context, console, "debug", V8Console::debugCallback); createBoundFunctionProperty(context, console, "error", V8Console::errorCallback); createBoundFunctionProperty(context, console, "info", V8Console::infoCallback); createBoundFunctionProperty(context, console, "log", V8Console::logCallback); createBoundFunctionProperty(context, console, "warn", V8Console::warnCallback); createBoundFunctionProperty(context, console, "dir", V8Console::dirCallback); createBoundFunctionProperty(context, console, "dirxml", V8Console::dirxmlCallback); createBoundFunctionProperty(context, console, "table", V8Console::tableCallback); createBoundFunctionProperty(context, console, "trace", V8Console::traceCallback); createBoundFunctionProperty(context, console, "group", V8Console::groupCallback); createBoundFunctionProperty(context, console, "groupCollapsed", V8Console::groupCollapsedCallback); createBoundFunctionProperty(context, console, "groupEnd", V8Console::groupEndCallback); createBoundFunctionProperty(context, console, "clear", V8Console::clearCallback); createBoundFunctionProperty(context, console, "count", V8Console::countCallback); createBoundFunctionProperty(context, console, "assert", V8Console::assertCallback); createBoundFunctionProperty(context, console, "markTimeline", V8Console::markTimelineCallback); createBoundFunctionProperty(context, console, "profile", V8Console::profileCallback); createBoundFunctionProperty(context, console, "profileEnd", V8Console::profileEndCallback); createBoundFunctionProperty(context, console, "timeline", V8Console::timelineCallback); createBoundFunctionProperty(context, console, "timelineEnd", V8Console::timelineEndCallback); createBoundFunctionProperty(context, console, "time", V8Console::timeCallback); createBoundFunctionProperty(context, console, "timeEnd", V8Console::timeEndCallback); createBoundFunctionProperty(context, console, "timeStamp", V8Console::timeStampCallback); bool success = console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false); DCHECK(success); if (hasMemoryAttribute) console->SetAccessorProperty(toV8StringInternalized(isolate, "memory"), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memoryGetterCallback, console, 0).ToLocalChecked(), V8_FUNCTION_NEW_REMOVE_PROTOTYPE(context, V8Console::memorySetterCallback, v8::Local<v8::Value>(), 0).ToLocalChecked(), static_cast<v8::PropertyAttribute>(v8::None), v8::DEFAULT); console->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext)); return console; } 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 int _php_image_type (char data[8]) { #ifdef HAVE_LIBGD15 /* Based on ext/standard/image.c */ if (data == NULL) { return -1; } if (!memcmp(data, php_sig_gd2, 3)) { return PHP_GDIMG_TYPE_GD2; } else if (!memcmp(data, php_sig_jpg, 3)) { return PHP_GDIMG_TYPE_JPG; } else if (!memcmp(data, php_sig_png, 3)) { if (!memcmp(data, php_sig_png, 8)) { return PHP_GDIMG_TYPE_PNG; } } else if (!memcmp(data, php_sig_gif, 3)) { return PHP_GDIMG_TYPE_GIF; } #ifdef HAVE_GD_WBMP else { gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(8, data, 0); if (io_ctx) { if (getmbi((int(*)(void *)) gdGetC, io_ctx) == 0 && skipheader((int(*)(void *)) gdGetC, io_ctx) == 0 ) { #if HAVE_LIBGD204 io_ctx->gd_free(io_ctx); #else io_ctx->free(io_ctx); #endif return PHP_GDIMG_TYPE_WBM; } else { #if HAVE_LIBGD204 io_ctx->gd_free(io_ctx); #else io_ctx->free(io_ctx); #endif } } } #endif return -1; #endif } Commit Message: 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: char *FoFiType1::getName() { if (!parsed) { parse(); } return name; } 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: get_part_table_device_file (struct udev_device *given_device, const gchar *given_device_file, gchar **out_partition_table_syspath, guint64 *out_offset, guint64 *out_alignment_offset, guint *out_partition_number) { gchar *ret; guint64 offset; guint partition_number; const gchar *devpath; gchar *partition_table_syspath; guint64 alignment_offset; devpath = NULL; offset = 0; ret = NULL; partition_table_syspath = NULL; alignment_offset = 0; devpath = udev_device_get_syspath (given_device); if (devpath == NULL) goto out; partition_number = sysfs_get_int (devpath, "partition"); /* find device file for partition table device */ if (partition_number > 0) { struct udev_device *device; guint n; /* partition */ partition_table_syspath = g_strdup (devpath); for (n = strlen (partition_table_syspath) - 1; partition_table_syspath[n] != '/'; n--) partition_table_syspath[n] = '\0'; partition_table_syspath[n] = '\0'; device = udev_device_new_from_syspath (udev_device_get_udev (given_device), partition_table_syspath); if (device == NULL) { g_printerr ("Error getting udev device for syspath %s: %m\n", partition_table_syspath); goto out; } ret = g_strdup (udev_device_get_devnode (device)); udev_device_unref (device); if (ret == NULL) { /* This Should Not Happen™, but was reported in a distribution upgrade scenario, so handle it gracefully */ g_printerr ("Error getting devnode from udev device path %s: %m\n", partition_table_syspath); goto out; } offset = sysfs_get_uint64 (devpath, "start") * 512; alignment_offset = sysfs_get_uint64 (devpath, "alignment_offset"); } else { const char *targets_type; const char *encoded_targets_params; targets_type = g_getenv ("UDISKS_DM_TARGETS_TYPE"); if (targets_type == NULL) targets_type = udev_device_get_property_value (given_device, "UDISKS_DM_TARGETS_TYPE"); encoded_targets_params = g_getenv ("UDISKS_DM_TARGETS_PARAMS"); if (encoded_targets_params == NULL) encoded_targets_params = udev_device_get_property_value (given_device, "UDISKS_DM_TARGETS_PARAMS"); if (g_strcmp0 (targets_type, "linear") == 0) { gint partition_slave_major; gchar *targets_params; targets_params = decode_udev_encoded_string (encoded_targets_params); if (targets_params == NULL || sscanf (targets_params, "%d:%d\x20%" G_GUINT64_FORMAT, &partition_slave_major, &partition_slave_minor, &offset_sectors) != 3) { g_printerr ("Error decoding UDISKS_DM_TARGETS_PARAMS=`%s'\n", targets_params); } else { struct udev_device *mp_device; mp_device = udev_device_new_from_devnum (udev_device_get_udev (given_device), 'b', makedev (partition_slave_major, partition_slave_minor)); if (mp_device != NULL) { const char *dm_name; gint n; /* now figure out the partition number... we infer this from DM_NAME */ partition_number = 0; dm_name = g_getenv ("DM_NAME"); if (dm_name == NULL) dm_name = udev_device_get_property_value (given_device, "DM_NAME"); if (dm_name == NULL || strlen (dm_name) == 0) { g_printerr ("DM_NAME not available\n"); goto out; } for (n = strlen (dm_name) - 1; n >= 0; n--) { if (!isdigit (dm_name[n])) break; } if (n < 0 || dm_name[n] != 'p') { g_printerr ("DM_NAME=`%s' is malformed (expected <name>p<number>)\n", dm_name); goto out; } partition_number = atoi (dm_name + n + 1); if (partition_number < 1) { g_printerr ("Error determining partition number from DM_NAME=`%s'\n", dm_name); goto out; } ret = g_strdup (udev_device_get_devnode (mp_device)); offset = offset_sectors * 512; partition_table_syspath = g_strdup (udev_device_get_syspath (mp_device)); udev_device_unref (mp_device); g_free (targets_params); /* TODO: set alignment_offset */ goto out; } } g_free (targets_params); } /* not a kernel partition */ partition_table_syspath = g_strdup (devpath); ret = g_strdup (given_device_file); partition_number = 0; } out: if (out_offset != NULL) *out_offset = offset; if (out_partition_number != NULL) *out_partition_number = partition_number; if (out_partition_table_syspath != NULL) *out_partition_table_syspath = partition_table_syspath; else g_free (partition_table_syspath); if (out_alignment_offset != NULL) *out_alignment_offset = alignment_offset; return ret; } Commit Message: CWE ID: CWE-200 Target: 1 Example 2: Code: static int inet_insert_ifa(struct in_ifaddr *ifa) { return __inet_insert_ifa(ifa, NULL, 0); } Commit Message: ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <[email protected]> Signed-off-by: David S. Miller <[email protected]> Tested-by: Cyrill Gorcunov <[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: PaintPropertyTreeBuilderFragmentContext() : current_effect(EffectPaintPropertyNode::Root()) { current.clip = absolute_position.clip = fixed_position.clip = ClipPaintPropertyNode::Root(); current.transform = absolute_position.transform = fixed_position.transform = TransformPaintPropertyNode::Root(); current.scroll = absolute_position.scroll = fixed_position.scroll = ScrollPaintPropertyNode::Root(); } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} 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 UINT drdynvc_virtual_channel_event_data_received(drdynvcPlugin* drdynvc, void* pData, UINT32 dataLength, UINT32 totalLength, UINT32 dataFlags) { wStream* data_in; if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME)) { return CHANNEL_RC_OK; } if (dataFlags & CHANNEL_FLAG_FIRST) { if (drdynvc->data_in) Stream_Free(drdynvc->data_in, TRUE); drdynvc->data_in = Stream_New(NULL, totalLength); } if (!(data_in = drdynvc->data_in)) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } if (!Stream_EnsureRemainingCapacity(data_in, (int) dataLength)) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!"); Stream_Free(drdynvc->data_in, TRUE); drdynvc->data_in = NULL; return ERROR_INTERNAL_ERROR; } Stream_Write(data_in, pData, dataLength); if (dataFlags & CHANNEL_FLAG_LAST) { if (Stream_Capacity(data_in) != Stream_GetPosition(data_in)) { WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_plugin_process_received: read error"); return ERROR_INVALID_DATA; } drdynvc->data_in = NULL; Stream_SealLength(data_in); Stream_SetPosition(data_in, 0); if (!MessageQueue_Post(drdynvc->queue, NULL, 0, (void*) data_in, NULL)) { WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Post failed!"); return ERROR_INTERNAL_ERROR; } } return CHANNEL_RC_OK; } Commit Message: Fix for #4866: Added additional length checks CWE ID: Target: 1 Example 2: Code: long keyctl_set_reqkey_keyring(int reqkey_defl) { struct cred *new; int ret, old_setting; old_setting = current_cred_xxx(jit_keyring); if (reqkey_defl == KEY_REQKEY_DEFL_NO_CHANGE) return old_setting; new = prepare_creds(); if (!new) return -ENOMEM; switch (reqkey_defl) { case KEY_REQKEY_DEFL_THREAD_KEYRING: ret = install_thread_keyring_to_cred(new); if (ret < 0) goto error; goto set; case KEY_REQKEY_DEFL_PROCESS_KEYRING: ret = install_process_keyring_to_cred(new); if (ret < 0) { if (ret != -EEXIST) goto error; ret = 0; } goto set; case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_SESSION_KEYRING: case KEY_REQKEY_DEFL_USER_KEYRING: case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: goto set; case KEY_REQKEY_DEFL_NO_CHANGE: case KEY_REQKEY_DEFL_GROUP_KEYRING: default: ret = -EINVAL; goto error; } set: new->jit_keyring = reqkey_defl; commit_creds(new); return old_setting; error: abort_creds(new); return ret; } Commit Message: KEYS: Fix race between read and revoke This fixes CVE-2015-7550. There's a race between keyctl_read() and keyctl_revoke(). If the revoke happens between keyctl_read() checking the validity of a key and the key's semaphore being taken, then the key type read method will see a revoked key. This causes a problem for the user-defined key type because it assumes in its read method that there will always be a payload in a non-revoked key and doesn't check for a NULL pointer. Fix this by making keyctl_read() check the validity of a key after taking semaphore instead of before. I think the bug was introduced with the original keyrings code. This was discovered by a multithreaded test program generated by syzkaller (http://github.com/google/syzkaller). Here's a cleaned up version: #include <sys/types.h> #include <keyutils.h> #include <pthread.h> void *thr0(void *arg) { key_serial_t key = (unsigned long)arg; keyctl_revoke(key); return 0; } void *thr1(void *arg) { key_serial_t key = (unsigned long)arg; char buffer[16]; keyctl_read(key, buffer, 16); return 0; } int main() { key_serial_t key = add_key("user", "%", "foo", 3, KEY_SPEC_USER_KEYRING); pthread_t th[5]; pthread_create(&th[0], 0, thr0, (void *)(unsigned long)key); pthread_create(&th[1], 0, thr1, (void *)(unsigned long)key); pthread_create(&th[2], 0, thr0, (void *)(unsigned long)key); pthread_create(&th[3], 0, thr1, (void *)(unsigned long)key); pthread_join(th[0], 0); pthread_join(th[1], 0); pthread_join(th[2], 0); pthread_join(th[3], 0); return 0; } Build as: cc -o keyctl-race keyctl-race.c -lkeyutils -lpthread Run as: while keyctl-race; do :; done as it may need several iterations to crash the kernel. The crash can be summarised as: BUG: unable to handle kernel NULL pointer dereference at 0000000000000010 IP: [<ffffffff81279b08>] user_read+0x56/0xa3 ... Call Trace: [<ffffffff81276aa9>] keyctl_read_key+0xb6/0xd7 [<ffffffff81277815>] SyS_keyctl+0x83/0xe0 [<ffffffff815dbb97>] entry_SYSCALL_64_fastpath+0x12/0x6f Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: David Howells <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: [email protected] Signed-off-by: James Morris <[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: void RTCPeerConnectionHandlerChromium::setLocalDescription(PassRefPtr<RTCVoidRequest> request, PassRefPtr<RTCSessionDescriptionDescriptor> sessionDescription) { if (!m_webHandler) return; m_webHandler->setLocalDescription(request, sessionDescription); } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec) { struct drm_vc4_submit_cl *args = exec->args; void *temp = NULL; void *bin; int ret = 0; uint32_t bin_offset = 0; uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size, 16); uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size; uint32_t exec_size = uniforms_offset + args->uniforms_size; uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) * args->shader_rec_count); struct vc4_bo *bo; if (uniforms_offset < shader_rec_offset || exec_size < uniforms_offset || args->shader_rec_count >= (UINT_MAX / sizeof(struct vc4_shader_state)) || temp_size < exec_size) { DRM_ERROR("overflow in exec arguments\n"); goto fail; } /* Allocate space where we'll store the copied in user command lists * and shader records. * * We don't just copy directly into the BOs because we need to * read the contents back for validation, and I think the * bo->vaddr is uncached access. */ temp = drm_malloc_ab(temp_size, 1); if (!temp) { DRM_ERROR("Failed to allocate storage for copying " "in bin/render CLs.\n"); ret = -ENOMEM; goto fail; } bin = temp + bin_offset; exec->shader_rec_u = temp + shader_rec_offset; exec->uniforms_u = temp + uniforms_offset; exec->shader_state = temp + exec_size; exec->shader_state_size = args->shader_rec_count; if (copy_from_user(bin, (void __user *)(uintptr_t)args->bin_cl, args->bin_cl_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->shader_rec_u, (void __user *)(uintptr_t)args->shader_rec, args->shader_rec_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->uniforms_u, (void __user *)(uintptr_t)args->uniforms, args->uniforms_size)) { ret = -EFAULT; goto fail; } bo = vc4_bo_create(dev, exec_size, true); if (IS_ERR(bo)) { DRM_ERROR("Couldn't allocate BO for binning\n"); ret = PTR_ERR(bo); goto fail; } exec->exec_bo = &bo->base; list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head, &exec->unref_list); exec->ct0ca = exec->exec_bo->paddr + bin_offset; exec->bin_u = bin; exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset; exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset; exec->shader_rec_size = args->shader_rec_size; exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset; exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset; exec->uniforms_size = args->uniforms_size; ret = vc4_validate_bin_cl(dev, exec->exec_bo->vaddr + bin_offset, bin, exec); if (ret) goto fail; ret = vc4_validate_shader_recs(dev, exec); if (ret) goto fail; /* Block waiting on any previous rendering into the CS's VBO, * IB, or textures, so that pixels are actually written by the * time we try to read them. */ ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true); fail: drm_free_large(temp); return ret; } Commit Message: drm/vc4: Fix an integer overflow in temporary allocation layout. We copy the unvalidated ioctl arguments from the user into kernel temporary memory to run the validation from, to avoid a race where the user updates the unvalidate contents in between validating them and copying them into the validated BO. However, in setting up the layout of the kernel side, we failed to check one of the additions (the roundup() for shader_rec_offset) against integer overflow, allowing a nearly MAX_UINT value of bin_cl_size to cause us to under-allocate the temporary space that we then copy_from_user into. Reported-by: Murray McAllister <[email protected]> Signed-off-by: Eric Anholt <[email protected]> Fixes: d5b1a78a772f ("drm/vc4: Add support for drawing 3D frames.") CWE ID: CWE-190 Target: 1 Example 2: Code: GLuint GLES2DecoderImpl::DoGetMaxValueInBufferCHROMIUM( GLuint buffer_id, GLsizei count, GLenum type, GLuint offset) { GLuint max_vertex_accessed = 0; Buffer* buffer = GetBuffer(buffer_id); if (!buffer) { LOCAL_SET_GL_ERROR( GL_INVALID_VALUE, "GetMaxValueInBufferCHROMIUM", "unknown buffer"); } else { if (!buffer->GetMaxValueForRange( offset, count, type, state_.enable_flags.primitive_restart_fixed_index, &max_vertex_accessed)) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "GetMaxValueInBufferCHROMIUM", "range out of bounds for buffer"); } } return max_vertex_accessed; } 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 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 RenderBox::styleWillChange(StyleDifference diff, const RenderStyle& newStyle) { RenderStyle* oldStyle = style(); if (oldStyle) { if (diff >= StyleDifferenceRepaint && node() && (isHTMLHtmlElement(*node()) || isHTMLBodyElement(*node()))) { view()->repaint(); if (oldStyle->hasEntirelyFixedBackground() != newStyle.hasEntirelyFixedBackground()) view()->compositor()->setNeedsUpdateFixedBackground(); } if (diff == StyleDifferenceLayout && parent() && oldStyle->position() != newStyle.position()) { markContainingBlocksForLayout(); if (oldStyle->position() == StaticPosition) repaint(); else if (newStyle.hasOutOfFlowPosition()) parent()->setChildNeedsLayout(); if (isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition()) removeFloatingOrPositionedChildFromBlockLists(); } } else if (isBody()) view()->repaint(); RenderBoxModelObject::styleWillChange(diff, newStyle); } 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:
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 start_decoder(vorb *f) { uint8 header[6], x,y; int len,i,j,k, max_submaps = 0; int longest_floorlist=0; if (!start_page(f)) return FALSE; if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); if (f->segments[0] != 30) { if (f->segments[0] == 64 && getn(f, header, 6) && header[0] == 'f' && header[1] == 'i' && header[2] == 's' && header[3] == 'h' && header[4] == 'e' && header[5] == 'a' && get8(f) == 'd' && get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported); else return error(f, VORBIS_invalid_first_page); } if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); get32(f); // bitrate_maximum get32(f); // bitrate_nominal get32(f); // bitrate_minimum x = get8(f); { int log0,log1; log0 = x & 15; log1 = x >> 4; f->blocksize_0 = 1 << log0; f->blocksize_1 = 1 << log1; if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); if (log0 > log1) return error(f, VORBIS_invalid_setup); } x = get8(f); if (!(x & 1)) return error(f, VORBIS_invalid_first_page); if (!start_page(f)) return FALSE; if (!start_packet(f)) return FALSE; do { len = next_segment(f); skip(f, len); f->bytes_in_seg = 0; } while (len); if (!start_packet(f)) return FALSE; #ifndef STB_VORBIS_NO_PUSHDATA_API if (IS_PUSH_MODE(f)) { if (!is_whole_packet_present(f, TRUE)) { if (f->error == VORBIS_invalid_stream) f->error = VORBIS_invalid_setup; return FALSE; } } #endif crc32_init(); // always init it, to avoid multithread race conditions if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); for (i=0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); f->codebook_count = get_bits(f,8) + 1; f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); if (f->codebooks == NULL) return error(f, VORBIS_outofmem); memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); for (i=0; i < f->codebook_count; ++i) { uint32 *values; int ordered, sorted_count; int total=0; uint8 *lengths; Codebook *c = f->codebooks+i; CHECK(f); x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); c->dimensions = (get_bits(f, 8)<<8) + x; x = get_bits(f, 8); y = get_bits(f, 8); c->entries = (get_bits(f, 8)<<16) + (y<<8) + x; ordered = get_bits(f,1); c->sparse = ordered ? 0 : get_bits(f,1); if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); if (c->sparse) lengths = (uint8 *) setup_temp_malloc(f, c->entries); else lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (!lengths) return error(f, VORBIS_outofmem); if (ordered) { int current_entry = 0; int current_length = get_bits(f,5) + 1; while (current_entry < c->entries) { int limit = c->entries - current_entry; int n = get_bits(f, ilog(limit)); if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); } memset(lengths + current_entry, current_length, n); current_entry += n; ++current_length; } } else { for (j=0; j < c->entries; ++j) { int present = c->sparse ? get_bits(f,1) : 1; if (present) { lengths[j] = get_bits(f, 5) + 1; ++total; if (lengths[j] == 32) return error(f, VORBIS_invalid_setup); } else { lengths[j] = NO_CODE; } } } if (c->sparse && total >= c->entries >> 2) { if (c->entries > (int) f->setup_temp_memory_required) f->setup_temp_memory_required = c->entries; c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); memcpy(c->codeword_lengths, lengths, c->entries); setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! lengths = c->codeword_lengths; c->sparse = 0; } if (c->sparse) { sorted_count = total; } else { sorted_count = 0; #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH for (j=0; j < c->entries; ++j) if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) ++sorted_count; #endif } c->sorted_entries = sorted_count; values = NULL; CHECK(f); if (!c->sparse) { c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries); if (!c->codewords) return error(f, VORBIS_outofmem); } else { unsigned int size; if (c->sorted_entries) { c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries); if (!c->codeword_lengths) return error(f, VORBIS_outofmem); c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); if (!c->codewords) return error(f, VORBIS_outofmem); values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); if (!values) return error(f, VORBIS_outofmem); } size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; if (size > f->setup_temp_memory_required) f->setup_temp_memory_required = size; } if (!compute_codewords(c, lengths, c->entries, values)) { if (c->sparse) setup_temp_free(f, values, 0); return error(f, VORBIS_invalid_setup); } if (c->sorted_entries) { c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1)); if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1)); if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); ++c->sorted_values; c->sorted_values[-1] = -1; compute_sorted_huffman(c, lengths, values); } if (c->sparse) { setup_temp_free(f, values, sizeof(*values)*c->sorted_entries); setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); setup_temp_free(f, lengths, c->entries); c->codewords = NULL; } compute_accelerated_huffman(c); CHECK(f); c->lookup_type = get_bits(f, 4); if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); if (c->lookup_type > 0) { uint16 *mults; c->minimum_value = float32_unpack(get_bits(f, 32)); c->delta_value = float32_unpack(get_bits(f, 32)); c->value_bits = get_bits(f, 4)+1; c->sequence_p = get_bits(f,1); if (c->lookup_type == 1) { c->lookup_values = lookup1_values(c->entries, c->dimensions); } else { c->lookup_values = c->entries * c->dimensions; } if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); if (mults == NULL) return error(f, VORBIS_outofmem); for (j=0; j < (int) c->lookup_values; ++j) { int q = get_bits(f, c->value_bits); if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } mults[j] = q; } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int len, sparse = c->sparse; float last=0; if (sparse) { if (c->sorted_entries == 0) goto skip; c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); } else c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } len = sparse ? c->sorted_entries : c->entries; for (j=0; j < len; ++j) { unsigned int z = sparse ? c->sorted_values[j] : j; unsigned int div=1; for (k=0; k < c->dimensions; ++k) { int off = (z / div) % c->lookup_values; float val = mults[off]; val = mults[off]*c->delta_value + c->minimum_value + last; c->multiplicands[j*c->dimensions + k] = val; if (c->sequence_p) last = val; if (k+1 < c->dimensions) { if (div > UINT_MAX / (unsigned int) c->lookup_values) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } div *= c->lookup_values; } } } c->lookup_type = 2; } else #endif { float last=0; CHECK(f); c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } for (j=0; j < (int) c->lookup_values; ++j) { float val = mults[j] * c->delta_value + c->minimum_value + last; c->multiplicands[j] = val; if (c->sequence_p) last = val; } } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK skip:; #endif setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); CHECK(f); } CHECK(f); } x = get_bits(f, 6) + 1; for (i=0; i < x; ++i) { uint32 z = get_bits(f, 16); if (z != 0) return error(f, VORBIS_invalid_setup); } f->floor_count = get_bits(f, 6)+1; f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); if (f->floor_config == NULL) return error(f, VORBIS_outofmem); for (i=0; i < f->floor_count; ++i) { f->floor_types[i] = get_bits(f, 16); if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); if (f->floor_types[i] == 0) { Floor0 *g = &f->floor_config[i].floor0; g->order = get_bits(f,8); g->rate = get_bits(f,16); g->bark_map_size = get_bits(f,16); g->amplitude_bits = get_bits(f,6); g->amplitude_offset = get_bits(f,8); g->number_of_books = get_bits(f,4) + 1; for (j=0; j < g->number_of_books; ++j) g->book_list[j] = get_bits(f,8); return error(f, VORBIS_feature_not_supported); } else { stbv__floor_ordering p[31*8+2]; Floor1 *g = &f->floor_config[i].floor1; int max_class = -1; g->partitions = get_bits(f, 5); for (j=0; j < g->partitions; ++j) { g->partition_class_list[j] = get_bits(f, 4); if (g->partition_class_list[j] > max_class) max_class = g->partition_class_list[j]; } for (j=0; j <= max_class; ++j) { g->class_dimensions[j] = get_bits(f, 3)+1; g->class_subclasses[j] = get_bits(f, 2); if (g->class_subclasses[j]) { g->class_masterbooks[j] = get_bits(f, 8); if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } for (k=0; k < 1 << g->class_subclasses[j]; ++k) { g->subclass_books[j][k] = get_bits(f,8)-1; if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } } g->floor1_multiplier = get_bits(f,2)+1; g->rangebits = get_bits(f,4); g->Xlist[0] = 0; g->Xlist[1] = 1 << g->rangebits; g->values = 2; for (j=0; j < g->partitions; ++j) { int c = g->partition_class_list[j]; for (k=0; k < g->class_dimensions[c]; ++k) { g->Xlist[g->values] = get_bits(f, g->rangebits); ++g->values; } } for (j=0; j < g->values; ++j) { p[j].x = g->Xlist[j]; p[j].id = j; } qsort(p, g->values, sizeof(p[0]), point_compare); for (j=0; j < g->values; ++j) g->sorted_order[j] = (uint8) p[j].id; for (j=2; j < g->values; ++j) { int low,hi; neighbors(g->Xlist, j, &low,&hi); g->neighbors[j][0] = low; g->neighbors[j][1] = hi; } if (g->values > longest_floorlist) longest_floorlist = g->values; } } f->residue_count = get_bits(f, 6)+1; f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); if (f->residue_config == NULL) return error(f, VORBIS_outofmem); memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); for (i=0; i < f->residue_count; ++i) { uint8 residue_cascade[64]; Residue *r = f->residue_config+i; f->residue_types[i] = get_bits(f, 16); if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); r->begin = get_bits(f, 24); r->end = get_bits(f, 24); if (r->end < r->begin) return error(f, VORBIS_invalid_setup); r->part_size = get_bits(f,24)+1; r->classifications = get_bits(f,6)+1; r->classbook = get_bits(f,8); if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); for (j=0; j < r->classifications; ++j) { uint8 high_bits=0; uint8 low_bits=get_bits(f,3); if (get_bits(f,1)) high_bits = get_bits(f,5); residue_cascade[j] = high_bits*8 + low_bits; } r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); if (r->residue_books == NULL) return error(f, VORBIS_outofmem); for (j=0; j < r->classifications; ++j) { for (k=0; k < 8; ++k) { if (residue_cascade[j] & (1 << k)) { r->residue_books[j][k] = get_bits(f, 8); if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } else { r->residue_books[j][k] = -1; } } } r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); if (!r->classdata) return error(f, VORBIS_outofmem); memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); for (j=0; j < f->codebooks[r->classbook].entries; ++j) { int classwords = f->codebooks[r->classbook].dimensions; int temp = j; r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); for (k=classwords-1; k >= 0; --k) { r->classdata[j][k] = temp % r->classifications; temp /= r->classifications; } } } f->mapping_count = get_bits(f,6)+1; f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); if (f->mapping == NULL) return error(f, VORBIS_outofmem); memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); for (i=0; i < f->mapping_count; ++i) { Mapping *m = f->mapping + i; int mapping_type = get_bits(f,16); if (mapping_type != 0) return error(f, VORBIS_invalid_setup); m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan)); if (m->chan == NULL) return error(f, VORBIS_outofmem); if (get_bits(f,1)) m->submaps = get_bits(f,4)+1; else m->submaps = 1; if (m->submaps > max_submaps) max_submaps = m->submaps; if (get_bits(f,1)) { m->coupling_steps = get_bits(f,8)+1; for (k=0; k < m->coupling_steps; ++k) { m->chan[k].magnitude = get_bits(f, ilog(f->channels-1)); m->chan[k].angle = get_bits(f, ilog(f->channels-1)); if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); } } else m->coupling_steps = 0; if (get_bits(f,2)) return error(f, VORBIS_invalid_setup); if (m->submaps > 1) { for (j=0; j < f->channels; ++j) { m->chan[j].mux = get_bits(f, 4); if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); } } else for (j=0; j < f->channels; ++j) m->chan[j].mux = 0; for (j=0; j < m->submaps; ++j) { get_bits(f,8); // discard m->submap_floor[j] = get_bits(f,8); m->submap_residue[j] = get_bits(f,8); if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); } } f->mode_count = get_bits(f, 6)+1; for (i=0; i < f->mode_count; ++i) { Mode *m = f->mode_config+i; m->blockflag = get_bits(f,1); m->windowtype = get_bits(f,16); m->transformtype = get_bits(f,16); m->mapping = get_bits(f,8); if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); } flush_packet(f); f->previous_length = 0; for (i=0; i < f->channels; ++i) { f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1); f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist); if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1); #ifdef STB_VORBIS_NO_DEFER_FLOOR f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); #endif } if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; f->blocksize[0] = f->blocksize_0; f->blocksize[1] = f->blocksize_1; #ifdef STB_VORBIS_DIVIDE_TABLE if (integer_divide_table[1][1]==0) for (i=0; i < DIVTAB_NUMER; ++i) for (j=1; j < DIVTAB_DENOM; ++j) integer_divide_table[i][j] = i / j; #endif { uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); uint32 classify_mem; int i,max_part_read=0; for (i=0; i < f->residue_count; ++i) { Residue *r = f->residue_config + i; unsigned int actual_size = f->blocksize_1 / 2; unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size; unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size; int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; if (part_read > max_part_read) max_part_read = part_read; } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *)); #else classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *)); #endif f->temp_memory_required = classify_mem; if (imdct_mem > f->temp_memory_required) f->temp_memory_required = imdct_mem; } f->first_decode = TRUE; if (f->alloc.alloc_buffer) { assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset) return error(f, VORBIS_outofmem); } f->first_audio_page_offset = stb_vorbis_get_file_offset(f); return TRUE; } Commit Message: Fix seven bugs discovered and fixed by ForAllSecure: CVE-2019-13217: heap buffer overflow in start_decoder() CVE-2019-13218: stack buffer overflow in compute_codewords() CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest() CVE-2019-13220: out-of-range read in draw_line() CVE-2019-13221: issue with large 1D codebooks in lookup1_values() CVE-2019-13222: unchecked NULL returned by get_window() CVE-2019-13223: division by zero in predict_point() CWE ID: CWE-20 Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoSetEnableDCLayersCHROMIUM( GLboolean enable) { GLint current_framebuffer = 0; api()->glGetIntegervFn(GL_FRAMEBUFFER_BINDING, &current_framebuffer); if (current_framebuffer != 0) { InsertError(GL_INVALID_OPERATION, "framebuffer must not be bound."); return error::kNoError; } if (!surface_->SupportsDCLayers()) { InsertError(GL_INVALID_OPERATION, "surface doesn't support SetDrawRectangle."); return error::kNoError; } if (!surface_->SetEnableDCLayers(!!enable)) { InsertError(GL_INVALID_OPERATION, "SetEnableDCLayers failed on surface."); return error::kNoError; } return error::kNoError; } 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 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::RenderFrameImpl(const CreateParams& params) : frame_(NULL), is_subframe_(false), is_local_root_(false), render_view_(params.render_view->AsWeakPtr()), routing_id_(params.routing_id), is_swapped_out_(false), render_frame_proxy_(NULL), is_detaching_(false), proxy_routing_id_(MSG_ROUTING_NONE), #if defined(ENABLE_PLUGINS) plugin_power_saver_helper_(NULL), #endif cookie_jar_(this), selection_text_offset_(0), selection_range_(gfx::Range::InvalidRange()), handling_select_range_(false), notification_permission_dispatcher_(NULL), web_user_media_client_(NULL), media_permission_dispatcher_(NULL), midi_dispatcher_(NULL), #if defined(OS_ANDROID) media_player_manager_(NULL), #endif #if defined(ENABLE_BROWSER_CDMS) cdm_manager_(NULL), #endif #if defined(VIDEO_HOLE) contains_media_player_(false), #endif has_played_media_(false), devtools_agent_(nullptr), geolocation_dispatcher_(NULL), push_messaging_dispatcher_(NULL), presentation_dispatcher_(NULL), screen_orientation_dispatcher_(NULL), manifest_manager_(NULL), accessibility_mode_(AccessibilityModeOff), renderer_accessibility_(NULL), weak_factory_(this) { std::pair<RoutingIDFrameMap::iterator, bool> result = g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this)); CHECK(result.second) << "Inserting a duplicate item."; RenderThread::Get()->AddRoute(routing_id_, this); render_view_->RegisterRenderFrame(this); #if defined(OS_ANDROID) new GinJavaBridgeDispatcher(this); #endif #if defined(ENABLE_PLUGINS) plugin_power_saver_helper_ = new PluginPowerSaverHelper(this); #endif manifest_manager_ = new ManifestManager(this); } Commit Message: Connect WebUSB client interface to the devices app This provides a basic WebUSB client interface in content/renderer. Most of the interface is unimplemented, but this CL hooks up navigator.usb.getDevices() to the browser's Mojo devices app to enumerate available USB devices. BUG=492204 Review URL: https://codereview.chromium.org/1293253002 Cr-Commit-Position: refs/heads/master@{#344881} 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 DownloadController::CreateGETDownload( const content::ResourceRequestInfo::WebContentsGetter& wc_getter, bool must_download, const DownloadInfo& info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&DownloadController::StartAndroidDownload, base::Unretained(this), wc_getter, must_download, info)); } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254 Target: 1 Example 2: Code: int listMatchObjects(void *a, void *b) { return equalStringObjects(a,b); } 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: void SafeBrowsingPrivateEventRouter::OnDangerousDeepScanningResult( const GURL& url, const std::string& file_name, const std::string& download_digest_sha256) { if (client_) { base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, url.spec()); event.SetStringKey(kKeyFileName, file_name); event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256); event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); ReportRealtimeEvent(kKeyDangerousDownloadEvent, std::move(event)); } } Commit Message: Add reporting for DLP deep scanning For each triggered rule in the DLP response, we report the download as violating that rule. This also implements the UnsafeReportingEnabled enterprise policy, which controls whether or not we do any reporting. Bug: 980777 Change-Id: I48100cfb4dd5aa92ed80da1f34e64a6e393be2fa Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1772381 Commit-Queue: Daniel Rubery <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Reviewed-by: Roger Tawa <[email protected]> Cr-Commit-Position: refs/heads/master@{#691371} 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: static inline int object_common2(UNSERIALIZE_PARAMETER, long elements) { zval *retval_ptr = NULL; zval fname; if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) { /* We've got partially constructed object on our hands here. Wipe it. */ if(Z_TYPE_PP(rval) == IS_OBJECT) { zend_hash_clean(Z_OBJPROP_PP(rval)); } ZVAL_NULL(*rval); return 0; } if (Z_TYPE_PP(rval) != IS_OBJECT) { return 0; } if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY && zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) { INIT_PZVAL(&fname); ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0); BG(serialize_lock)++; call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC); BG(serialize_lock)--; } if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } if (EG(exception)) { return 0; } return finish_nested_data(UNSERIALIZE_PASSTHRU); } Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction CWE ID: CWE-119 Target: 1 Example 2: Code: XML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler) { if (parser != NULL) parser->m_entityDeclHandler = handler; } Commit Message: xmlparse.c: Deny internal entities closing the doctype CWE ID: CWE-611 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: FramebufferInfoTest() : manager_(1, 1), feature_info_(new FeatureInfo()), renderbuffer_manager_(NULL, kMaxRenderbufferSize, kMaxSamples, kDepth24Supported) { texture_manager_.reset(new TextureManager(NULL, feature_info_.get(), kMaxTextureSize, kMaxCubemapSize, kUseDefaultTextures)); } 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:
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: virtual InputMethodDescriptor current_input_method() const { return current_input_method_; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: SigAlarm(SIGNAL_ARG) { char *data; if (CurrentAlarm->sec > 0) { CurrentKey = -1; CurrentKeyData = NULL; CurrentCmdData = data = (char *)CurrentAlarm->data; #ifdef USE_MOUSE if (use_mouse) mouse_inactive(); #endif w3mFuncList[CurrentAlarm->cmd].func(); #ifdef USE_MOUSE if (use_mouse) mouse_active(); #endif CurrentCmdData = NULL; if (CurrentAlarm->status == AL_IMPLICIT_ONCE) { CurrentAlarm->sec = 0; CurrentAlarm->status = AL_UNSET; } if (Currentbuf->event) { if (Currentbuf->event->status != AL_UNSET) CurrentAlarm = Currentbuf->event; else Currentbuf->event = NULL; } if (!Currentbuf->event) CurrentAlarm = &DefaultAlarm; if (CurrentAlarm->sec > 0) { mySignal(SIGALRM, SigAlarm); alarm(CurrentAlarm->sec); } } SIGNAL_RETURN; } Commit Message: Make temporary directory safely when ~/.w3m is unwritable CWE ID: CWE-59 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: GF_Err fpar_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; FilePartitionBox *ptr = (FilePartitionBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_int(bs, ptr->itemID, ptr->version ? 32 : 16); gf_bs_write_u16(bs, ptr->packet_payload_size); gf_bs_write_u8(bs, 0); gf_bs_write_u8(bs, ptr->FEC_encoding_ID); gf_bs_write_u16(bs, ptr->FEC_instance_ID); gf_bs_write_u16(bs, ptr->max_source_block_length); gf_bs_write_u16(bs, ptr->encoding_symbol_length); gf_bs_write_u16(bs, ptr->max_number_of_encoding_symbols); if (ptr->scheme_specific_info) { gf_bs_write_data(bs, ptr->scheme_specific_info, (u32)strlen(ptr->scheme_specific_info) ); } gf_bs_write_u8(bs, 0); gf_bs_write_int(bs, ptr->nb_entries, ptr->version ? 32 : 16); for (i=0;i < ptr->nb_entries; i++) { gf_bs_write_u16(bs, ptr->entries[i].block_count); gf_bs_write_u32(bs, ptr->entries[i].block_size); } return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) 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: std::set<std::string> GetDistinctHosts(const URLPatternSet& host_patterns, bool include_rcd, bool exclude_file_scheme) { typedef base::StringPairs HostVector; HostVector hosts_best_rcd; for (const URLPattern& pattern : host_patterns) { if (exclude_file_scheme && pattern.scheme() == url::kFileScheme) continue; std::string host = pattern.host(); if (pattern.match_subdomains()) host = "*." + host; std::string rcd; size_t reg_len = net::registry_controlled_domains::PermissiveGetHostRegistryLength( host, net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES); if (reg_len && reg_len != std::string::npos) { if (include_rcd) // else leave rcd empty rcd = host.substr(host.size() - reg_len); host = host.substr(0, host.size() - reg_len); } HostVector::iterator it = hosts_best_rcd.begin(); for (; it != hosts_best_rcd.end(); ++it) { if (it->first == host) break; } if (it != hosts_best_rcd.end()) { if (include_rcd && RcdBetterThan(rcd, it->second)) it->second = rcd; } else { // Previously unseen host, append it. hosts_best_rcd.push_back(std::make_pair(host, rcd)); } } std::set<std::string> distinct_hosts; for (const auto& host_rcd : hosts_best_rcd) distinct_hosts.insert(host_rcd.first + host_rcd.second); return distinct_hosts; } Commit Message: Ensure IDN domains are in punycode format in extension host permissions Today in extension dialogs and bubbles, IDN domains in host permissions are not displayed in punycode format. There is a low security risk that granting such permission would allow extensions to interact with pages using spoofy IDN domains. Note that this does not affect the omnibox, which would represent the origin properly. To address this issue, this CL converts IDN domains in host permissions to punycode format. Bug: 745580 Change-Id: Ifc04030fae645f8a78ac8fde170660f2d514acce Reviewed-on: https://chromium-review.googlesource.com/644140 Commit-Queue: catmullings <[email protected]> Reviewed-by: Istiaque Ahmed <[email protected]> Reviewed-by: Tommy Li <[email protected]> Cr-Commit-Position: refs/heads/master@{#499090} CWE ID: CWE-20 Target: 1 Example 2: Code: inline void ImageLoader::ClearFailedLoadURL() { failed_load_url_ = AtomicString(); } Commit Message: service worker: Disable interception when OBJECT/EMBED uses ImageLoader. Per the specification, service worker should not intercept requests for OBJECT/EMBED elements. R=kinuko Bug: 771933 Change-Id: Ia6da6107dc5c68aa2c2efffde14bd2c51251fbd4 Reviewed-on: https://chromium-review.googlesource.com/927303 Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Matt Falkenhagen <[email protected]> Cr-Commit-Position: refs/heads/master@{#538027} 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 BrowserOpenedNotificationObserver::set_for_browser_command( bool for_browser_command) { for_browser_command_ = for_browser_command; } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 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 ar6000_create_ap_interface(struct ar6_softc *ar, char *ap_ifname) { struct net_device *dev; struct ar_virtual_interface *arApDev; dev = alloc_etherdev(sizeof(struct ar_virtual_interface)); if (dev == NULL) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: can't alloc etherdev\n")); return A_ERROR; } ether_setup(dev); init_netdev(dev, ap_ifname); if (register_netdev(dev)) { AR_DEBUG_PRINTF(ATH_DEBUG_ERR,("ar6000_create_ap_interface: register_netdev failed\n")); return A_ERROR; } arApDev = netdev_priv(dev); arApDev->arDev = ar; arApDev->arNetDev = dev; arApDev->arStaNetDev = ar->arNetDev; ar->arApDev = arApDev; arApNetDev = dev; /* Copy the MAC address */ memcpy(dev->dev_addr, ar->arNetDev->dev_addr, AR6000_ETH_ADDR_LEN); return 0; } 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: static int sctp_send_asconf_del_ip(struct sock *sk, struct sockaddr *addrs, int addrcnt) { struct net *net = sock_net(sk); struct sctp_sock *sp; struct sctp_endpoint *ep; struct sctp_association *asoc; struct sctp_transport *transport; struct sctp_bind_addr *bp; struct sctp_chunk *chunk; union sctp_addr *laddr; void *addr_buf; struct sctp_af *af; struct sctp_sockaddr_entry *saddr; int i; int retval = 0; int stored = 0; chunk = NULL; if (!net->sctp.addip_enable) return retval; sp = sctp_sk(sk); ep = sp->ep; SCTP_DEBUG_PRINTK("%s: (sk: %p, addrs: %p, addrcnt: %d)\n", __func__, sk, addrs, addrcnt); list_for_each_entry(asoc, &ep->asocs, asocs) { if (!asoc->peer.asconf_capable) continue; if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP) continue; if (!sctp_state(asoc, ESTABLISHED)) continue; /* Check if any address in the packed array of addresses is * not present in the bind address list of the association. * If so, do not send the asconf chunk to its peer, but * continue with other associations. */ addr_buf = addrs; for (i = 0; i < addrcnt; i++) { laddr = addr_buf; af = sctp_get_af_specific(laddr->v4.sin_family); if (!af) { retval = -EINVAL; goto out; } if (!sctp_assoc_lookup_laddr(asoc, laddr)) break; addr_buf += af->sockaddr_len; } if (i < addrcnt) continue; /* Find one address in the association's bind address list * that is not in the packed array of addresses. This is to * make sure that we do not delete all the addresses in the * association. */ bp = &asoc->base.bind_addr; laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs, addrcnt, sp); if ((laddr == NULL) && (addrcnt == 1)) { if (asoc->asconf_addr_del_pending) continue; asoc->asconf_addr_del_pending = kzalloc(sizeof(union sctp_addr), GFP_ATOMIC); if (asoc->asconf_addr_del_pending == NULL) { retval = -ENOMEM; goto out; } asoc->asconf_addr_del_pending->sa.sa_family = addrs->sa_family; asoc->asconf_addr_del_pending->v4.sin_port = htons(bp->port); if (addrs->sa_family == AF_INET) { struct sockaddr_in *sin; sin = (struct sockaddr_in *)addrs; asoc->asconf_addr_del_pending->v4.sin_addr.s_addr = sin->sin_addr.s_addr; } else if (addrs->sa_family == AF_INET6) { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *)addrs; asoc->asconf_addr_del_pending->v6.sin6_addr = sin6->sin6_addr; } SCTP_DEBUG_PRINTK_IPADDR("send_asconf_del_ip: keep the last address asoc: %p ", " at %p\n", asoc, asoc->asconf_addr_del_pending, asoc->asconf_addr_del_pending); asoc->src_out_of_asoc_ok = 1; stored = 1; goto skip_mkasconf; } /* We do not need RCU protection throughout this loop * because this is done under a socket lock from the * setsockopt call. */ chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt, SCTP_PARAM_DEL_IP); if (!chunk) { retval = -ENOMEM; goto out; } skip_mkasconf: /* Reset use_as_src flag for the addresses in the bind address * list that are to be deleted. */ addr_buf = addrs; for (i = 0; i < addrcnt; i++) { laddr = addr_buf; af = sctp_get_af_specific(laddr->v4.sin_family); list_for_each_entry(saddr, &bp->address_list, list) { if (sctp_cmp_addr_exact(&saddr->a, laddr)) saddr->state = SCTP_ADDR_DEL; } addr_buf += af->sockaddr_len; } /* Update the route and saddr entries for all the transports * as some of the addresses in the bind address list are * about to be deleted and cannot be used as source addresses. */ list_for_each_entry(transport, &asoc->peer.transport_addr_list, transports) { dst_release(transport->dst); sctp_transport_route(transport, NULL, sctp_sk(asoc->base.sk)); } if (stored) /* We don't need to transmit ASCONF */ continue; retval = sctp_send_asconf(asoc, chunk); } out: return retval; } Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS Building sctp may fail with: In function ‘copy_from_user’, inlined from ‘sctp_getsockopt_assoc_stats’ at net/sctp/socket.c:5656:20: arch/x86/include/asm/uaccess_32.h:211:26: error: call to ‘copy_from_user_overflow’ declared with attribute error: copy_from_user() buffer size is not provably correct if built with W=1 due to a missing parameter size validation before the call to copy_from_user. Signed-off-by: Guenter Roeck <[email protected]> Acked-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[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 int tun_set_coalesce(struct net_device *dev, struct ethtool_coalesce *ec) { struct tun_struct *tun = netdev_priv(dev); if (ec->rx_max_coalesced_frames > NAPI_POLL_WEIGHT) tun->rx_batched = NAPI_POLL_WEIGHT; else tun->rx_batched = ec->rx_max_coalesced_frames; return 0; } Commit Message: tun: call dev_get_valid_name() before register_netdevice() register_netdevice() could fail early when we have an invalid dev name, in which case ->ndo_uninit() is not called. For tun device, this is a problem because a timer etc. are already initialized and it expects ->ndo_uninit() to clean them up. We could move these initializations into a ->ndo_init() so that register_netdevice() knows better, however this is still complicated due to the logic in tun_detach(). Therefore, I choose to just call dev_get_valid_name() before register_netdevice(), which is quicker and much easier to audit. And for this specific case, it is already enough. Fixes: 96442e42429e ("tuntap: choose the txq based on rxq") Reported-by: Dmitry Alexeev <[email protected]> Cc: Jason Wang <[email protected]> Cc: "Michael S. Tsirkin" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[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: cJSON *cJSON_CreateIntArray( int64_t *numbers, int count ) { int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for ( i = 0; a && i < count; ++i ) { n = cJSON_CreateInt( numbers[i] ); if ( ! i ) a->child = n; else suffix_object( p, n ); p = n; } return a; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static inline void cirrus_bitblt_fgcol(CirrusVGAState *s) { unsigned int color; switch (s->cirrus_blt_pixelwidth) { case 1: s->cirrus_blt_fgcol = s->cirrus_shadow_gr1; break; case 2: color = s->cirrus_shadow_gr1 | (s->vga.gr[0x11] << 8); s->cirrus_blt_fgcol = le16_to_cpu(color); break; case 3: s->cirrus_blt_fgcol = s->cirrus_shadow_gr1 | (s->vga.gr[0x11] << 8) | (s->vga.gr[0x13] << 16); break; default: case 4: color = s->cirrus_shadow_gr1 | (s->vga.gr[0x11] << 8) | (s->vga.gr[0x13] << 16) | (s->vga.gr[0x15] << 24); s->cirrus_blt_fgcol = le32_to_cpu(color); break; } } 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 make_raw_rw_request(void) { int aligned_sector_t; int max_sector; int max_size; int tracksize; int ssize; if (WARN(max_buffer_sectors == 0, "VFS: Block I/O scheduled on unopened device\n")) return 0; set_fdc((long)current_req->rq_disk->private_data); raw_cmd = &default_raw_cmd; raw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK; raw_cmd->cmd_count = NR_RW; if (rq_data_dir(current_req) == READ) { raw_cmd->flags |= FD_RAW_READ; COMMAND = FM_MODE(_floppy, FD_READ); } else if (rq_data_dir(current_req) == WRITE) { raw_cmd->flags |= FD_RAW_WRITE; COMMAND = FM_MODE(_floppy, FD_WRITE); } else { DPRINT("%s: unknown command\n", __func__); return 0; } max_sector = _floppy->sect * _floppy->head; TRACK = (int)blk_rq_pos(current_req) / max_sector; fsector_t = (int)blk_rq_pos(current_req) % max_sector; if (_floppy->track && TRACK >= _floppy->track) { if (blk_rq_cur_sectors(current_req) & 1) { current_count_sectors = 1; return 1; } else return 0; } HEAD = fsector_t / _floppy->sect; if (((_floppy->stretch & (FD_SWAPSIDES | FD_SECTBASEMASK)) || test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) && fsector_t < _floppy->sect) max_sector = _floppy->sect; /* 2M disks have phantom sectors on the first track */ if ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)) { max_sector = 2 * _floppy->sect / 3; if (fsector_t >= max_sector) { current_count_sectors = min_t(int, _floppy->sect - fsector_t, blk_rq_sectors(current_req)); return 1; } SIZECODE = 2; } else SIZECODE = FD_SIZECODE(_floppy); raw_cmd->rate = _floppy->rate & 0x43; if ((_floppy->rate & FD_2M) && (TRACK || HEAD) && raw_cmd->rate == 2) raw_cmd->rate = 1; if (SIZECODE) SIZECODE2 = 0xff; else SIZECODE2 = 0x80; raw_cmd->track = TRACK << STRETCH(_floppy); DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, HEAD); GAP = _floppy->gap; ssize = DIV_ROUND_UP(1 << SIZECODE, 4); SECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE; SECTOR = ((fsector_t % _floppy->sect) << 2 >> SIZECODE) + FD_SECTBASE(_floppy); /* tracksize describes the size which can be filled up with sectors * of size ssize. */ tracksize = _floppy->sect - _floppy->sect % ssize; if (tracksize < _floppy->sect) { SECT_PER_TRACK++; if (tracksize <= fsector_t % _floppy->sect) SECTOR--; /* if we are beyond tracksize, fill up using smaller sectors */ while (tracksize <= fsector_t % _floppy->sect) { while (tracksize + ssize > _floppy->sect) { SIZECODE--; ssize >>= 1; } SECTOR++; SECT_PER_TRACK++; tracksize += ssize; } max_sector = HEAD * _floppy->sect + tracksize; } else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) { max_sector = _floppy->sect; } else if (!HEAD && CT(COMMAND) == FD_WRITE) { /* for virtual DMA bug workaround */ max_sector = _floppy->sect; } in_sector_offset = (fsector_t % _floppy->sect) % ssize; aligned_sector_t = fsector_t - in_sector_offset; max_size = blk_rq_sectors(current_req); if ((raw_cmd->track == buffer_track) && (current_drive == buffer_drive) && (fsector_t >= buffer_min) && (fsector_t < buffer_max)) { /* data already in track buffer */ if (CT(COMMAND) == FD_READ) { copy_buffer(1, max_sector, buffer_max); return 1; } } else if (in_sector_offset || blk_rq_sectors(current_req) < ssize) { if (CT(COMMAND) == FD_WRITE) { unsigned int sectors; sectors = fsector_t + blk_rq_sectors(current_req); if (sectors > ssize && sectors < ssize + ssize) max_size = ssize + ssize; else max_size = ssize; } raw_cmd->flags &= ~FD_RAW_WRITE; raw_cmd->flags |= FD_RAW_READ; COMMAND = FM_MODE(_floppy, FD_READ); } else if ((unsigned long)current_req->buffer < MAX_DMA_ADDRESS) { unsigned long dma_limit; int direct, indirect; indirect = transfer_size(ssize, max_sector, max_buffer_sectors * 2) - fsector_t; /* * Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide * on a 64 bit machine! */ max_size = buffer_chain_size(); dma_limit = (MAX_DMA_ADDRESS - ((unsigned long)current_req->buffer)) >> 9; if ((unsigned long)max_size > dma_limit) max_size = dma_limit; /* 64 kb boundaries */ if (CROSS_64KB(current_req->buffer, max_size << 9)) max_size = (K_64 - ((unsigned long)current_req->buffer) % K_64) >> 9; direct = transfer_size(ssize, max_sector, max_size) - fsector_t; /* * We try to read tracks, but if we get too many errors, we * go back to reading just one sector at a time. * * This means we should be able to read a sector even if there * are other bad sectors on this track. */ if (!direct || (indirect * 2 > direct * 3 && *errors < DP->max_errors.read_track && ((!probing || (DP->read_track & (1 << DRS->probed_format)))))) { max_size = blk_rq_sectors(current_req); } else { raw_cmd->kernel_data = current_req->buffer; raw_cmd->length = current_count_sectors << 9; if (raw_cmd->length == 0) { DPRINT("%s: zero dma transfer attempted\n", __func__); DPRINT("indirect=%d direct=%d fsector_t=%d\n", indirect, direct, fsector_t); return 0; } virtualdmabug_workaround(); return 2; } } if (CT(COMMAND) == FD_READ) max_size = max_sector; /* unbounded */ /* claim buffer track if needed */ if (buffer_track != raw_cmd->track || /* bad track */ buffer_drive != current_drive || /* bad drive */ fsector_t > buffer_max || fsector_t < buffer_min || ((CT(COMMAND) == FD_READ || (!in_sector_offset && blk_rq_sectors(current_req) >= ssize)) && max_sector > 2 * max_buffer_sectors + buffer_min && max_size + fsector_t > 2 * max_buffer_sectors + buffer_min)) { /* not enough space */ buffer_track = -1; buffer_drive = current_drive; buffer_max = buffer_min = aligned_sector_t; } raw_cmd->kernel_data = floppy_track_buffer + ((aligned_sector_t - buffer_min) << 9); if (CT(COMMAND) == FD_WRITE) { /* copy write buffer to track buffer. * if we get here, we know that the write * is either aligned or the data already in the buffer * (buffer will be overwritten) */ if (in_sector_offset && buffer_track == -1) DPRINT("internal error offset !=0 on write\n"); buffer_track = raw_cmd->track; buffer_drive = current_drive; copy_buffer(ssize, max_sector, 2 * max_buffer_sectors + buffer_min); } else transfer_size(ssize, max_sector, 2 * max_buffer_sectors + buffer_min - aligned_sector_t); /* round up current_count_sectors to get dma xfer size */ raw_cmd->length = in_sector_offset + current_count_sectors; raw_cmd->length = ((raw_cmd->length - 1) | (ssize - 1)) + 1; raw_cmd->length <<= 9; if ((raw_cmd->length < current_count_sectors << 9) || (raw_cmd->kernel_data != current_req->buffer && CT(COMMAND) == FD_WRITE && (aligned_sector_t + (raw_cmd->length >> 9) > buffer_max || aligned_sector_t < buffer_min)) || raw_cmd->length % (128 << SIZECODE) || raw_cmd->length <= 0 || current_count_sectors <= 0) { DPRINT("fractionary current count b=%lx s=%lx\n", raw_cmd->length, current_count_sectors); if (raw_cmd->kernel_data != current_req->buffer) pr_info("addr=%d, length=%ld\n", (int)((raw_cmd->kernel_data - floppy_track_buffer) >> 9), current_count_sectors); pr_info("st=%d ast=%d mse=%d msi=%d\n", fsector_t, aligned_sector_t, max_sector, max_size); pr_info("ssize=%x SIZECODE=%d\n", ssize, SIZECODE); pr_info("command=%x SECTOR=%d HEAD=%d, TRACK=%d\n", COMMAND, SECTOR, HEAD, TRACK); pr_info("buffer drive=%d\n", buffer_drive); pr_info("buffer track=%d\n", buffer_track); pr_info("buffer_min=%d\n", buffer_min); pr_info("buffer_max=%d\n", buffer_max); return 0; } if (raw_cmd->kernel_data != current_req->buffer) { if (raw_cmd->kernel_data < floppy_track_buffer || current_count_sectors < 0 || raw_cmd->length < 0 || raw_cmd->kernel_data + raw_cmd->length > floppy_track_buffer + (max_buffer_sectors << 10)) { DPRINT("buffer overrun in schedule dma\n"); pr_info("fsector_t=%d buffer_min=%d current_count=%ld\n", fsector_t, buffer_min, raw_cmd->length >> 9); pr_info("current_count_sectors=%ld\n", current_count_sectors); if (CT(COMMAND) == FD_READ) pr_info("read\n"); if (CT(COMMAND) == FD_WRITE) pr_info("write\n"); return 0; } } else if (raw_cmd->length > blk_rq_bytes(current_req) || current_count_sectors > blk_rq_sectors(current_req)) { DPRINT("buffer overrun in direct transfer\n"); return 0; } else if (raw_cmd->length < current_count_sectors << 9) { DPRINT("more sectors than bytes\n"); pr_info("bytes=%ld\n", raw_cmd->length >> 9); pr_info("sectors=%ld\n", current_count_sectors); } if (raw_cmd->length == 0) { DPRINT("zero dma transfer attempted from make_raw_request\n"); return 0; } virtualdmabug_workaround(); return 2; } Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output Do not leak kernel-only floppy_raw_cmd structure members to userspace. This includes the linked-list pointer and the pointer to the allocated DMA space. Signed-off-by: Matthew Daley <[email protected]> Signed-off-by: Linus Torvalds <[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: static int udf_read_inode(struct inode *inode, bool hidden_inode) { struct buffer_head *bh = NULL; struct fileEntry *fe; struct extendedFileEntry *efe; uint16_t ident; struct udf_inode_info *iinfo = UDF_I(inode); struct udf_sb_info *sbi = UDF_SB(inode->i_sb); struct kernel_lb_addr *iloc = &iinfo->i_location; unsigned int link_count; unsigned int indirections = 0; int bs = inode->i_sb->s_blocksize; int ret = -EIO; reread: if (iloc->logicalBlockNum >= sbi->s_partmaps[iloc->partitionReferenceNum].s_partition_len) { udf_debug("block=%d, partition=%d out of range\n", iloc->logicalBlockNum, iloc->partitionReferenceNum); return -EIO; } /* * Set defaults, but the inode is still incomplete! * Note: get_new_inode() sets the following on a new inode: * i_sb = sb * i_no = ino * i_flags = sb->s_flags * i_state = 0 * clean_inode(): zero fills and sets * i_count = 1 * i_nlink = 1 * i_op = NULL; */ bh = udf_read_ptagged(inode->i_sb, iloc, 0, &ident); if (!bh) { udf_err(inode->i_sb, "(ino %ld) failed !bh\n", inode->i_ino); return -EIO; } if (ident != TAG_IDENT_FE && ident != TAG_IDENT_EFE && ident != TAG_IDENT_USE) { udf_err(inode->i_sb, "(ino %ld) failed ident=%d\n", inode->i_ino, ident); goto out; } fe = (struct fileEntry *)bh->b_data; efe = (struct extendedFileEntry *)bh->b_data; if (fe->icbTag.strategyType == cpu_to_le16(4096)) { struct buffer_head *ibh; ibh = udf_read_ptagged(inode->i_sb, iloc, 1, &ident); if (ident == TAG_IDENT_IE && ibh) { struct kernel_lb_addr loc; struct indirectEntry *ie; ie = (struct indirectEntry *)ibh->b_data; loc = lelb_to_cpu(ie->indirectICB.extLocation); if (ie->indirectICB.extLength) { brelse(ibh); memcpy(&iinfo->i_location, &loc, sizeof(struct kernel_lb_addr)); if (++indirections > UDF_MAX_ICB_NESTING) { udf_err(inode->i_sb, "too many ICBs in ICB hierarchy" " (max %d supported)\n", UDF_MAX_ICB_NESTING); goto out; } brelse(bh); goto reread; } } brelse(ibh); } else if (fe->icbTag.strategyType != cpu_to_le16(4)) { udf_err(inode->i_sb, "unsupported strategy type: %d\n", le16_to_cpu(fe->icbTag.strategyType)); goto out; } if (fe->icbTag.strategyType == cpu_to_le16(4)) iinfo->i_strat4096 = 0; else /* if (fe->icbTag.strategyType == cpu_to_le16(4096)) */ iinfo->i_strat4096 = 1; iinfo->i_alloc_type = le16_to_cpu(fe->icbTag.flags) & ICBTAG_FLAG_AD_MASK; iinfo->i_unique = 0; iinfo->i_lenEAttr = 0; iinfo->i_lenExtents = 0; iinfo->i_lenAlloc = 0; iinfo->i_next_alloc_block = 0; iinfo->i_next_alloc_goal = 0; if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_EFE)) { iinfo->i_efe = 1; iinfo->i_use = 0; ret = udf_alloc_i_data(inode, bs - sizeof(struct extendedFileEntry)); if (ret) goto out; memcpy(iinfo->i_ext.i_data, bh->b_data + sizeof(struct extendedFileEntry), bs - sizeof(struct extendedFileEntry)); } else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_FE)) { iinfo->i_efe = 0; iinfo->i_use = 0; ret = udf_alloc_i_data(inode, bs - sizeof(struct fileEntry)); if (ret) goto out; memcpy(iinfo->i_ext.i_data, bh->b_data + sizeof(struct fileEntry), bs - sizeof(struct fileEntry)); } else if (fe->descTag.tagIdent == cpu_to_le16(TAG_IDENT_USE)) { iinfo->i_efe = 0; iinfo->i_use = 1; iinfo->i_lenAlloc = le32_to_cpu( ((struct unallocSpaceEntry *)bh->b_data)-> lengthAllocDescs); ret = udf_alloc_i_data(inode, bs - sizeof(struct unallocSpaceEntry)); if (ret) goto out; memcpy(iinfo->i_ext.i_data, bh->b_data + sizeof(struct unallocSpaceEntry), bs - sizeof(struct unallocSpaceEntry)); return 0; } ret = -EIO; read_lock(&sbi->s_cred_lock); i_uid_write(inode, le32_to_cpu(fe->uid)); if (!uid_valid(inode->i_uid) || UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_IGNORE) || UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_UID_SET)) inode->i_uid = UDF_SB(inode->i_sb)->s_uid; i_gid_write(inode, le32_to_cpu(fe->gid)); if (!gid_valid(inode->i_gid) || UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_IGNORE) || UDF_QUERY_FLAG(inode->i_sb, UDF_FLAG_GID_SET)) inode->i_gid = UDF_SB(inode->i_sb)->s_gid; if (fe->icbTag.fileType != ICBTAG_FILE_TYPE_DIRECTORY && sbi->s_fmode != UDF_INVALID_MODE) inode->i_mode = sbi->s_fmode; else if (fe->icbTag.fileType == ICBTAG_FILE_TYPE_DIRECTORY && sbi->s_dmode != UDF_INVALID_MODE) inode->i_mode = sbi->s_dmode; else inode->i_mode = udf_convert_permissions(fe); inode->i_mode &= ~sbi->s_umask; read_unlock(&sbi->s_cred_lock); link_count = le16_to_cpu(fe->fileLinkCount); if (!link_count) { if (!hidden_inode) { ret = -ESTALE; goto out; } link_count = 1; } set_nlink(inode, link_count); inode->i_size = le64_to_cpu(fe->informationLength); iinfo->i_lenExtents = inode->i_size; if (iinfo->i_efe == 0) { inode->i_blocks = le64_to_cpu(fe->logicalBlocksRecorded) << (inode->i_sb->s_blocksize_bits - 9); if (!udf_disk_stamp_to_time(&inode->i_atime, fe->accessTime)) inode->i_atime = sbi->s_record_time; if (!udf_disk_stamp_to_time(&inode->i_mtime, fe->modificationTime)) inode->i_mtime = sbi->s_record_time; if (!udf_disk_stamp_to_time(&inode->i_ctime, fe->attrTime)) inode->i_ctime = sbi->s_record_time; iinfo->i_unique = le64_to_cpu(fe->uniqueID); iinfo->i_lenEAttr = le32_to_cpu(fe->lengthExtendedAttr); iinfo->i_lenAlloc = le32_to_cpu(fe->lengthAllocDescs); iinfo->i_checkpoint = le32_to_cpu(fe->checkpoint); } else { inode->i_blocks = le64_to_cpu(efe->logicalBlocksRecorded) << (inode->i_sb->s_blocksize_bits - 9); if (!udf_disk_stamp_to_time(&inode->i_atime, efe->accessTime)) inode->i_atime = sbi->s_record_time; if (!udf_disk_stamp_to_time(&inode->i_mtime, efe->modificationTime)) inode->i_mtime = sbi->s_record_time; if (!udf_disk_stamp_to_time(&iinfo->i_crtime, efe->createTime)) iinfo->i_crtime = sbi->s_record_time; if (!udf_disk_stamp_to_time(&inode->i_ctime, efe->attrTime)) inode->i_ctime = sbi->s_record_time; iinfo->i_unique = le64_to_cpu(efe->uniqueID); iinfo->i_lenEAttr = le32_to_cpu(efe->lengthExtendedAttr); iinfo->i_lenAlloc = le32_to_cpu(efe->lengthAllocDescs); iinfo->i_checkpoint = le32_to_cpu(efe->checkpoint); } inode->i_generation = iinfo->i_unique; /* Sanity checks for files in ICB so that we don't get confused later */ if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { /* * For file in ICB data is stored in allocation descriptor * so sizes should match */ if (iinfo->i_lenAlloc != inode->i_size) goto out; /* File in ICB has to fit in there... */ if (inode->i_size > bs - udf_file_entry_alloc_offset(inode)) goto out; } switch (fe->icbTag.fileType) { case ICBTAG_FILE_TYPE_DIRECTORY: inode->i_op = &udf_dir_inode_operations; inode->i_fop = &udf_dir_operations; inode->i_mode |= S_IFDIR; inc_nlink(inode); break; case ICBTAG_FILE_TYPE_REALTIME: case ICBTAG_FILE_TYPE_REGULAR: case ICBTAG_FILE_TYPE_UNDEF: case ICBTAG_FILE_TYPE_VAT20: if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) inode->i_data.a_ops = &udf_adinicb_aops; else inode->i_data.a_ops = &udf_aops; inode->i_op = &udf_file_inode_operations; inode->i_fop = &udf_file_operations; inode->i_mode |= S_IFREG; break; case ICBTAG_FILE_TYPE_BLOCK: inode->i_mode |= S_IFBLK; break; case ICBTAG_FILE_TYPE_CHAR: inode->i_mode |= S_IFCHR; break; case ICBTAG_FILE_TYPE_FIFO: init_special_inode(inode, inode->i_mode | S_IFIFO, 0); break; case ICBTAG_FILE_TYPE_SOCKET: init_special_inode(inode, inode->i_mode | S_IFSOCK, 0); break; case ICBTAG_FILE_TYPE_SYMLINK: inode->i_data.a_ops = &udf_symlink_aops; inode->i_op = &udf_symlink_inode_operations; inode->i_mode = S_IFLNK | S_IRWXUGO; break; case ICBTAG_FILE_TYPE_MAIN: udf_debug("METADATA FILE-----\n"); break; case ICBTAG_FILE_TYPE_MIRROR: udf_debug("METADATA MIRROR FILE-----\n"); break; case ICBTAG_FILE_TYPE_BITMAP: udf_debug("METADATA BITMAP FILE-----\n"); break; default: udf_err(inode->i_sb, "(ino %ld) failed unknown file type=%d\n", inode->i_ino, fe->icbTag.fileType); goto out; } if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) { struct deviceSpec *dsea = (struct deviceSpec *)udf_get_extendedattr(inode, 12, 1); if (dsea) { init_special_inode(inode, inode->i_mode, MKDEV(le32_to_cpu(dsea->majorDeviceIdent), le32_to_cpu(dsea->minorDeviceIdent))); /* Developer ID ??? */ } else goto out; } ret = 0; out: brelse(bh); return ret; } Commit Message: udf: Check length of extended attributes and allocation descriptors Check length of extended attributes and allocation descriptors when loading inodes from disk. Otherwise corrupted filesystems could confuse the code and make the kernel oops. Reported-by: Carl Henrik Lunde <[email protected]> CC: [email protected] Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: media::MediaPermission* RenderFrameImpl::GetMediaPermission() { if (!media_permission_dispatcher_) media_permission_dispatcher_.reset(new MediaPermissionDispatcher(this)); return media_permission_dispatcher_.get(); } 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: v8::Isolate* isolate() const { return m_scriptState->isolate(); } Commit Message: Replace further questionable HashMap::add usages in bindings BUG=390928 [email protected] Review URL: https://codereview.chromium.org/411273002 git-svn-id: svn://svn.chromium.org/blink/trunk@178823 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 proxy_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC) { zval **login, **password; if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_login", sizeof("_proxy_login"), (void **)&login) == SUCCESS) { unsigned char* buf; int len; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login)); smart_str_appendc(&auth, ':'); if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_password", sizeof("_proxy_password"), (void **)&password) == SUCCESS) { smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password)); } smart_str_0(&auth); smart_str_appendl(soap_headers, (char*)buf, len); smart_str_append_const(soap_headers, "\r\n"); efree(buf); smart_str_free(&auth); return 1; } return 0; } Commit Message: CWE ID: Target: 1 Example 2: Code: void NavigationRequest::OnResponseStarted( const scoped_refptr<network::ResourceResponse>& response, network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints, std::unique_ptr<NavigationData> navigation_data, const GlobalRequestID& request_id, bool is_download, bool is_stream, base::Optional<SubresourceLoaderParams> subresource_loader_params) { DCHECK(state_ == STARTED); DCHECK(response); TRACE_EVENT_ASYNC_STEP_INTO0("navigation", "NavigationRequest", this, "OnResponseStarted"); state_ = RESPONSE_STARTED; response_should_be_rendered_ = !is_download && (!response->head.headers.get() || (response->head.headers->response_code() != 204 && response->head.headers->response_code() != 205)); if (!response_should_be_rendered_) { navigation_handle_->set_net_error_code(net::ERR_ABORTED); net_error_ = net::ERR_ABORTED; } request_params_.service_worker_provider_id = navigation_handle_->service_worker_handle() ? navigation_handle_->service_worker_handle() ->service_worker_provider_host_id() : kInvalidServiceWorkerProviderId; request_params_.appcache_host_id = navigation_handle_->appcache_handle() ? navigation_handle_->appcache_handle()->appcache_host_id() : kAppCacheNoHostId; request_params_.was_activated = false; if (navigation_handle_->IsRendererInitiated() && frame_tree_node_->has_received_user_gesture() && ShouldPropagateUserActivation( frame_tree_node_->current_origin(), url::Origin::Create(navigation_handle_->GetURL()))) { request_params_.was_activated = true; } else if (((navigation_handle_->HasUserGesture() && navigation_handle_->IsRendererInitiated()) || navigation_handle_->WasStartedFromContextMenu()) && ShouldPropagateUserActivation( url::Origin::Create(navigation_handle_->GetReferrer().url), url::Origin::Create(navigation_handle_->GetURL()))) { request_params_.was_activated = true; } common_params_.previews_state = static_cast<PreviewsState>(response->head.previews_state); RenderFrameHostImpl* render_frame_host = nullptr; if (response_should_be_rendered_) { render_frame_host = frame_tree_node_->render_manager()->GetFrameHostForNavigation(*this); NavigatorImpl::CheckWebUIRendererDoesNotDisplayNormalURL( render_frame_host, common_params_.url); } DCHECK(render_frame_host || !response_should_be_rendered_); if (!browser_initiated_ && render_frame_host && render_frame_host != frame_tree_node_->current_frame_host()) { common_params_.source_location.reset(); if (!frame_tree_node_->navigator()->GetDelegate()->ShouldTransferNavigation( frame_tree_node_->IsMainFrame())) { navigation_handle_->set_net_error_code(net::ERR_ABORTED); frame_tree_node_->ResetNavigationRequest(false, true); return; } } if (navigation_data) navigation_handle_->set_navigation_data(std::move(navigation_data)); response_ = response; url_loader_client_endpoints_ = std::move(url_loader_client_endpoints); ssl_info_ = response->head.ssl_info.has_value() ? *response->head.ssl_info : net::SSLInfo(); is_download_ = is_download; subresource_loader_params_ = std::move(subresource_loader_params); if (render_frame_host && SiteInstanceImpl::ShouldAssignSiteForURL(common_params_.url)) { render_frame_host->GetProcess()->SetIsUsed(); SiteInstanceImpl* instance = render_frame_host->GetSiteInstance(); if (!instance->HasSite() && SiteInstanceImpl::DoesSiteRequireDedicatedProcess( instance->GetBrowserContext(), common_params_.url)) { instance->SetSite(common_params_.url); } } RenderFrameDevToolsAgentHost::OnNavigationResponseReceived(*this, *response); if (is_download && (response->head.headers.get() && (response->head.headers->response_code() / 100 != 2))) { navigation_handle_->set_net_error_code(net::ERR_INVALID_RESPONSE); frame_tree_node_->ResetNavigationRequest(false, true); return; } navigation_handle_->WillProcessResponse( render_frame_host, response->head.headers.get(), response->head.connection_info, response->head.socket_address, ssl_info_, request_id, common_params_.should_replace_current_entry, is_download, is_stream, base::Bind(&NavigationRequest::OnWillProcessResponseChecksComplete, base::Unretained(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 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 libxsmm_sparse_csc_reader( libxsmm_generated_code* io_generated_code, const char* i_csc_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csc_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_column_idx_id = NULL; unsigned int l_i = 0; l_csc_file_handle = fopen( i_csc_file_in, "r" ); if ( l_csc_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_INPUT ); return; } while (fgets(l_line, l_line_length, l_csc_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose( l_csc_file_handle ); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC data structure matching mtx file */ *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_column_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_column_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_column_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_column_idx, 0, sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_column_idx_id, 0, sizeof(unsigned int) * (*o_column_count)); /* init column idx */ for (l_i = 0; l_i <= *o_column_count; ++l_i) { (*o_column_idx)[l_i] = *o_element_count; } /* init */ (*o_column_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_DESC ); fclose( l_csc_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_ELEMS ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_row_idx)[l_i] = l_row; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_column_idx_id[l_column] = 1; (*o_column_idx)[l_column+1] = l_i; } } } /* close mtx file */ fclose( l_csc_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_LEN ); return; } if ( l_column_idx_id != NULL ) { /* let's handle empty columns */ for ( l_i = 0; l_i < (*o_column_count); l_i++) { if ( l_column_idx_id[l_i] == 0 ) { (*o_column_idx)[l_i+1] = (*o_column_idx)[l_i]; } } /* free helper data structure */ free( l_column_idx_id ); } } Commit Message: Issue #287: made CSR/CSC readers more robust against invalid input (case #1). 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 ClientControlledShellSurface::OnBoundsChangeEvent( ash::WindowStateType current_state, ash::WindowStateType requested_state, int64_t display_id, const gfx::Rect& window_bounds, int bounds_change) { if (!geometry().IsEmpty() && !window_bounds.IsEmpty() && (!widget_->IsMinimized() || requested_state != ash::WindowStateType::kMinimized) && bounds_changed_callback_) { ash::NonClientFrameViewAsh* frame_view = GetFrameView(); const bool becoming_snapped = requested_state == ash::WindowStateType::kLeftSnapped || requested_state == ash::WindowStateType::kRightSnapped; const bool is_tablet_mode = WMHelper::GetInstance()->IsTabletModeWindowManagerEnabled(); gfx::Rect client_bounds = becoming_snapped && is_tablet_mode ? window_bounds : frame_view->GetClientBoundsForWindowBounds(window_bounds); gfx::Size current_size = frame_view->GetBoundsForClientView().size(); bool is_resize = client_bounds.size() != current_size && !widget_->IsMaximized() && !widget_->IsFullscreen(); bounds_changed_callback_.Run(current_state, requested_state, display_id, client_bounds, is_resize, bounds_change); auto* window_state = GetWindowState(); if (server_reparent_window_ && window_state->GetDisplay().id() != display_id) { ScopedSetBoundsLocally scoped_set_bounds(this); int container_id = window_state->window()->parent()->id(); aura::Window* new_parent = ash::Shell::GetRootWindowControllerWithDisplayId(display_id) ->GetContainer(container_id); new_parent->AddChild(window_state->window()); } } } Commit Message: Ignore updatePipBounds before initial bounds is set When PIP enter/exit transition happens, window state change and initial bounds change are committed in the same commit. However, as state change is applied first in OnPreWidgetCommit and the bounds is update later, if updatePipBounds is called between the gap, it ends up returning a wrong bounds based on the previous bounds. Currently, there are two callstacks that end up triggering updatePipBounds between the gap: (i) The state change causes OnWindowAddedToLayout and updatePipBounds is called in OnWMEvent, (ii) updatePipBounds is called in UpdatePipState to prevent it from being placed under some system ui. As it doesn't make sense to call updatePipBounds before the first bounds is not set, this CL adds a boolean to defer updatePipBounds. position. Bug: b130782006 Test: Got VLC into PIP and confirmed it was placed at the correct Change-Id: I5b9f3644bfb2533fd3f905bc09d49708a5d08a90 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1578719 Commit-Queue: Kazuki Takise <[email protected]> Auto-Submit: Kazuki Takise <[email protected]> Reviewed-by: Mitsuru Oshima <[email protected]> Cr-Commit-Position: refs/heads/master@{#668724} CWE ID: CWE-787 Target: 1 Example 2: Code: GF_Err elng_Read(GF_Box *s, GF_BitStream *bs) { GF_ExtendedLanguageBox *ptr = (GF_ExtendedLanguageBox *)s; if (ptr->size) { ptr->extended_language = (char*)gf_malloc((u32) ptr->size); if (ptr->extended_language == NULL) return GF_OUT_OF_MEM; gf_bs_read_data(bs, ptr->extended_language, (u32) ptr->size); /*safety check in case the string is not null-terminated*/ if (ptr->extended_language[ptr->size-1]) { char *str = (char*)gf_malloc((u32) ptr->size + 1); memcpy(str, ptr->extended_language, (u32) ptr->size); str[ptr->size] = 0; gf_free(ptr->extended_language); ptr->extended_language = str; } } 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 ProcessControlLaunched() { base::ScopedAllowBlockingForTesting allow_blocking; base::ProcessId service_pid; EXPECT_TRUE(GetServiceProcessData(NULL, &service_pid)); EXPECT_NE(static_cast<base::ProcessId>(0), service_pid); #if defined(OS_WIN) service_process_ = base::Process::OpenWithAccess(service_pid, SYNCHRONIZE | PROCESS_QUERY_INFORMATION); #else service_process_ = base::Process::Open(service_pid); #endif EXPECT_TRUE(service_process_.IsValid()); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); } Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated(). Bug: 844016 Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0 Reviewed-on: https://chromium-review.googlesource.com/1126576 Commit-Queue: Wez <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94 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 ExtensionDevToolsClientHost::InfoBarDismissed() { detach_reason_ = api::debugger::DETACH_REASON_CANCELED_BY_USER; SendDetachedEvent(); Close(); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20 Target: 1 Example 2: Code: status_t Camera3Device::registerInFlight(uint32_t frameNumber, int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput, const AeTriggerCancelOverride_t &aeTriggerCancelOverride) { ATRACE_CALL(); Mutex::Autolock l(mInFlightLock); ssize_t res; res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput, aeTriggerCancelOverride)); if (res < 0) return res; return OK; } Commit Message: Camera3Device: Validate template ID Validate template ID before creating a default request. Bug: 26866110 Bug: 27568958 Change-Id: Ifda457024f1d5c2b1382f189c1a8d5fda852d30d 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: LoginBigUserView* LockContentsView::AllocateLoginBigUserView( const mojom::LoginUserInfoPtr& user, bool is_primary) { LoginAuthUserView::Callbacks auth_user_callbacks; auth_user_callbacks.on_auth = base::BindRepeating( &LockContentsView::OnAuthenticate, base::Unretained(this)), auth_user_callbacks.on_tap = base::BindRepeating( &LockContentsView::SwapActiveAuthBetweenPrimaryAndSecondary, base::Unretained(this), is_primary), auth_user_callbacks.on_remove_warning_shown = base::BindRepeating(&LockContentsView::OnRemoveUserWarningShown, base::Unretained(this), is_primary); auth_user_callbacks.on_remove = base::BindRepeating( &LockContentsView::RemoveUser, base::Unretained(this), is_primary); auth_user_callbacks.on_easy_unlock_icon_hovered = base::BindRepeating( &LockContentsView::OnEasyUnlockIconHovered, base::Unretained(this)); auth_user_callbacks.on_easy_unlock_icon_tapped = base::BindRepeating( &LockContentsView::OnEasyUnlockIconTapped, base::Unretained(this)); LoginPublicAccountUserView::Callbacks public_account_callbacks; public_account_callbacks.on_tap = auth_user_callbacks.on_tap; public_account_callbacks.on_public_account_tapped = base::BindRepeating( &LockContentsView::OnPublicAccountTapped, base::Unretained(this)); return new LoginBigUserView(user, auth_user_callbacks, public_account_callbacks); } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} 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: static void hid_input_field(struct hid_device *hid, struct hid_field *field, __u8 *data, int interrupt) { unsigned n; unsigned count = field->report_count; unsigned offset = field->report_offset; unsigned size = field->report_size; __s32 min = field->logical_minimum; __s32 max = field->logical_maximum; __s32 *value; value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC); if (!value) return; for (n = 0; n < count; n++) { value[n] = min < 0 ? snto32(hid_field_extract(hid, data, offset + n * size, size), size) : hid_field_extract(hid, data, offset + n * size, size); /* Ignore report if ErrorRollOver */ if (!(field->flags & HID_MAIN_ITEM_VARIABLE) && value[n] >= min && value[n] <= max && field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1) goto exit; } for (n = 0; n < count; n++) { if (HID_MAIN_ITEM_VARIABLE & field->flags) { hid_process_event(hid, field, &field->usage[n], value[n], interrupt); continue; } if (field->value[n] >= min && field->value[n] <= max && field->usage[field->value[n] - min].hid && search(value, field->value[n], count)) hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt); if (value[n] >= min && value[n] <= max && field->usage[value[n] - min].hid && search(field->value, value[n], count)) hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt); } memcpy(field->value, value, count * sizeof(__s32)); exit: kfree(value); } Commit Message: HID: core: prevent out-of-bound readings Plugging a Logitech DJ receiver with KASAN activated raises a bunch of out-of-bound readings. The fields are allocated up to MAX_USAGE, meaning that potentially, we do not have enough fields to fit the incoming values. Add checks and silence KASAN. Signed-off-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: int kernel_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { if (sock->ops->sendpage) return sock->ops->sendpage(sock, page, offset, size, flags); return sock_no_sendpage(sock, page, offset, size, flags); } 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: 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: MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image, const ChannelType channel,double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].entropy=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[RedChannel].entropy; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[GreenChannel].entropy; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlueChannel].entropy; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[OpacityChannel].entropy; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlackChannel].entropy; channels++; } channel_statistics[CompositeChannels].entropy/=channels; *entropy=channel_statistics[CompositeChannels].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1615 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: static void WriteTo8BimProfile(Image *image,const char *name, const StringInfo *profile) { const unsigned char *datum, *q; register const unsigned char *p; size_t length; StringInfo *profile_8bim; ssize_t count; unsigned char length_byte; unsigned int value; unsigned short id, profile_id; if (LocaleCompare(name,"icc") == 0) profile_id=0x040f; else if (LocaleCompare(name,"iptc") == 0) profile_id=0x0404; else if (LocaleCompare(name,"xmp") == 0) profile_id=0x0424; else return; profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,"8bim"); if (profile_8bim == (StringInfo *) NULL) return; datum=GetStringInfoDatum(profile_8bim); length=GetStringInfoLength(profile_8bim); for (p=datum; p < (datum+length-16); ) { q=p; if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((count & 0x01) != 0) count++; if ((p > (datum+length-count)) || (count > (ssize_t) length)) break; if (id != profile_id) p+=count; else { size_t extent, offset; ssize_t extract_extent; StringInfo *extract_profile; extract_extent=0; extent=(datum+length)-(p+count); if (profile == (StringInfo *) NULL) { offset=(q-datum); extract_profile=AcquireStringInfo(offset+extent); (void) CopyMagickMemory(extract_profile->datum,datum,offset); } else { offset=(p-datum); extract_extent=profile->length; if ((extract_extent & 0x01) != 0) extract_extent++; extract_profile=AcquireStringInfo(offset+extract_extent+extent); (void) CopyMagickMemory(extract_profile->datum,datum,offset-4); (void) WriteResourceLong(extract_profile->datum+offset-4, (unsigned int) profile->length); (void) CopyMagickMemory(extract_profile->datum+offset, profile->datum,profile->length); } (void) CopyMagickMemory(extract_profile->datum+offset+extract_extent, p+count,extent); (void) AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString("8bim"),CloneStringInfo(extract_profile)); extract_profile=DestroyStringInfo(extract_profile); break; } } } Commit Message: Fixed SEGV reported in https://github.com/ImageMagick/ImageMagick/issues/130 CWE ID: CWE-20 Target: 1 Example 2: Code: DictionaryValue* BookmarkSpecificsToValue( const sync_pb::BookmarkSpecifics& proto) { DictionaryValue* value = new DictionaryValue(); SET_STR(url); SET_BYTES(favicon); SET_STR(title); return value; } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 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: xmlParseCharRef(xmlParserCtxtPtr ctxt) { unsigned int val = 0; int count = 0; unsigned int outofrange = 0; /* * Using RAW/CUR/NEXT is okay since we are working on ASCII range here */ if ((RAW == '&') && (NXT(1) == '#') && (NXT(2) == 'x')) { SKIP(3); GROW; while (RAW != ';') { /* loop blocked by count */ if (count++ > 20) { count = 0; GROW; } if ((RAW >= '0') && (RAW <= '9')) val = val * 16 + (CUR - '0'); else if ((RAW >= 'a') && (RAW <= 'f') && (count < 20)) val = val * 16 + (CUR - 'a') + 10; else if ((RAW >= 'A') && (RAW <= 'F') && (count < 20)) val = val * 16 + (CUR - 'A') + 10; else { xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL); val = 0; break; } if (val > 0x10FFFF) outofrange = val; NEXT; count++; } if (RAW == ';') { /* on purpose to avoid reentrancy problems with NEXT and SKIP */ ctxt->input->col++; ctxt->nbChars ++; ctxt->input->cur++; } } else if ((RAW == '&') && (NXT(1) == '#')) { SKIP(2); GROW; while (RAW != ';') { /* loop blocked by count */ if (count++ > 20) { count = 0; GROW; } if ((RAW >= '0') && (RAW <= '9')) val = val * 10 + (CUR - '0'); else { xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL); val = 0; break; } if (val > 0x10FFFF) outofrange = val; NEXT; count++; } if (RAW == ';') { /* on purpose to avoid reentrancy problems with NEXT and SKIP */ ctxt->input->col++; ctxt->nbChars ++; ctxt->input->cur++; } } else { xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL); } /* * [ WFC: Legal Character ] * Characters referred to using character references must match the * production for Char. */ if ((IS_CHAR(val) && (outofrange == 0))) { return(val); } else { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseCharRef: invalid xmlChar value %d\n", val); } return(0); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 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 ReadUncompressedRGBA(Image *image, DDSInfo *dds_info, ExceptionInfo *exception) { PixelPacket *q; ssize_t alphaBits, x, y; unsigned short color; alphaBits=0; if (dds_info->pixelformat.rgb_bitcount == 16) { if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000)) alphaBits=1; else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00)) { alphaBits=2; (void) SetImageType(image,GrayscaleMatteType); } else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000)) alphaBits=4; else ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); } for (y = 0; y < (ssize_t) dds_info->height; y++) { q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; for (x = 0; x < (ssize_t) dds_info->width; x++) { if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); if (alphaBits == 1) { SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 1) >> 11)/31.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 6) >> 11)/31.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255))); } else if (alphaBits == 2) { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) (color >> 8))); SetPixelGray(q,ScaleCharToQuantum((unsigned char)color)); } else { SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) (((color >> 12)/15.0)*255))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 4) >> 12)/15.0)*255))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 8) >> 12)/15.0)*255))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 12) >> 12)/15.0)*255))); } } else { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) return MagickFalse; } SkipRGBMipmaps(image, dds_info, 4); return MagickTrue; } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20 Target: 1 Example 2: Code: static long aac_compat_do_ioctl(struct aac_dev *dev, unsigned cmd, unsigned long arg) { long ret; mutex_lock(&aac_mutex); switch (cmd) { case FSACTL_MINIPORT_REV_CHECK: case FSACTL_SENDFIB: case FSACTL_OPEN_GET_ADAPTER_FIB: case FSACTL_CLOSE_GET_ADAPTER_FIB: case FSACTL_SEND_RAW_SRB: case FSACTL_GET_PCI_INFO: case FSACTL_QUERY_DISK: case FSACTL_DELETE_DISK: case FSACTL_FORCE_DELETE_DISK: case FSACTL_GET_CONTAINERS: case FSACTL_SEND_LARGE_FIB: ret = aac_do_ioctl(dev, cmd, (void __user *)arg); break; case FSACTL_GET_NEXT_ADAPTER_FIB: { struct fib_ioctl __user *f; f = compat_alloc_user_space(sizeof(*f)); ret = 0; if (clear_user(f, sizeof(*f))) ret = -EFAULT; if (copy_in_user(f, (void __user *)arg, sizeof(struct fib_ioctl) - sizeof(u32))) ret = -EFAULT; if (!ret) ret = aac_do_ioctl(dev, cmd, f); break; } default: ret = -ENOIOCTLCMD; break; } mutex_unlock(&aac_mutex); return ret; } Commit Message: aacraid: missing capable() check in compat ioctl In commit d496f94d22d1 ('[SCSI] aacraid: fix security weakness') we added a check on CAP_SYS_RAWIO to the ioctl. The compat ioctls need the check as well. Signed-off-by: Dan Carpenter <[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 CoordinatorImpl::PerformNextQueuedGlobalMemoryDump() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); QueuedRequest* request = GetCurrentRequest(); if (request == nullptr) return; std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); if (pid == base::kNullProcessId) { VLOG(1) << "Couldn't find a PID for client \"" << client_identity.name() << "." << client_identity.instance() << "\""; continue; } clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } auto chrome_callback = base::Bind( &CoordinatorImpl::OnChromeMemoryDumpResponse, base::Unretained(this)); auto os_callback = base::Bind(&CoordinatorImpl::OnOSMemoryDumpResponse, base::Unretained(this), request->dump_guid); QueuedRequestDispatcher::SetUpAndDispatch(request, clients, chrome_callback, os_callback); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnQueuedRequestTimedOut, base::Unretained(this), request->dump_guid), client_process_timeout_); if (request->args.add_to_trace && heap_profiler_) { request->heap_dump_in_progress = true; bool strip_path_from_mapped_files = base::trace_event::TraceLog::GetInstance() ->GetCurrentTraceConfig() .IsArgumentFilterEnabled(); heap_profiler_->DumpProcessesForTracing( strip_path_from_mapped_files, base::BindRepeating(&CoordinatorImpl::OnDumpProcessesForTracing, base::Unretained(this), request->dump_guid)); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnHeapDumpTimeOut, base::Unretained(this), request->dump_guid), kHeapDumpTimeout); } 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 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 vrend_renderer_init_blit_ctx(struct vrend_blitter_ctx *blit_ctx) { struct virgl_gl_ctx_param ctx_params; int i; if (blit_ctx->initialised) { vrend_clicbs->make_current(0, blit_ctx->gl_context); return; } ctx_params.shared = true; ctx_params.major_ver = VREND_GL_VER_MAJOR; ctx_params.minor_ver = VREND_GL_VER_MINOR; vrend_clicbs->make_current(0, blit_ctx->gl_context); glGenVertexArrays(1, &blit_ctx->vaoid); glGenFramebuffers(1, &blit_ctx->fb_id); glGenBuffers(1, &blit_ctx->vbo_id); blit_build_vs_passthrough(blit_ctx); for (i = 0; i < 4; i++) blit_ctx->vertices[i][0][3] = 1; /*v.w*/ glBindVertexArray(blit_ctx->vaoid); glBindBuffer(GL_ARRAY_BUFFER, blit_ctx->vbo_id); } Commit Message: CWE ID: CWE-772 Target: 1 Example 2: Code: void InspectorResourceAgent::didReceiveData(LocalFrame*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength) { String requestId = IdentifiersFactory::requestId(identifier); if (data) { NetworkResourcesData::ResourceData const* resourceData = m_resourcesData->data(requestId); if (resourceData && (!resourceData->cachedResource() || resourceData->cachedResource()->dataBufferingPolicy() == DoNotBufferData || isErrorStatusCode(resourceData->httpStatusCode()))) m_resourcesData->maybeAddResourceData(requestId, data, dataLength); } m_frontend->dataReceived(requestId, currentTime(), dataLength, encodedDataLength); } Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser. BUG=366585 Review URL: https://codereview.chromium.org/251183005 git-svn-id: svn://svn.chromium.org/blink/trunk@172984 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: QQmlComponent* QQuickWebViewExperimental::confirmDialog() const { Q_D(const QQuickWebView); return d->confirmDialog; } Commit Message: [Qt][WK2] There's no way to test the gesture tap on WTR https://bugs.webkit.org/show_bug.cgi?id=92895 Reviewed by Kenneth Rohde Christiansen. Source/WebKit2: Add an instance of QtViewportHandler to QQuickWebViewPrivate, so it's now available on mobile and desktop modes, as a side effect gesture tap events can now be created and sent to WebCore. This is needed to test tap gestures and to get tap gestures working when you have a WebView (in desktop mode) on notebooks equipped with touch screens. * UIProcess/API/qt/qquickwebview.cpp: (QQuickWebViewPrivate::onComponentComplete): (QQuickWebViewFlickablePrivate::onComponentComplete): Implementation moved to QQuickWebViewPrivate::onComponentComplete. * UIProcess/API/qt/qquickwebview_p_p.h: (QQuickWebViewPrivate): (QQuickWebViewFlickablePrivate): Tools: WTR doesn't create the QQuickItem from C++, not from QML, so a call to componentComplete() was added to mimic the QML behaviour. * WebKitTestRunner/qt/PlatformWebViewQt.cpp: (WTR::PlatformWebView::PlatformWebView): git-svn-id: svn://svn.chromium.org/blink/trunk@124625 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: const PPB_NaCl_Private* GetNaclInterface() { pp::Module *module = pp::Module::Get(); CHECK(module); return static_cast<const PPB_NaCl_Private*>( module->GetBrowserInterface(PPB_NACL_PRIVATE_INTERFACE)); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: void Parcel::Blob::init(bool mapped, void* data, size_t size) { mMapped = mapped; mData = data; mSize = size; } Commit Message: Disregard alleged binder entities beyond parcel bounds When appending one parcel's contents to another, ignore binder objects within the source Parcel that appear to lie beyond the formal bounds of that Parcel's data buffer. Bug 17312693 Change-Id: If592a260f3fcd9a56fc160e7feb2c8b44c73f514 (cherry picked from commit 27182be9f20f4f5b48316666429f09b9ecc1f22e) 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: long Chapters::Edition::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) { // Atom ID status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: 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 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 ComponentControllerImpl::OnNavigationStateChanged( chromium::web::NavigationStateChangeDetails change, OnNavigationStateChangedCallback callback) {} Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264 Target: 1 Example 2: Code: service_manager::InterfaceProvider* RenderFrameHostImpl::GetJavaInterfaces() { if (!java_interfaces_) { service_manager::mojom::InterfaceProviderPtr provider; BindInterfaceRegistryForRenderFrameHost(mojo::MakeRequest(&provider), this); java_interfaces_.reset(new service_manager::InterfaceProvider); java_interfaces_->Bind(std::move(provider)); } return java_interfaces_.get(); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <[email protected]> Reviewed-by: Charles Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#466778} 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: char *stristr(const char *data, const char *key) { const char *max; int keylen, datalen, pos; keylen = strlen(key); datalen = strlen(data); if (keylen > datalen) return NULL; if (keylen == 0) return (char *) data; max = data+datalen-keylen; pos = 0; while (data <= max) { if (key[pos] == '\0') return (char *) data; if (i_toupper(data[pos]) == i_toupper(key[pos])) pos++; else { data++; pos = 0; } } return NULL; } Commit Message: Merge branch 'security' into 'master' Security Closes #10 See merge request !17 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: static void do_free_upto(BIO *f, BIO *upto) { if (upto) { BIO *tbio; do { tbio = BIO_pop(f); BIO_free(f); f = tbio; } while (f != upto); } else BIO_free_all(f); } Commit Message: Canonicalise input in CMS_verify. If content is detached and not binary mode translate the input to CRLF format. Before this change the input was verified verbatim which lead to a discrepancy between sign and verify. CWE ID: CWE-399 Target: 1 Example 2: Code: static int php_tcp_sockop_set_option(php_stream *stream, int option, int value, void *ptrparam) { php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract; php_stream_xport_param *xparam; switch(option) { case PHP_STREAM_OPTION_XPORT_API: xparam = (php_stream_xport_param *)ptrparam; switch(xparam->op) { case STREAM_XPORT_OP_CONNECT: case STREAM_XPORT_OP_CONNECT_ASYNC: xparam->outputs.returncode = php_tcp_sockop_connect(stream, sock, xparam); return PHP_STREAM_OPTION_RETURN_OK; case STREAM_XPORT_OP_BIND: xparam->outputs.returncode = php_tcp_sockop_bind(stream, sock, xparam); return PHP_STREAM_OPTION_RETURN_OK; case STREAM_XPORT_OP_ACCEPT: xparam->outputs.returncode = php_tcp_sockop_accept(stream, sock, xparam STREAMS_CC); return PHP_STREAM_OPTION_RETURN_OK; default: /* fall through */ ; } } return php_sockop_set_option(stream, option, value, ptrparam); } Commit Message: Detect invalid port in xp_socket parse ip address For historical reasons, fsockopen() accepts the port and hostname separately: fsockopen('127.0.0.1', 80) However, with the introdcution of stream transports in PHP 4.3, it became possible to include the port in the hostname specifier: fsockopen('127.0.0.1:80') Or more formally: fsockopen('tcp://127.0.0.1:80') Confusing results when these two forms are combined, however. fsockopen('127.0.0.1:80', 443) results in fsockopen() attempting to connect to '127.0.0.1:80:443' which any reasonable stack would consider invalid. Unfortunately, PHP parses the address looking for the first colon (with special handling for IPv6, don't worry) and calls atoi() from there. atoi() in turn, simply stops parsing at the first non-numeric character and returns the value so far. The end result is that the explicitly supplied port is treated as ignored garbage, rather than producing an error. This diff replaces atoi() with strtol() and inspects the stop character. If additional "garbage" of any kind is found, it fails and returns an error. CWE ID: CWE-918 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 RunRoundTripErrorCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); int max_error = 0; int total_error = 0; const int count_test_block = 100000; DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64); DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, 64); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, 64); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, 64); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < 64; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; } REGISTER_STATE_CHECK( RunFwdTxfm(test_input_block, test_temp_block, pitch_)); for (int j = 0; j < 64; ++j) { if (test_temp_block[j] > 0) { test_temp_block[j] += 2; test_temp_block[j] /= 4; test_temp_block[j] *= 4; } else { test_temp_block[j] -= 2; test_temp_block[j] /= 4; test_temp_block[j] *= 4; } } REGISTER_STATE_CHECK( RunInvTxfm(test_temp_block, dst, pitch_)); for (int j = 0; j < 64; ++j) { const int diff = dst[j] - src[j]; const int error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(1, max_error) << "Error: 8x8 FDCT/IDCT or FHT/IHT has an individual" << " roundtrip error > 1"; EXPECT_GE(count_test_block/5, total_error) << "Error: 8x8 FDCT/IDCT or FHT/IHT has average roundtrip " << "error > 1/5 per block"; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 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: exsltCryptoPopString (xmlXPathParserContextPtr ctxt, int nargs, xmlChar ** str) { int str_len = 0; if ((nargs < 1) || (nargs > 2)) { xmlXPathSetArityError (ctxt); return 0; } *str = xmlXPathPopString (ctxt); str_len = xmlUTF8Strlen (*str); if (str_len == 0) { xmlXPathReturnEmptyString (ctxt); xmlFree (*str); return 0; } return str_len; } 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 Target: 1 Example 2: Code: static void SetUpTestCase() { scoped_task_environment = std::make_unique<TestBrowserThreadBundle>( TestBrowserThreadBundle::REAL_IO_THREAD); io_runner = base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO}); base::Thread::Options options(base::MessageLoop::TYPE_IO, 0); background_thread.reset(new base::Thread("AppCacheTest::BackgroundThread")); ASSERT_TRUE(background_thread->StartWithOptions(options)); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200 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 yr_re_ast_create( RE_AST** re_ast) { *re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST)); if (*re_ast == NULL) return ERROR_INSUFFICIENT_MEMORY; (*re_ast)->flags = 0; (*re_ast)->root_node = NULL; return ERROR_SUCCESS; } Commit Message: Fix issue #674. Move regexp limits to limits.h. CWE ID: CWE-674 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 kvm_set_guest_paused(struct kvm_vcpu *vcpu) { if (!vcpu->arch.time_page) return -EINVAL; vcpu->arch.pvclock_set_guest_stopped_request = true; kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); return 0; } Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797) There is a potential use after free issue with the handling of MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable memory such as frame buffers then KVM might continue to write to that address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins the page in memory so it's unlikely to cause an issue, but if the user space component re-purposes the memory previously used for the guest, then the guest will be able to corrupt that memory. Tested: Tested against kvmclock unit test Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: base::string16 AuthenticatorTransportSelectorSheetModel::GetStepTitle() const { return l10n_util::GetStringFUTF16(IDS_WEBAUTHN_TRANSPORT_SELECTION_TITLE, GetRelyingPartyIdString(dialog_model())); } Commit Message: chrome/browser/ui/webauthn: long domains may cause a line break. As requested by UX in [1], allow long host names to split a title into two lines. This allows us to show more of the name before eliding, although sufficiently long names will still trigger elision. Screenshot at https://drive.google.com/open?id=1_V6t2CeZDAVazy3Px-OET2LnB__aEW1r. [1] https://docs.google.com/presentation/d/1TtxkPUchyVZulqgdMcfui-68B0W-DWaFFVJEffGIbLA/edit#slide=id.g5913c4105f_1_12 Change-Id: I70f6541e0db3e9942239304de43b487a7561ca34 Bug: 870892 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1601812 Auto-Submit: Adam Langley <[email protected]> Commit-Queue: Nina Satragno <[email protected]> Reviewed-by: Nina Satragno <[email protected]> Cr-Commit-Position: refs/heads/master@{#658114} 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 Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MaxTextExtent], id[MaxTextExtent], keyword[MaxTextExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register ssize_t i; size_t depth, length; ssize_t count; StringInfo *profile; unsigned int signature; /* 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); } (void) CopyMagickString(cache_filename,image->filename,MaxTextExtent); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ profiles=(LinkedListInfo *) NULL; length=MaxTextExtent; options=AcquireString((char *) NULL); signature=GetMagickSignature((const StringInfo *) NULL); image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MaxTextExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorDatabase(options,&image->background_color, exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorDatabase(options,&image->border_color, exception); break; } (void) SetImageProperty(image,keyword,options); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=StringToDouble(options, (char **) NULL); break; } (void) SetImageProperty(image,keyword,options); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MaxTextExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"magick-signature") == 0) { signature=(unsigned int) StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"matte") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"matte-color") == 0) { (void) QueryColorDatabase(options,&image->matte_color, exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=StringToDouble( options,(char **) NULL); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=StringToDouble(options, (char **) NULL); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"opaque") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->matte=(MagickBooleanType) matte; break; } if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=BlobToStringInfo((const void *) NULL,(size_t) StringToLong(options)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); (void) SetImageProfile(image,keyword+8,profile); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions,MagickFalse, options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options); break; } default: { (void) SetImageProperty(image,keyword,options); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (signature != GetMagickSignature((const StringInfo *) NULL)) ThrowReaderException(CacheError,"IncompatibleAPI"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MaxTextExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MaxTextExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MaxTextExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; register unsigned char *p; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); count=ReadBlob(image,GetStringInfoLength(profile),p); } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=colormap; switch (depth) { default: ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) ThrowReaderException(CacheError,"UnableToPersistPixelCache"); /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* 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 (c != EOF); (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: void PrintingMessageFilter::OnUpdatePrintSettingsReply( scoped_refptr<printing::PrinterQuery> printer_query, IPC::Message* reply_msg) { PrintMsg_PrintPages_Params params; if (printer_query->last_status() != printing::PrintingContext::OK) { params.Reset(); } else { RenderParamsFromPrintSettings(printer_query->settings(), &params.params); params.params.document_cookie = printer_query->cookie(); params.pages = printing::PageRange::GetPages(printer_query->settings().ranges); } PrintHostMsg_UpdatePrintSettings::WriteReplyParams(reply_msg, params); Send(reply_msg); if (printer_query->cookie() && printer_query->settings().dpi()) print_job_manager_->QueuePrinterQuery(printer_query.get()); else printer_query->StopWorker(); } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static char *legousbtower_devnode(struct device *dev, umode_t *mode) { return kasprintf(GFP_KERNEL, "usb/%s", dev_name(dev)); } Commit Message: usb: misc: legousbtower: Fix NULL pointer deference This patch fixes a NULL pointer dereference caused by a race codition in the probe function of the legousbtower driver. It re-structures the probe function to only register the interface after successfully reading the board's firmware ID. The probe function does not deregister the usb interface after an error receiving the devices firmware ID. The device file registered (/dev/usb/legousbtower%d) may be read/written globally before the probe function returns. When tower_delete is called in the probe function (after an r/w has been initiated), core dev structures are deleted while the file operation functions are still running. If the 0 address is mappable on the machine, this vulnerability can be used to create a Local Priviege Escalation exploit via a write-what-where condition by remapping dev->interrupt_out_buffer in tower_write. A forged USB device and local program execution would be required for LPE. The USB device would have to delay the control message in tower_probe and accept the control urb in tower_open whilst guest code initiated a write to the device file as tower_delete is called from the error in tower_probe. This bug has existed since 2003. Patch tested by emulated device. Reported-by: James Patrick-Evans <[email protected]> Tested-by: James Patrick-Evans <[email protected]> Signed-off-by: James Patrick-Evans <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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: void HeadlessWebContentsImpl::DetachClient(HeadlessDevToolsClient* client) { DCHECK(agent_host_); HeadlessDevToolsClientImpl::From(client)->DetachFromHost(agent_host_.get()); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} 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: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), nullptr, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string) && combining_diacritics_exceptions_.containsNone(label_string)) { return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string) && !lgc_letters_n_ascii_.containsAll(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])" R"([\u30ce\u30f3\u30bd\u30be])" R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)" R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)" R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)" R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)" R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)" R"([a-z]\u30fb|\u30fb[a-z]|)" R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)" R"([ijl\u0131]\u0307)", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); } Commit Message: Block dotless-i / j + a combining mark U+0131 (doltess i) and U+0237 (dotless j) are blocked from being followed by a combining mark in U+0300 block. Bug: 774842 Test: See the bug Change-Id: I92aac0e97233184864d060fd0f137a90b042c679 Reviewed-on: https://chromium-review.googlesource.com/767888 Commit-Queue: Jungshik Shin <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#517605} CWE ID: CWE-20 Target: 1 Example 2: Code: static int request_frame(AVFilterLink *outlink) { int ret; AVFilterContext *ctx = outlink->src; FieldMatchContext *fm = ctx->priv; const uint32_t eof_mask = 1<<INPUT_MAIN | fm->ppsrc<<INPUT_CLEANSRC; if ((fm->eof & eof_mask) == eof_mask) // flush done? return AVERROR_EOF; if ((ret = request_inlink(ctx, INPUT_MAIN)) < 0) return ret; if (fm->ppsrc && (ret = request_inlink(ctx, INPUT_CLEANSRC)) < 0) return ret; return 0; } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <[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: KeyedService* LogoServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = static_cast<Profile*>(context); DCHECK(!profile->IsOffTheRecord()); #if defined(OS_ANDROID) bool use_gray_background = !GetIsChromeHomeEnabled(); #else bool use_gray_background = false; #endif return new LogoService(profile->GetPath().Append(kCachedLogoDirectory), TemplateURLServiceFactory::GetForProfile(profile), base::MakeUnique<suggestions::ImageDecoderImpl>(), profile->GetRequestContext(), use_gray_background); } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} 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: fep_client_open (const char *address) { FepClient *client; struct sockaddr_un sun; ssize_t sun_len; int retval; if (!address) address = getenv ("LIBFEP_CONTROL_SOCK"); if (!address) return NULL; if (strlen (address) + 1 >= sizeof(sun.sun_path)) { fep_log (FEP_LOG_LEVEL_WARNING, "unix domain socket path too long: %d + 1 >= %d", strlen (address), sizeof (sun.sun_path)); free (address); return NULL; } client = xzalloc (sizeof(FepClient)); client->filter_running = false; client->messages = NULL; memset (&sun, 0, sizeof(struct sockaddr_un)); sun.sun_family = AF_UNIX; #ifdef __linux__ sun.sun_path[0] = '\0'; memcpy (sun.sun_path + 1, address, strlen (address)); sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (address) + 1; #else memcpy (sun.sun_path, address, strlen (address)); sun_len = sizeof (struct sockaddr_un); #endif client->control = socket (AF_UNIX, SOCK_STREAM, 0); if (client->control < 0) { free (client); return NULL; } retval = connect (client->control, (const struct sockaddr *) &sun, sun_len); if (retval < 0) { close (client->control); free (client); return NULL; } return client; } Commit Message: Don't use abstract Unix domain sockets CWE ID: CWE-264 Target: 1 Example 2: Code: GF_Err btrt_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_BitRateBox *ptr = (GF_BitRateBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_bs_write_u32(bs, ptr->bufferSizeDB); gf_bs_write_u32(bs, ptr->maxBitrate); gf_bs_write_u32(bs, ptr->avgBitrate); return GF_OK; } Commit Message: fix some exploitable overflows (#994, #997) 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 build_skb_flow_key(struct flowi4 *fl4, const struct sk_buff *skb, const struct sock *sk) { const struct iphdr *iph = ip_hdr(skb); int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; __build_flow_key(fl4, sk, iph, oif, tos, prot, mark, 0); } Commit Message: ipv4: try to cache dst_entries which would cause a redirect Not caching dst_entries which cause redirects could be exploited by hosts on the same subnet, causing a severe DoS attack. This effect aggravated since commit f88649721268999 ("ipv4: fix dst race in sk_dst_get()"). Lookups causing redirects will be allocated with DST_NOCACHE set which will force dst_release to free them via RCU. Unfortunately waiting for RCU grace period just takes too long, we can end up with >1M dst_entries waiting to be released and the system will run OOM. rcuos threads cannot catch up under high softirq load. Attaching the flag to emit a redirect later on to the specific skb allows us to cache those dst_entries thus reducing the pressure on allocation and deallocation. This issue was discovered by Marcelo Leitner. Cc: Julian Anastasov <[email protected]> Signed-off-by: Marcelo Leitner <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Julian Anastasov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-17 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: png_get_copyright(png_structp png_ptr) { PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */ #ifdef PNG_STRING_COPYRIGHT return PNG_STRING_COPYRIGHT #else #ifdef __STDC__ return ((png_charp) PNG_STRING_NEWLINE \ "libpng version 1.2.52 - November 20, 2014" PNG_STRING_NEWLINE \ "Copyright (c) 1998-2014 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \ "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \ "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \ PNG_STRING_NEWLINE); #else return ((png_charp) "libpng version 1.2.52 - November 20, 2014\ Copyright (c) 1998-2014 Glenn Randers-Pehrson\ Copyright (c) 1996-1997 Andreas Dilger\ Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc."); #endif #endif } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoClearStencil(GLint s) { api()->glClearStencilFn(s); return error::kNoError; } 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 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: asmlinkage void __kprobes do_page_fault(struct pt_regs *regs, unsigned long write, unsigned long address) { struct vm_area_struct * vma = NULL; struct task_struct *tsk = current; struct mm_struct *mm = tsk->mm; const int field = sizeof(unsigned long) * 2; siginfo_t info; int fault; #if 0 printk("Cpu%d[%s:%d:%0*lx:%ld:%0*lx]\n", raw_smp_processor_id(), current->comm, current->pid, field, address, write, field, regs->cp0_epc); #endif #ifdef CONFIG_KPROBES /* * This is to notify the fault handler of the kprobes. The * exception code is redundant as it is also carried in REGS, * but we pass it anyhow. */ if (notify_die(DIE_PAGE_FAULT, "page fault", regs, -1, (regs->cp0_cause >> 2) & 0x1f, SIGSEGV) == NOTIFY_STOP) return; #endif info.si_code = SEGV_MAPERR; /* * We fault-in kernel-space virtual memory on-demand. The * 'reference' page table is init_mm.pgd. * * NOTE! We MUST NOT take any locks for this case. We may * be in an interrupt or a critical region, and should * only copy the information from the master page table, * nothing more. */ #ifdef CONFIG_64BIT # define VMALLOC_FAULT_TARGET no_context #else # define VMALLOC_FAULT_TARGET vmalloc_fault #endif if (unlikely(address >= VMALLOC_START && address <= VMALLOC_END)) goto VMALLOC_FAULT_TARGET; #ifdef MODULE_START if (unlikely(address >= MODULE_START && address < MODULE_END)) goto VMALLOC_FAULT_TARGET; #endif /* * If we're in an interrupt or have no user * context, we must not take the fault.. */ if (in_atomic() || !mm) goto bad_area_nosemaphore; down_read(&mm->mmap_sem); vma = find_vma(mm, address); if (!vma) goto bad_area; if (vma->vm_start <= address) goto good_area; if (!(vma->vm_flags & VM_GROWSDOWN)) goto bad_area; if (expand_stack(vma, address)) goto bad_area; /* * Ok, we have a good vm_area for this memory access, so * we can handle it.. */ good_area: info.si_code = SEGV_ACCERR; if (write) { if (!(vma->vm_flags & VM_WRITE)) goto bad_area; } else { if (kernel_uses_smartmips_rixi) { if (address == regs->cp0_epc && !(vma->vm_flags & VM_EXEC)) { #if 0 pr_notice("Cpu%d[%s:%d:%0*lx:%ld:%0*lx] XI violation\n", raw_smp_processor_id(), current->comm, current->pid, field, address, write, field, regs->cp0_epc); #endif goto bad_area; } if (!(vma->vm_flags & VM_READ)) { #if 0 pr_notice("Cpu%d[%s:%d:%0*lx:%ld:%0*lx] RI violation\n", raw_smp_processor_id(), current->comm, current->pid, field, address, write, field, regs->cp0_epc); #endif goto bad_area; } } else { if (!(vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC))) goto bad_area; } } /* * If for any reason at all we couldn't handle the fault, * make sure we exit gracefully rather than endlessly redo * the fault. */ fault = handle_mm_fault(mm, vma, address, write ? FAULT_FLAG_WRITE : 0); perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address); if (unlikely(fault & VM_FAULT_ERROR)) { if (fault & VM_FAULT_OOM) goto out_of_memory; else if (fault & VM_FAULT_SIGBUS) goto do_sigbus; BUG(); } if (fault & VM_FAULT_MAJOR) { perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0, regs, address); tsk->maj_flt++; } else { perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0, regs, address); tsk->min_flt++; } up_read(&mm->mmap_sem); return; /* * Something tried to access memory that isn't in our memory map.. * Fix it, but check if it's kernel or user first.. */ bad_area: up_read(&mm->mmap_sem); bad_area_nosemaphore: /* User mode accesses just cause a SIGSEGV */ if (user_mode(regs)) { tsk->thread.cp0_badvaddr = address; tsk->thread.error_code = write; #if 0 printk("do_page_fault() #2: sending SIGSEGV to %s for " "invalid %s\n%0*lx (epc == %0*lx, ra == %0*lx)\n", tsk->comm, write ? "write access to" : "read access from", field, address, field, (unsigned long) regs->cp0_epc, field, (unsigned long) regs->regs[31]); #endif info.si_signo = SIGSEGV; info.si_errno = 0; /* info.si_code has been set above */ info.si_addr = (void __user *) address; force_sig_info(SIGSEGV, &info, tsk); return; } no_context: /* Are we prepared to handle this kernel fault? */ if (fixup_exception(regs)) { current->thread.cp0_baduaddr = address; return; } /* * Oops. The kernel tried to access some bad page. We'll have to * terminate things with extreme prejudice. */ bust_spinlocks(1); printk(KERN_ALERT "CPU %d Unable to handle kernel paging request at " "virtual address %0*lx, epc == %0*lx, ra == %0*lx\n", raw_smp_processor_id(), field, address, field, regs->cp0_epc, field, regs->regs[31]); die("Oops", regs); out_of_memory: /* * We ran out of memory, call the OOM killer, and return the userspace * (which will retry the fault, or kill us if we got oom-killed). */ up_read(&mm->mmap_sem); pagefault_out_of_memory(); return; do_sigbus: up_read(&mm->mmap_sem); /* Kernel mode? Handle exceptions or die */ if (!user_mode(regs)) goto no_context; else /* * Send a sigbus, regardless of whether we were in kernel * or user mode. */ #if 0 printk("do_page_fault() #3: sending SIGBUS to %s for " "invalid %s\n%0*lx (epc == %0*lx, ra == %0*lx)\n", tsk->comm, write ? "write access to" : "read access from", field, address, field, (unsigned long) regs->cp0_epc, field, (unsigned long) regs->regs[31]); #endif tsk->thread.cp0_badvaddr = address; info.si_signo = SIGBUS; info.si_errno = 0; info.si_code = BUS_ADRERR; info.si_addr = (void __user *) address; force_sig_info(SIGBUS, &info, tsk); return; #ifndef CONFIG_64BIT vmalloc_fault: { /* * Synchronize this task's top level page-table * with the 'reference' page table. * * Do _not_ use "tsk" here. We might be inside * an interrupt in the middle of a task switch.. */ int offset = __pgd_offset(address); pgd_t *pgd, *pgd_k; pud_t *pud, *pud_k; pmd_t *pmd, *pmd_k; pte_t *pte_k; pgd = (pgd_t *) pgd_current[raw_smp_processor_id()] + offset; pgd_k = init_mm.pgd + offset; if (!pgd_present(*pgd_k)) goto no_context; set_pgd(pgd, *pgd_k); pud = pud_offset(pgd, address); pud_k = pud_offset(pgd_k, address); if (!pud_present(*pud_k)) goto no_context; pmd = pmd_offset(pud, address); pmd_k = pmd_offset(pud_k, address); if (!pmd_present(*pmd_k)) goto no_context; set_pmd(pmd, *pmd_k); pte_k = pte_offset_kernel(pmd_k, address); if (!pte_present(*pte_k)) goto no_context; return; } #endif } 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: void TopSitesImpl::SetTopSites(const MostVisitedURLList& new_top_sites, const CallLocation location) { DCHECK(thread_checker_.CalledOnValidThread()); MostVisitedURLList top_sites(new_top_sites); size_t num_forced_urls = MergeCachedForcedURLs(&top_sites); AddPrepopulatedPages(&top_sites, num_forced_urls); TopSitesDelta delta; DiffMostVisited(cache_->top_sites(), top_sites, &delta); TopSitesBackend::RecordHistogram record_or_not = TopSitesBackend::RECORD_HISTOGRAM_NO; if (location == CALL_LOCATION_FROM_ON_GOT_MOST_VISITED_THUMBNAILS && !histogram_recorded_) { size_t delta_size = delta.deleted.size() + delta.added.size() + delta.moved.size(); UMA_HISTOGRAM_COUNTS_100("History.FirstSetTopSitesDeltaSize", delta_size); record_or_not = TopSitesBackend::RECORD_HISTOGRAM_YES; histogram_recorded_ = true; } bool should_notify_observers = false; if (!delta.deleted.empty() || !delta.added.empty() || !delta.moved.empty()) { backend_->UpdateTopSites(delta, record_or_not); should_notify_observers = true; } if (!should_notify_observers) should_notify_observers = DoTitlesDiffer(cache_->top_sites(), top_sites); cache_->SetTopSites(top_sites); if (!temp_images_.empty()) { for (const MostVisitedURL& mv : top_sites) { const GURL& canonical_url = cache_->GetCanonicalURL(mv.url); for (TempImages::iterator it = temp_images_.begin(); it != temp_images_.end(); ++it) { if (canonical_url == cache_->GetCanonicalURL(it->first)) { bool success = SetPageThumbnailEncoded( mv.url, it->second.thumbnail.get(), it->second.thumbnail_score); if (success) { UMA_HISTOGRAM_ENUMERATION("Thumbnails.AddedToTopSites", THUMBNAIL_PROMOTED_TEMP_TO_REGULAR, THUMBNAIL_EVENT_COUNT); } temp_images_.erase(it); break; } } } } if (top_sites.size() - num_forced_urls >= kNonForcedTopSitesNumber) temp_images_.clear(); ResetThreadSafeCache(); ResetThreadSafeImageCache(); if (should_notify_observers) { if (location == CALL_LOCATION_FROM_FORCED_URLS) NotifyTopSitesChanged(TopSitesObserver::ChangeReason::FORCED_URL); else NotifyTopSitesChanged(TopSitesObserver::ChangeReason::MOST_VISITED); } } Commit Message: TopSites: Clear thumbnails from the cache when their URLs get removed We already cleared the thumbnails from persistent storage, but they remained in the in-memory cache, so they remained accessible (until the next Chrome restart) even after all browsing data was cleared. Bug: 758169 Change-Id: Id916d22358430a82e6d5043ac04fa463a32f824f Reviewed-on: https://chromium-review.googlesource.com/758640 Commit-Queue: Marc Treib <[email protected]> Reviewed-by: Sylvain Defresne <[email protected]> Cr-Commit-Position: refs/heads/master@{#514861} CWE ID: CWE-200 Target: 1 Example 2: Code: static void airo_process_scan_results (struct airo_info *ai) { union iwreq_data wrqu; BSSListRid bss; int rc; BSSListElement * loop_net; BSSListElement * tmp_net; /* Blow away current list of scan results */ list_for_each_entry_safe (loop_net, tmp_net, &ai->network_list, list) { list_move_tail (&loop_net->list, &ai->network_free_list); /* Don't blow away ->list, just BSS data */ memset (loop_net, 0, sizeof (loop_net->bss)); } /* Try to read the first entry of the scan result */ rc = PC4500_readrid(ai, ai->bssListFirst, &bss, ai->bssListRidLen, 0); if((rc) || (bss.index == cpu_to_le16(0xffff))) { /* No scan results */ goto out; } /* Read and parse all entries */ tmp_net = NULL; while((!rc) && (bss.index != cpu_to_le16(0xffff))) { /* Grab a network off the free list */ if (!list_empty(&ai->network_free_list)) { tmp_net = list_entry(ai->network_free_list.next, BSSListElement, list); list_del(ai->network_free_list.next); } if (tmp_net != NULL) { memcpy(tmp_net, &bss, sizeof(tmp_net->bss)); list_add_tail(&tmp_net->list, &ai->network_list); tmp_net = NULL; } /* Read next entry */ rc = PC4500_readrid(ai, ai->bssListNext, &bss, ai->bssListRidLen, 0); } out: ai->scan_timeout = 0; clear_bit(JOB_SCAN_RESULTS, &ai->jobs); up(&ai->sem); /* Send an empty event to user space. * We don't send the received data on * the event because it would require * us to do complex transcoding, and * we want to minimise the work done in * the irq handler. Use a request to * extract the data - Jean II */ wrqu.data.length = 0; wrqu.data.flags = 0; wireless_send_event(ai->dev, SIOCGIWSCAN, &wrqu, NULL); } 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: 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: EffectPaintPropertyNode* EffectPaintPropertyNode::Root() { DEFINE_STATIC_REF(EffectPaintPropertyNode, root, (EffectPaintPropertyNode::Create( nullptr, State{TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root()}))); return root; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} 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 em_fxsave(struct x86_emulate_ctxt *ctxt) { struct fxregs_state fx_state; size_t size; int rc; rc = check_fxsr(ctxt); if (rc != X86EMUL_CONTINUE) return rc; ctxt->ops->get_fpu(ctxt); rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_state)); ctxt->ops->put_fpu(ctxt); if (rc != X86EMUL_CONTINUE) return rc; if (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR) size = offsetof(struct fxregs_state, xmm_space[8 * 16/4]); else size = offsetof(struct fxregs_state, xmm_space[0]); return segmented_write(ctxt, ctxt->memop.addr.mem, &fx_state, size); } Commit Message: KVM: x86: Introduce segmented_write_std Introduces segemented_write_std. Switches from emulated reads/writes to standard read/writes in fxsave, fxrstor, sgdt, and sidt. This fixes CVE-2017-2584, a longstanding kernel memory leak. Since commit 283c95d0e389 ("KVM: x86: emulate FXSAVE and FXRSTOR", 2016-11-09), which is luckily not yet in any final release, this would also be an exploitable kernel memory *write*! Reported-by: Dmitry Vyukov <[email protected]> Cc: [email protected] Fixes: 96051572c819194c37a8367624b285be10297eca Fixes: 283c95d0e3891b64087706b344a4b545d04a6e62 Suggested-by: Paolo Bonzini <[email protected]> Signed-off-by: Steve Rutherford <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: strtoint(const char *const str) { char *endptr; const int r = strtol(str, &endptr, 10); if (*endptr) return -1; return r; } Commit Message: evdns: fix searching empty hostnames From #332: Here follows a bug report by **Guido Vranken** via the _Tor bug bounty program_. Please credit Guido accordingly. ## Bug report The DNS code of Libevent contains this rather obvious OOB read: ```c static char * search_make_new(const struct search_state *const state, int n, const char *const base_name) { const size_t base_len = strlen(base_name); const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1; ``` If the length of ```base_name``` is 0, then line 3125 reads 1 byte before the buffer. This will trigger a crash on ASAN-protected builds. To reproduce: Build libevent with ASAN: ``` $ CFLAGS='-fomit-frame-pointer -fsanitize=address' ./configure && make -j4 ``` Put the attached ```resolv.conf``` and ```poc.c``` in the source directory and then do: ``` $ gcc -fsanitize=address -fomit-frame-pointer poc.c .libs/libevent.a $ ./a.out ================================================================= ==22201== ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60060000efdf at pc 0x4429da bp 0x7ffe1ed47300 sp 0x7ffe1ed472f8 READ of size 1 at 0x60060000efdf thread T0 ``` P.S. we can add a check earlier, but since this is very uncommon, I didn't add it. Fixes: #332 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: cib_notify_client(gpointer key, gpointer value, gpointer user_data) { const char *type = NULL; gboolean do_send = FALSE; cib_client_t *client = value; xmlNode *update_msg = user_data; CRM_CHECK(client != NULL, return TRUE); CRM_CHECK(update_msg != NULL, return TRUE); if (client->ipc == NULL) { crm_warn("Skipping client with NULL channel"); return FALSE; } type = crm_element_value(update_msg, F_SUBTYPE); CRM_LOG_ASSERT(type != NULL); if (client->diffs && safe_str_eq(type, T_CIB_DIFF_NOTIFY)) { do_send = TRUE; } else if (client->replace && safe_str_eq(type, T_CIB_REPLACE_NOTIFY)) { do_send = TRUE; } else if (client->confirmations && safe_str_eq(type, T_CIB_UPDATE_CONFIRM)) { do_send = TRUE; } else if (client->pre_notify && safe_str_eq(type, T_CIB_PRE_NOTIFY)) { do_send = TRUE; } else if (client->post_notify && safe_str_eq(type, T_CIB_POST_NOTIFY)) { do_send = TRUE; } if (do_send) { if (client->ipc) { if(crm_ipcs_send(client->ipc, 0, update_msg, TRUE) == FALSE) { crm_warn("Notification of client %s/%s failed", client->name, client->id); } #ifdef HAVE_GNUTLS_GNUTLS_H } else if (client->session) { crm_debug("Sent %s notification to client %s/%s", type, client->name, client->id); crm_send_remote_msg(client->session, update_msg, client->encrypted); #endif } else { crm_err("Unknown transport for %s", client->name); } } return FALSE; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. 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: batadv_frag_merge_packets(struct hlist_head *chain, struct sk_buff *skb) { struct batadv_frag_packet *packet; struct batadv_frag_list_entry *entry; struct sk_buff *skb_out = NULL; int size, hdr_size = sizeof(struct batadv_frag_packet); /* Make sure incoming skb has non-bogus data. */ packet = (struct batadv_frag_packet *)skb->data; size = ntohs(packet->total_size); if (size > batadv_frag_size_limit()) goto free; /* Remove first entry, as this is the destination for the rest of the * fragments. */ entry = hlist_entry(chain->first, struct batadv_frag_list_entry, list); hlist_del(&entry->list); skb_out = entry->skb; kfree(entry); /* Make room for the rest of the fragments. */ if (pskb_expand_head(skb_out, 0, size - skb->len, GFP_ATOMIC) < 0) { kfree_skb(skb_out); skb_out = NULL; goto free; } /* Move the existing MAC header to just before the payload. (Override * the fragment header.) */ skb_pull_rcsum(skb_out, hdr_size); memmove(skb_out->data - ETH_HLEN, skb_mac_header(skb_out), ETH_HLEN); skb_set_mac_header(skb_out, -ETH_HLEN); skb_reset_network_header(skb_out); skb_reset_transport_header(skb_out); /* Copy the payload of the each fragment into the last skb */ hlist_for_each_entry(entry, chain, list) { size = entry->skb->len - hdr_size; memcpy(skb_put(skb_out, size), entry->skb->data + hdr_size, size); } free: /* Locking is not needed, because 'chain' is not part of any orig. */ batadv_frag_clear_chain(chain); return skb_out; } Commit Message: batman-adv: Calculate extra tail size based on queued fragments The fragmentation code was replaced in 610bfc6bc99bc83680d190ebc69359a05fc7f605 ("batman-adv: Receive fragmented packets and merge"). The new code provided a mostly unused parameter skb for the merging function. It is used inside the function to calculate the additionally needed skb tailroom. But instead of increasing its own tailroom, it is only increasing the tailroom of the first queued skb. This is not correct in some situations because the first queued entry can be a different one than the parameter. An observed problem was: 1. packet with size 104, total_size 1464, fragno 1 was received - packet is queued 2. packet with size 1400, total_size 1464, fragno 0 was received - packet is queued at the end of the list 3. enough data was received and can be given to the merge function (1464 == (1400 - 20) + (104 - 20)) - merge functions gets 1400 byte large packet as skb argument 4. merge function gets first entry in queue (104 byte) - stored as skb_out 5. merge function calculates the required extra tail as total_size - skb->len - pskb_expand_head tail of skb_out with 64 bytes 6. merge function tries to squeeze the extra 1380 bytes from the second queued skb (1400 byte aka skb parameter) in the 64 extra tail bytes of skb_out Instead calculate the extra required tail bytes for skb_out also using skb_out instead of using the parameter skb. The skb parameter is only used to get the total_size from the last received packet. This is also the total_size used to decide that all fragments were received. Reported-by: Philipp Psurek <[email protected]> Signed-off-by: Sven Eckelmann <[email protected]> Acked-by: Martin Hundebøll <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: status_t BufferQueueConsumer::setDefaultBufferSize(uint32_t width, uint32_t height) { ATRACE_CALL(); if (width == 0 || height == 0) { BQ_LOGV("setDefaultBufferSize: dimensions cannot be 0 (width=%u " "height=%u)", width, height); return BAD_VALUE; } BQ_LOGV("setDefaultBufferSize: width=%u height=%u", width, height); Mutex::Autolock lock(mCore->mMutex); mCore->mDefaultWidth = width; mCore->mDefaultHeight = height; return NO_ERROR; } Commit Message: Add SN logging Bug 27046057 Change-Id: Iede7c92e59e60795df1ec7768ebafd6b090f1c27 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: SYSCALL_DEFINE2(shutdown, int, fd, int, how) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_shutdown(sock, how); if (!err) err = sock->ops->shutdown(sock, how); fput_light(sock->file, fput_needed); } return err; } 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 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 Track::Seek( long long time_ns, const BlockEntry*& pResult) const { const long status = GetFirst(pResult); if (status < 0) //buffer underflow, etc return status; assert(pResult); if (pResult->EOS()) return 0; const Cluster* pCluster = pResult->GetCluster(); assert(pCluster); assert(pCluster->GetIndex() >= 0); if (time_ns <= pResult->GetBlock()->GetTime(pCluster)) return 0; Cluster** const clusters = m_pSegment->m_clusters; assert(clusters); const long count = m_pSegment->GetCount(); //loaded only, not preloaded assert(count > 0); Cluster** const i = clusters + pCluster->GetIndex(); assert(i); assert(*i == pCluster); assert(pCluster->GetTime() <= time_ns); Cluster** const j = clusters + count; Cluster** lo = i; Cluster** hi = j; while (lo < hi) { Cluster** const mid = lo + (hi - lo) / 2; assert(mid < hi); pCluster = *mid; assert(pCluster); assert(pCluster->GetIndex() >= 0); assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters)); const long long t = pCluster->GetTime(); if (t <= time_ns) lo = mid + 1; else hi = mid; assert(lo <= hi); } assert(lo == hi); assert(lo > i); assert(lo <= j); while (lo > i) { pCluster = *--lo; assert(pCluster); assert(pCluster->GetTime() <= time_ns); pResult = pCluster->GetEntry(this); if ((pResult != 0) && !pResult->EOS()) return 0; } pResult = GetEOS(); //weird return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: static int user_reset_fdc(int drive, int arg, bool interruptible) { int ret; if (lock_fdc(drive, interruptible)) return -EINTR; if (arg == FD_RESET_ALWAYS) FDCS->reset = 1; if (FDCS->reset) { cont = &reset_cont; ret = wait_til_done(reset_fdc, interruptible); if (ret == -EINTR) return -EINTR; } process_fd_request(); return 0; } Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output Do not leak kernel-only floppy_raw_cmd structure members to userspace. This includes the linked-list pointer and the pointer to the allocated DMA space. Signed-off-by: Matthew Daley <[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: static void show_object(struct object *object, struct strbuf *path, const char *last, void *data) { struct bitmap *base = data; int bitmap_pos; bitmap_pos = bitmap_position(object->oid.hash); if (bitmap_pos < 0) { char *name = path_name(path, last); bitmap_pos = ext_index_add_object(object, name); free(name); } bitmap_set(base, bitmap_pos); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[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: OMX_ERRORTYPE SoftOpus::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch ((int)index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.opus", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAndroidOpus: { const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams = (const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params; if (opusParams->nPortIndex != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Target: 1 Example 2: Code: bool smb1cli_conn_server_writebraw(struct smbXcli_conn *conn) { return conn->smb1.server.writebraw; } 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: void ssl_set_client_disabled(SSL *s) { CERT *c = s->cert; c->mask_a = 0; c->mask_k = 0; /* Don't allow TLS 1.2 only ciphers if we don't suppport them */ if (!SSL_CLIENT_USE_TLS1_2_CIPHERS(s)) c->mask_ssl = SSL_TLSV1_2; else c->mask_ssl = 0; ssl_set_sig_mask(&c->mask_a, s, SSL_SECOP_SIGALG_MASK); /* Disable static DH if we don't include any appropriate * signature algorithms. */ if (c->mask_a & SSL_aRSA) c->mask_k |= SSL_kDHr|SSL_kECDHr; if (c->mask_a & SSL_aDSS) c->mask_k |= SSL_kDHd; if (c->mask_a & SSL_aECDSA) c->mask_k |= SSL_kECDHe; #ifndef OPENSSL_NO_KRB5 if (!kssl_tgt_is_available(s->kssl_ctx)) { c->mask_a |= SSL_aKRB5; c->mask_k |= SSL_kKRB5; } #endif #ifndef OPENSSL_NO_PSK /* with PSK there must be client callback set */ if (!s->psk_client_callback) { c->mask_a |= SSL_aPSK; c->mask_k |= SSL_kPSK; } #endif /* OPENSSL_NO_PSK */ c->valid = 1; } 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: bool AffiliationFetcher::ParseResponse( AffiliationFetcherDelegate::Result* result) const { std::string serialized_response; if (!fetcher_->GetResponseAsString(&serialized_response)) { NOTREACHED(); } affiliation_pb::LookupAffiliationResponse response; if (!response.ParseFromString(serialized_response)) return false; result->reserve(requested_facet_uris_.size()); std::map<FacetURI, size_t> facet_uri_to_class_index; for (int i = 0; i < response.affiliation_size(); ++i) { const affiliation_pb::Affiliation& equivalence_class( response.affiliation(i)); AffiliatedFacets affiliated_uris; for (int j = 0; j < equivalence_class.facet_size(); ++j) { const std::string& uri_spec(equivalence_class.facet(j)); FacetURI uri = FacetURI::FromPotentiallyInvalidSpec(uri_spec); if (!uri.is_valid()) continue; affiliated_uris.push_back(uri); } if (affiliated_uris.empty()) continue; for (const FacetURI& uri : affiliated_uris) { if (!facet_uri_to_class_index.count(uri)) facet_uri_to_class_index[uri] = result->size(); if (facet_uri_to_class_index[uri] != facet_uri_to_class_index[affiliated_uris[0]]) { return false; } } if (facet_uri_to_class_index[affiliated_uris[0]] == result->size()) result->push_back(affiliated_uris); } for (const FacetURI& uri : requested_facet_uris_) { if (!facet_uri_to_class_index.count(uri)) result->push_back(AffiliatedFacets(1, uri)); } return true; } Commit Message: Update AffiliationFetcher to use new Affiliation API wire format. The new format is not backward compatible with the old one, therefore this CL updates the client side protobuf definitions to be in line with the API definition. However, this CL does not yet make use of any additional fields introduced in the new wire format. BUG=437865 Review URL: https://codereview.chromium.org/996613002 Cr-Commit-Position: refs/heads/master@{#319860} CWE ID: CWE-119 Target: 1 Example 2: Code: void Type_Measurement_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } Commit Message: Added an extra check to MLU bounds Thanks to Ibrahim el-sayed for spotting the bug 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 SyncManager::ReceivedExperiment(browser_sync::Experiments* experiments) const { ReadTransaction trans(FROM_HERE, GetUserShare()); ReadNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { DVLOG(1) << "Couldn't find Nigori node."; return false; } bool found_experiment = false; if (node.GetNigoriSpecifics().sync_tabs()) { experiments->sync_tabs = true; found_experiment = true; } if (node.GetNigoriSpecifics().sync_tab_favicons()) { experiments->sync_tab_favicons = true; found_experiment = true; } return found_experiment; } 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:
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: ppp_unregister_channel(struct ppp_channel *chan) { struct channel *pch = chan->ppp; struct ppp_net *pn; if (!pch) return; /* should never happen */ chan->ppp = NULL; /* * This ensures that we have returned from any calls into the * the channel's start_xmit or ioctl routine before we proceed. */ down_write(&pch->chan_sem); spin_lock_bh(&pch->downl); pch->chan = NULL; spin_unlock_bh(&pch->downl); up_write(&pch->chan_sem); ppp_disconnect_channel(pch); pn = ppp_pernet(pch->chan_net); spin_lock_bh(&pn->all_channels_lock); list_del(&pch->list); spin_unlock_bh(&pn->all_channels_lock); pch->file.dead = 1; wake_up_interruptible(&pch->file.rwait); if (atomic_dec_and_test(&pch->file.refcnt)) ppp_destroy_channel(pch); } Commit Message: ppp: take reference on channels netns Let channels hold a reference on their network namespace. Some channel types, like ppp_async and ppp_synctty, can have their userspace controller running in a different namespace. Therefore they can't rely on them to preclude their netns from being removed from under them. ================================================================== BUG: KASAN: use-after-free in ppp_unregister_channel+0x372/0x3a0 at addr ffff880064e217e0 Read of size 8 by task syz-executor/11581 ============================================================================= BUG net_namespace (Not tainted): kasan: bad access detected ----------------------------------------------------------------------------- Disabling lock debugging due to kernel taint INFO: Allocated in copy_net_ns+0x6b/0x1a0 age=92569 cpu=3 pid=6906 [< none >] ___slab_alloc+0x4c7/0x500 kernel/mm/slub.c:2440 [< none >] __slab_alloc+0x4c/0x90 kernel/mm/slub.c:2469 [< inline >] slab_alloc_node kernel/mm/slub.c:2532 [< inline >] slab_alloc kernel/mm/slub.c:2574 [< none >] kmem_cache_alloc+0x23a/0x2b0 kernel/mm/slub.c:2579 [< inline >] kmem_cache_zalloc kernel/include/linux/slab.h:597 [< inline >] net_alloc kernel/net/core/net_namespace.c:325 [< none >] copy_net_ns+0x6b/0x1a0 kernel/net/core/net_namespace.c:360 [< none >] create_new_namespaces+0x2f6/0x610 kernel/kernel/nsproxy.c:95 [< none >] copy_namespaces+0x297/0x320 kernel/kernel/nsproxy.c:150 [< none >] copy_process.part.35+0x1bf4/0x5760 kernel/kernel/fork.c:1451 [< inline >] copy_process kernel/kernel/fork.c:1274 [< none >] _do_fork+0x1bc/0xcb0 kernel/kernel/fork.c:1723 [< inline >] SYSC_clone kernel/kernel/fork.c:1832 [< none >] SyS_clone+0x37/0x50 kernel/kernel/fork.c:1826 [< none >] entry_SYSCALL_64_fastpath+0x16/0x7a kernel/arch/x86/entry/entry_64.S:185 INFO: Freed in net_drop_ns+0x67/0x80 age=575 cpu=2 pid=2631 [< none >] __slab_free+0x1fc/0x320 kernel/mm/slub.c:2650 [< inline >] slab_free kernel/mm/slub.c:2805 [< none >] kmem_cache_free+0x2a0/0x330 kernel/mm/slub.c:2814 [< inline >] net_free kernel/net/core/net_namespace.c:341 [< none >] net_drop_ns+0x67/0x80 kernel/net/core/net_namespace.c:348 [< none >] cleanup_net+0x4e5/0x600 kernel/net/core/net_namespace.c:448 [< none >] process_one_work+0x794/0x1440 kernel/kernel/workqueue.c:2036 [< none >] worker_thread+0xdb/0xfc0 kernel/kernel/workqueue.c:2170 [< none >] kthread+0x23f/0x2d0 kernel/drivers/block/aoe/aoecmd.c:1303 [< none >] ret_from_fork+0x3f/0x70 kernel/arch/x86/entry/entry_64.S:468 INFO: Slab 0xffffea0001938800 objects=3 used=0 fp=0xffff880064e20000 flags=0x5fffc0000004080 INFO: Object 0xffff880064e20000 @offset=0 fp=0xffff880064e24200 CPU: 1 PID: 11581 Comm: syz-executor Tainted: G B 4.4.0+ Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014 00000000ffffffff ffff8800662c7790 ffffffff8292049d ffff88003e36a300 ffff880064e20000 ffff880064e20000 ffff8800662c77c0 ffffffff816f2054 ffff88003e36a300 ffffea0001938800 ffff880064e20000 0000000000000000 Call Trace: [< inline >] __dump_stack kernel/lib/dump_stack.c:15 [<ffffffff8292049d>] dump_stack+0x6f/0xa2 kernel/lib/dump_stack.c:50 [<ffffffff816f2054>] print_trailer+0xf4/0x150 kernel/mm/slub.c:654 [<ffffffff816f875f>] object_err+0x2f/0x40 kernel/mm/slub.c:661 [< inline >] print_address_description kernel/mm/kasan/report.c:138 [<ffffffff816fb0c5>] kasan_report_error+0x215/0x530 kernel/mm/kasan/report.c:236 [< inline >] kasan_report kernel/mm/kasan/report.c:259 [<ffffffff816fb4de>] __asan_report_load8_noabort+0x3e/0x40 kernel/mm/kasan/report.c:280 [< inline >] ? ppp_pernet kernel/include/linux/compiler.h:218 [<ffffffff83ad71b2>] ? ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392 [< inline >] ppp_pernet kernel/include/linux/compiler.h:218 [<ffffffff83ad71b2>] ppp_unregister_channel+0x372/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392 [< inline >] ? ppp_pernet kernel/drivers/net/ppp/ppp_generic.c:293 [<ffffffff83ad6f26>] ? ppp_unregister_channel+0xe6/0x3a0 kernel/drivers/net/ppp/ppp_generic.c:2392 [<ffffffff83ae18f3>] ppp_asynctty_close+0xa3/0x130 kernel/drivers/net/ppp/ppp_async.c:241 [<ffffffff83ae1850>] ? async_lcp_peek+0x5b0/0x5b0 kernel/drivers/net/ppp/ppp_async.c:1000 [<ffffffff82c33239>] tty_ldisc_close.isra.1+0x99/0xe0 kernel/drivers/tty/tty_ldisc.c:478 [<ffffffff82c332c0>] tty_ldisc_kill+0x40/0x170 kernel/drivers/tty/tty_ldisc.c:744 [<ffffffff82c34943>] tty_ldisc_release+0x1b3/0x260 kernel/drivers/tty/tty_ldisc.c:772 [<ffffffff82c1ef21>] tty_release+0xac1/0x13e0 kernel/drivers/tty/tty_io.c:1901 [<ffffffff82c1e460>] ? release_tty+0x320/0x320 kernel/drivers/tty/tty_io.c:1688 [<ffffffff8174de36>] __fput+0x236/0x780 kernel/fs/file_table.c:208 [<ffffffff8174e405>] ____fput+0x15/0x20 kernel/fs/file_table.c:244 [<ffffffff813595ab>] task_work_run+0x16b/0x200 kernel/kernel/task_work.c:115 [< inline >] exit_task_work kernel/include/linux/task_work.h:21 [<ffffffff81307105>] do_exit+0x8b5/0x2c60 kernel/kernel/exit.c:750 [<ffffffff813fdd20>] ? debug_check_no_locks_freed+0x290/0x290 kernel/kernel/locking/lockdep.c:4123 [<ffffffff81306850>] ? mm_update_next_owner+0x6f0/0x6f0 kernel/kernel/exit.c:357 [<ffffffff813215e6>] ? __dequeue_signal+0x136/0x470 kernel/kernel/signal.c:550 [<ffffffff8132067b>] ? recalc_sigpending_tsk+0x13b/0x180 kernel/kernel/signal.c:145 [<ffffffff81309628>] do_group_exit+0x108/0x330 kernel/kernel/exit.c:880 [<ffffffff8132b9d4>] get_signal+0x5e4/0x14f0 kernel/kernel/signal.c:2307 [< inline >] ? kretprobe_table_lock kernel/kernel/kprobes.c:1113 [<ffffffff8151d355>] ? kprobe_flush_task+0xb5/0x450 kernel/kernel/kprobes.c:1158 [<ffffffff8115f7d3>] do_signal+0x83/0x1c90 kernel/arch/x86/kernel/signal.c:712 [<ffffffff8151d2a0>] ? recycle_rp_inst+0x310/0x310 kernel/include/linux/list.h:655 [<ffffffff8115f750>] ? setup_sigcontext+0x780/0x780 kernel/arch/x86/kernel/signal.c:165 [<ffffffff81380864>] ? finish_task_switch+0x424/0x5f0 kernel/kernel/sched/core.c:2692 [< inline >] ? finish_lock_switch kernel/kernel/sched/sched.h:1099 [<ffffffff81380560>] ? finish_task_switch+0x120/0x5f0 kernel/kernel/sched/core.c:2678 [< inline >] ? context_switch kernel/kernel/sched/core.c:2807 [<ffffffff85d794e9>] ? __schedule+0x919/0x1bd0 kernel/kernel/sched/core.c:3283 [<ffffffff81003901>] exit_to_usermode_loop+0xf1/0x1a0 kernel/arch/x86/entry/common.c:247 [< inline >] prepare_exit_to_usermode kernel/arch/x86/entry/common.c:282 [<ffffffff810062ef>] syscall_return_slowpath+0x19f/0x210 kernel/arch/x86/entry/common.c:344 [<ffffffff85d88022>] int_ret_from_sys_call+0x25/0x9f kernel/arch/x86/entry/entry_64.S:281 Memory state around the buggy address: ffff880064e21680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff880064e21700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb >ffff880064e21780: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff880064e21800: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff880064e21880: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ================================================================== Fixes: 273ec51dd7ce ("net: ppp_generic - introduce net-namespace functionality v2") Reported-by: Baozeng Ding <[email protected]> Signed-off-by: Guillaume Nault <[email protected]> Reviewed-by: Cyrill Gorcunov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: static int write_end_fn(handle_t *handle, struct buffer_head *bh) { int ret; if (!buffer_mapped(bh) || buffer_freed(bh)) return 0; set_buffer_uptodate(bh); ret = ext4_handle_dirty_metadata(handle, NULL, bh); clear_buffer_meta(bh); clear_buffer_prio(bh); return ret; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[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: void ResourcePrefetchPredictor::Shutdown() { history_service_observer_.RemoveAll(); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} 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: PersistentHistogramAllocator::GetCreateHistogramResultHistogram() { constexpr subtle::AtomicWord kHistogramUnderConstruction = 1; static subtle::AtomicWord atomic_histogram_pointer = 0; subtle::AtomicWord histogram_value = subtle::Acquire_Load(&atomic_histogram_pointer); if (histogram_value == kHistogramUnderConstruction) return nullptr; if (histogram_value) return reinterpret_cast<HistogramBase*>(histogram_value); if (subtle::NoBarrier_CompareAndSwap(&atomic_histogram_pointer, 0, kHistogramUnderConstruction) != 0) { return nullptr; } if (GlobalHistogramAllocator::Get()) { DVLOG(1) << "Creating the results-histogram inside persistent" << " memory can cause future allocations to crash if" << " that memory is ever released (for testing)."; } HistogramBase* histogram_pointer = LinearHistogram::FactoryGet( kResultHistogram, 1, CREATE_HISTOGRAM_MAX, CREATE_HISTOGRAM_MAX + 1, HistogramBase::kUmaTargetedHistogramFlag); subtle::Release_Store( &atomic_histogram_pointer, reinterpret_cast<subtle::AtomicWord>(histogram_pointer)); return histogram_pointer; } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264 Target: 1 Example 2: Code: static int oplea(RAsm *a, ut8 *data, const Opcode *op){ int l = 0; int mod = 0; st32 offset = 0; int reg = 0; int rm = 0; if (op->operands[0].type & OT_REGALL && op->operands[1].type & (OT_MEMORY | OT_CONSTANT)) { if (a->bits == 64) { data[l++] = 0x48; } data[l++] = 0x8d; if (op->operands[1].regs[0] == X86R_UNDEFINED) { int high = 0xff00 & op->operands[1].offset; data[l++] = op->operands[0].reg << 3 | 5; data[l++] = op->operands[1].offset; data[l++] = high >> 8; data[l++] = op->operands[1].offset >> 16; data[l++] = op->operands[1].offset >> 24; return l; } else { reg = op->operands[0].reg; rm = op->operands[1].regs[0]; offset = op->operands[1].offset * op->operands[1].offset_sign; if (offset != 0 || op->operands[1].regs[0] == X86R_EBP) { mod = 1; if (offset >= 128 || offset < -128) { mod = 2; } data[l++] = mod << 6 | reg << 3 | rm; if (op->operands[1].regs[0] == X86R_ESP) { data[l++] = 0x24; } data[l++] = offset; if (mod == 2) { data[l++] = offset >> 8; data[l++] = offset >> 16; data[l++] = offset >> 24; } } else { data[l++] = op->operands[0].reg << 3 | op->operands[1].regs[0]; if (op->operands[1].regs[0] == X86R_ESP) { data[l++] = 0x24; } } } } return l; } Commit Message: Fix #12372 and #12373 - Crash in x86 assembler (#12380) 0 ,0,[bP-bL-bP-bL-bL-r-bL-bP-bL-bL- mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx-- leA ,0,[bP-bL-bL-bP-bL-bP-bL-60@bL- leA ,0,[bP-bL-r-bP-bL-bP-bL-60@bL- mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx-- 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: AudioOutputAuthorizationHandler::AudioOutputAuthorizationHandler( media::AudioManager* audio_manager, MediaStreamManager* media_stream_manager, int render_process_id, const std::string& salt) : audio_manager_(audio_manager), media_stream_manager_(media_stream_manager), permission_checker_(base::MakeUnique<MediaDevicesPermissionChecker>()), render_process_id_(render_process_id), salt_(salt), weak_factory_(this) { DCHECK(media_stream_manager_); } Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one. BUG=672468 CQ_INCLUDE_TRYBOTS=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 Review-Url: https://codereview.chromium.org/2692203003 Cr-Commit-Position: refs/heads/master@{#450939} 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 size_t safecat(char *buffer, size_t bufsize, size_t pos, PNG_CONST char *cat) { while (pos < bufsize && cat != NULL && *cat != 0) buffer[pos++] = *cat++; if (pos >= bufsize) pos = bufsize-1; buffer[pos] = 0; 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: exim_usage(uschar *progname) { /* Handle specific program invocation variants */ if (Ustrcmp(progname, US"-mailq") == 0) { fprintf(stderr, "mailq - list the contents of the mail queue\n\n" "For a list of options, see the Exim documentation.\n"); exit(EXIT_FAILURE); } /* Generic usage - we output this whatever happens */ fprintf(stderr, "Exim is a Mail Transfer Agent. It is normally called by Mail User Agents,\n" "not directly from a shell command line. Options and/or arguments control\n" "what it does when called. For a list of options, see the Exim documentation.\n"); exit(EXIT_FAILURE); } Commit Message: Cleanup (prevent repeated use of -p/-oMr to avoid mem leak) 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: static int ssl_write_new_session_ticket( mbedtls_ssl_context *ssl ) { int ret; size_t tlen; uint32_t lifetime; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write new session ticket" ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_NEW_SESSION_TICKET; /* * struct { * uint32 ticket_lifetime_hint; * opaque ticket<0..2^16-1>; * } NewSessionTicket; * * 4 . 7 ticket_lifetime_hint (0 = unspecified) * 8 . 9 ticket_len (n) * 10 . 9+n ticket content */ if( ( ret = ssl->conf->f_ticket_write( ssl->conf->p_ticket, ssl->session_negotiate, ssl->out_msg + 10, ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN, &tlen, &lifetime ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_write", ret ); tlen = 0; } ssl->out_msg[4] = ( lifetime >> 24 ) & 0xFF; ssl->out_msg[5] = ( lifetime >> 16 ) & 0xFF; ssl->out_msg[6] = ( lifetime >> 8 ) & 0xFF; ssl->out_msg[7] = ( lifetime ) & 0xFF; ssl->out_msg[8] = (unsigned char)( ( tlen >> 8 ) & 0xFF ); ssl->out_msg[9] = (unsigned char)( ( tlen ) & 0xFF ); ssl->out_msglen = 10 + tlen; /* * Morally equivalent to updating ssl->state, but NewSessionTicket and * ChangeCipherSpec share the same state. */ ssl->handshake->new_session_ticket = 0; if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write new session ticket" ) ); return( 0 ); } Commit Message: Prevent bounds check bypass through overflow in PSK identity parsing The check `if( *p + n > end )` in `ssl_parse_client_psk_identity` is unsafe because `*p + n` might overflow, thus bypassing the check. As `n` is a user-specified value up to 65K, this is relevant if the library happens to be located in the last 65K of virtual memory. This commit replaces the check by a safe version. CWE ID: CWE-190 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 ext4_writepage(struct page *page, struct writeback_control *wbc) { int ret = 0; loff_t size; unsigned int len; struct buffer_head *page_bufs; struct inode *inode = page->mapping->host; trace_ext4_writepage(inode, page); size = i_size_read(inode); if (page->index == size >> PAGE_CACHE_SHIFT) len = size & ~PAGE_CACHE_MASK; else len = PAGE_CACHE_SIZE; if (page_has_buffers(page)) { page_bufs = page_buffers(page); if (walk_page_buffers(NULL, page_bufs, 0, len, NULL, ext4_bh_delay_or_unwritten)) { /* * We don't want to do block allocation * So redirty the page and return * We may reach here when we do a journal commit * via journal_submit_inode_data_buffers. * If we don't have mapping block we just ignore * them. We can also reach here via shrink_page_list */ redirty_page_for_writepage(wbc, page); unlock_page(page); return 0; } } else { /* * The test for page_has_buffers() is subtle: * We know the page is dirty but it lost buffers. That means * that at some moment in time after write_begin()/write_end() * has been called all buffers have been clean and thus they * must have been written at least once. So they are all * mapped and we can happily proceed with mapping them * and writing the page. * * Try to initialize the buffer_heads and check whether * all are mapped and non delay. We don't want to * do block allocation here. */ ret = block_prepare_write(page, 0, len, noalloc_get_block_write); if (!ret) { page_bufs = page_buffers(page); /* check whether all are mapped and non delay */ if (walk_page_buffers(NULL, page_bufs, 0, len, NULL, ext4_bh_delay_or_unwritten)) { redirty_page_for_writepage(wbc, page); unlock_page(page); return 0; } } else { /* * We can't do block allocation here * so just redity the page and unlock * and return */ redirty_page_for_writepage(wbc, page); unlock_page(page); return 0; } /* now mark the buffer_heads as dirty and uptodate */ block_commit_write(page, 0, len); } if (PageChecked(page) && ext4_should_journal_data(inode)) { /* * It's mmapped pagecache. Add buffers and journal it. There * doesn't seem much point in redirtying the page here. */ ClearPageChecked(page); return __ext4_journalled_writepage(page, len); } if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode)) ret = nobh_writepage(page, noalloc_get_block_write, wbc); else ret = block_write_full_page(page, noalloc_get_block_write, wbc); return ret; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Target: 1 Example 2: Code: static int vti_vcpu_setup(struct kvm_vcpu *vcpu, int id) { unsigned long psr; int r; local_irq_save(psr); r = kvm_insert_vmm_mapping(vcpu); local_irq_restore(psr); if (r) goto fail; r = kvm_vcpu_init(vcpu, vcpu->kvm, id); if (r) goto fail; r = vti_init_vpd(vcpu); if (r) { printk(KERN_DEBUG"kvm: vpd init error!!\n"); goto uninit; } r = vti_create_vp(vcpu); if (r) goto uninit; kvm_purge_vmm_mapping(vcpu); return 0; uninit: kvm_vcpu_uninit(vcpu); fail: return r; } Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings (cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e) If some vcpus are created before KVM_CREATE_IRQCHIP, then irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading to potential NULL pointer dereferences. Fix by: - ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called - ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP This is somewhat long winded because vcpu->arch.apic is created without kvm->lock held. Based on earlier patch by Michael Ellerman. Signed-off-by: Michael Ellerman <[email protected]> Signed-off-by: Avi Kivity <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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: static void btif_fetch_local_bdaddr(bt_bdaddr_t *local_addr) { char val[PROPERTY_VALUE_MAX] = {0}; uint8_t valid_bda = FALSE; int val_size = 0; const uint8_t null_bdaddr[BD_ADDR_LEN] = {0,0,0,0,0,0}; /* Get local bdaddr storage path from property */ if (property_get(PROPERTY_BT_BDADDR_PATH, val, NULL)) { int addr_fd; BTIF_TRACE_DEBUG("%s, local bdaddr is stored in %s", __func__, val); if ((addr_fd = open(val, O_RDONLY)) != -1) { memset(val, 0, sizeof(val)); read(addr_fd, val, FACTORY_BT_BDADDR_STORAGE_LEN); /* If this is not a reserved/special bda, then use it */ if ((string_to_bdaddr(val, local_addr)) && (memcmp(local_addr->address, null_bdaddr, BD_ADDR_LEN) != 0)) { valid_bda = TRUE; BTIF_TRACE_DEBUG("%s: Got Factory BDA %s", __func__, val); } close(addr_fd); } } if(!valid_bda) { val_size = sizeof(val); if(btif_config_get_str("Adapter", "Address", val, &val_size)) { string_to_bdaddr(val, local_addr); BTIF_TRACE_DEBUG("local bdaddr from bt_config.xml is %s", val); return; } } /* No factory BDADDR found. Look for previously generated random BDA */ if (!valid_bda) { valid_bda = btif_fetch_property(PERSIST_BDADDR_PROPERTY, local_addr); } /* No BDADDR found in file. Look for BDA in factory property */ if (!valid_bda) { valid_bda = btif_fetch_property(FACTORY_BT_ADDR_PROPERTY, local_addr); } /* Generate new BDA if necessary */ if (!valid_bda) { bdstr_t bdstr; /* Seed the random number generator */ srand((unsigned int) (time(0))); /* No autogen BDA. Generate one now. */ local_addr->address[0] = 0x22; local_addr->address[1] = 0x22; local_addr->address[2] = (uint8_t) ((rand() >> 8) & 0xFF); local_addr->address[3] = (uint8_t) ((rand() >> 8) & 0xFF); local_addr->address[4] = (uint8_t) ((rand() >> 8) & 0xFF); local_addr->address[5] = (uint8_t) ((rand() >> 8) & 0xFF); /* Convert to ascii, and store as a persistent property */ bdaddr_to_string(local_addr, bdstr, sizeof(bdstr)); BTIF_TRACE_DEBUG("No preset BDA. Generating BDA: %s for prop %s", (char*)bdstr, PERSIST_BDADDR_PROPERTY); if (property_set(PERSIST_BDADDR_PROPERTY, (char*)bdstr) < 0) BTIF_TRACE_ERROR("Failed to set random BDA in prop %s",PERSIST_BDADDR_PROPERTY); } bdstr_t bdstr; bdaddr_to_string(local_addr, bdstr, sizeof(bdstr)); val_size = sizeof(val); if (btif_config_get_str("Adapter", "Address", val, &val_size)) { if (strcmp(bdstr, val) ==0) { return; } } btif_config_set_str("Adapter", "Address", bdstr); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 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 WallpaperManager::OnWallpaperDecoded( const AccountId& account_id, const wallpaper::WallpaperInfo& info, bool update_wallpaper, MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage> user_image) { DCHECK_CURRENTLY_ON(BrowserThread::UI); TRACE_EVENT_ASYNC_END0("ui", "LoadAndDecodeWallpaper", this); if (user_image->image().isNull()) { wallpaper::WallpaperInfo default_info( "", wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED, wallpaper::DEFAULT, base::Time::Now().LocalMidnight()); SetUserWallpaperInfo(account_id, default_info, true); if (update_wallpaper) DoSetDefaultWallpaper(account_id, std::move(on_finish)); return; } wallpaper_cache_[account_id].second = user_image->image(); if (update_wallpaper) SetWallpaper(user_image->image(), info); } Commit Message: [reland] Do not set default wallpaper unless it should do so. [email protected], [email protected] Bug: 751382 Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda Reviewed-on: https://chromium-review.googlesource.com/619754 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Alexander Alekseev <[email protected]> Reviewed-by: Biao She <[email protected]> Cr-Original-Commit-Position: refs/heads/master@{#498325} Reviewed-on: https://chromium-review.googlesource.com/646430 Cr-Commit-Position: refs/heads/master@{#498982} CWE ID: CWE-200 Target: 1 Example 2: Code: BnMemoryHeap::BnMemoryHeap() { } Commit Message: Sanity check IMemory access versus underlying mmap Bug 26877992 Change-Id: Ibbf4b1061e4675e4e96bc944a865b53eaf6984fe 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: static void send_monitor_event(struct sk_buff *skb) { struct sock *sk; BT_DBG("len %d", skb->len); read_lock(&hci_sk_list.lock); sk_for_each(sk, &hci_sk_list.head) { struct sk_buff *nskb; if (sk->sk_state != BT_BOUND) continue; if (hci_pi(sk)->channel != HCI_CHANNEL_MONITOR) continue; nskb = skb_clone(skb, GFP_ATOMIC); if (!nskb) continue; if (sock_queue_rcv_skb(sk, nskb)) kfree_skb(nskb); } read_unlock(&hci_sk_list.lock); } 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 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 inode_init_owner(struct inode *inode, const struct inode *dir, umode_t mode) { inode->i_uid = current_fsuid(); if (dir && dir->i_mode & S_ISGID) { inode->i_gid = dir->i_gid; if (S_ISDIR(mode)) mode |= S_ISGID; } else inode->i_gid = current_fsgid(); inode->i_mode = mode; } Commit Message: Fix up non-directory creation in SGID directories sgid directories have special semantics, making newly created files in the directory belong to the group of the directory, and newly created subdirectories will also become sgid. This is historically used for group-shared directories. But group directories writable by non-group members should not imply that such non-group members can magically join the group, so make sure to clear the sgid bit on non-directories for non-members (but remember that sgid without group execute means "mandatory locking", just to confuse things even more). Reported-by: Jann Horn <[email protected]> Cc: Andy Lutomirski <[email protected]> Cc: Al Viro <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-269 Target: 1 Example 2: Code: static int ecryptfs_process_flags(struct ecryptfs_crypt_stat *crypt_stat, char *page_virt, int *bytes_read) { int rc = 0; int i; u32 flags; flags = get_unaligned_be32(page_virt); for (i = 0; i < ((sizeof(ecryptfs_flag_map) / sizeof(struct ecryptfs_flag_map_elem))); i++) if (flags & ecryptfs_flag_map[i].file_flag) { crypt_stat->flags |= ecryptfs_flag_map[i].local_flag; } else crypt_stat->flags &= ~(ecryptfs_flag_map[i].local_flag); /* Version is in top 8 bits of the 32-bit flag vector */ crypt_stat->file_version = ((flags >> 24) & 0xFF); (*bytes_read) = 4; return rc; } Commit Message: eCryptfs: Remove buggy and unnecessary write in file name decode routine Dmitry Chernenkov used KASAN to discover that eCryptfs writes past the end of the allocated buffer during encrypted filename decoding. This fix corrects the issue by getting rid of the unnecessary 0 write when the current bit offset is 2. Signed-off-by: Michael Halcrow <[email protected]> Reported-by: Dmitry Chernenkov <[email protected]> Suggested-by: Kees Cook <[email protected]> Cc: [email protected] # v2.6.29+: 51ca58d eCryptfs: Filename Encryption: Encoding and encryption functions Signed-off-by: Tyler Hicks <[email protected]> CWE ID: CWE-189 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: PageInfoUI::GetSecurityDescription(const IdentityInfo& identity_info) const { std::unique_ptr<PageInfoUI::SecurityDescription> security_description( new PageInfoUI::SecurityDescription()); switch (identity_info.safe_browsing_status) { case PageInfo::SAFE_BROWSING_STATUS_NONE: break; case PageInfo::SAFE_BROWSING_STATUS_MALWARE: return CreateSecurityDescription(SecuritySummaryColor::RED, IDS_PAGE_INFO_MALWARE_SUMMARY, IDS_PAGE_INFO_MALWARE_DETAILS); case PageInfo::SAFE_BROWSING_STATUS_SOCIAL_ENGINEERING: return CreateSecurityDescription( SecuritySummaryColor::RED, IDS_PAGE_INFO_SOCIAL_ENGINEERING_SUMMARY, IDS_PAGE_INFO_SOCIAL_ENGINEERING_DETAILS); case PageInfo::SAFE_BROWSING_STATUS_UNWANTED_SOFTWARE: return CreateSecurityDescription(SecuritySummaryColor::RED, IDS_PAGE_INFO_UNWANTED_SOFTWARE_SUMMARY, IDS_PAGE_INFO_UNWANTED_SOFTWARE_DETAILS); case PageInfo::SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE: #if defined(FULL_SAFE_BROWSING) return CreateSecurityDescriptionForPasswordReuse( /*is_enterprise_password=*/false); #endif NOTREACHED(); break; case PageInfo::SAFE_BROWSING_STATUS_ENTERPRISE_PASSWORD_REUSE: #if defined(FULL_SAFE_BROWSING) return CreateSecurityDescriptionForPasswordReuse( /*is_enterprise_password=*/true); #endif NOTREACHED(); break; case PageInfo::SAFE_BROWSING_STATUS_BILLING: return CreateSecurityDescription(SecuritySummaryColor::RED, IDS_PAGE_INFO_BILLING_SUMMARY, IDS_PAGE_INFO_BILLING_DETAILS); } switch (identity_info.identity_status) { case PageInfo::SITE_IDENTITY_STATUS_INTERNAL_PAGE: #if defined(OS_ANDROID) return CreateSecurityDescription(SecuritySummaryColor::GREEN, IDS_PAGE_INFO_INTERNAL_PAGE, IDS_PAGE_INFO_INTERNAL_PAGE); #else NOTREACHED(); FALLTHROUGH; #endif case PageInfo::SITE_IDENTITY_STATUS_EV_CERT: FALLTHROUGH; case PageInfo::SITE_IDENTITY_STATUS_CERT: FALLTHROUGH; case PageInfo::SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN: FALLTHROUGH; case PageInfo::SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT: switch (identity_info.connection_status) { case PageInfo::SITE_CONNECTION_STATUS_INSECURE_ACTIVE_SUBRESOURCE: return CreateSecurityDescription(SecuritySummaryColor::RED, IDS_PAGE_INFO_NOT_SECURE_SUMMARY, IDS_PAGE_INFO_NOT_SECURE_DETAILS); case PageInfo::SITE_CONNECTION_STATUS_INSECURE_FORM_ACTION: return CreateSecurityDescription(SecuritySummaryColor::RED, IDS_PAGE_INFO_MIXED_CONTENT_SUMMARY, IDS_PAGE_INFO_NOT_SECURE_DETAILS); case PageInfo::SITE_CONNECTION_STATUS_INSECURE_PASSIVE_SUBRESOURCE: return CreateSecurityDescription(SecuritySummaryColor::RED, IDS_PAGE_INFO_MIXED_CONTENT_SUMMARY, IDS_PAGE_INFO_MIXED_CONTENT_DETAILS); default: return CreateSecurityDescription(SecuritySummaryColor::GREEN, IDS_PAGE_INFO_SECURE_SUMMARY, IDS_PAGE_INFO_SECURE_DETAILS); } case PageInfo::SITE_IDENTITY_STATUS_DEPRECATED_SIGNATURE_ALGORITHM: case PageInfo::SITE_IDENTITY_STATUS_UNKNOWN: case PageInfo::SITE_IDENTITY_STATUS_NO_CERT: default: return CreateSecurityDescription(SecuritySummaryColor::RED, IDS_PAGE_INFO_NOT_SECURE_SUMMARY, IDS_PAGE_INFO_NOT_SECURE_DETAILS); } } 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 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 timer_enter_running(Timer *t) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; int r; assert(t); /* Don't start job if we are supposed to go down */ if (unit_stop_pending(UNIT(t))) return; r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)), JOB_REPLACE, true, &error, NULL); if (r < 0) goto fail; dual_timestamp_get(&t->last_trigger); if (t->stamp_path) touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, 0); timer_set_state(t, TIMER_RUNNING); return; fail: log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r)); timer_enter_dead(t, TIMER_FAILURE_RESOURCES); } Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere CWE ID: CWE-264 Target: 1 Example 2: Code: void SyncTest::EnableNotifications() { EnableNotificationsImpl(); notifications_enabled_ = true; } 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 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: header_put_le_short (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; } ; } /* header_put_le_short */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119 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 NormalPageArena::expandObject(HeapObjectHeader* header, size_t newSize) { ASSERT(header->checkHeader()); if (header->payloadSize() >= newSize) return true; size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize); ASSERT(allocationSize > header->size()); size_t expandSize = allocationSize - header->size(); if (isObjectAllocatedAtAllocationPoint(header) && expandSize <= m_remainingAllocationSize) { m_currentAllocationPoint += expandSize; ASSERT(m_remainingAllocationSize >= expandSize); setRemainingAllocationSize(m_remainingAllocationSize - expandSize); SET_MEMORY_ACCESSIBLE(header->payloadEnd(), expandSize); header->setSize(allocationSize); ASSERT(findPageFromAddress(header->payloadEnd() - 1)); return true; } return false; } 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 Target: 1 Example 2: Code: static int tm_cgpr_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { int ret; if (!cpu_has_feature(CPU_FTR_TM)) return -ENODEV; if (!MSR_TM_ACTIVE(target->thread.regs->msr)) return -ENODATA; flush_tmregs_to_thread(target); flush_fp_to_thread(target); flush_altivec_to_thread(target); ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &target->thread.ckpt_regs, 0, offsetof(struct pt_regs, msr)); if (!ret) { unsigned long msr = get_user_ckpt_msr(target); ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &msr, offsetof(struct pt_regs, msr), offsetof(struct pt_regs, msr) + sizeof(msr)); } BUILD_BUG_ON(offsetof(struct pt_regs, orig_gpr3) != offsetof(struct pt_regs, msr) + sizeof(long)); if (!ret) ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &target->thread.ckpt_regs.orig_gpr3, offsetof(struct pt_regs, orig_gpr3), sizeof(struct pt_regs)); if (!ret) ret = user_regset_copyout_zero(&pos, &count, &kbuf, &ubuf, sizeof(struct pt_regs), -1); return ret; } Commit Message: powerpc/tm: Flush TM only if CPU has TM feature Commit cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump") added code to access TM SPRs in flush_tmregs_to_thread(). However flush_tmregs_to_thread() does not check if TM feature is available on CPU before trying to access TM SPRs in order to copy live state to thread structures. flush_tmregs_to_thread() is indeed guarded by CONFIG_PPC_TRANSACTIONAL_MEM but it might be the case that kernel was compiled with CONFIG_PPC_TRANSACTIONAL_MEM enabled and ran on a CPU without TM feature available, thus rendering the execution of TM instructions that are treated by the CPU as illegal instructions. The fix is just to add proper checking in flush_tmregs_to_thread() if CPU has the TM feature before accessing any TM-specific resource, returning immediately if TM is no available on the CPU. Adding that checking in flush_tmregs_to_thread() instead of in places where it is called, like in vsr_get() and vsr_set(), is better because avoids the same problem cropping up elsewhere. Cc: [email protected] # v4.13+ Fixes: cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump") Signed-off-by: Gustavo Romero <[email protected]> Reviewed-by: Cyril Bur <[email protected]> Signed-off-by: Michael Ellerman <[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 SessionService::RecordUpdatedTabClosed(base::TimeDelta delta, bool use_long_period) { std::string name("SessionRestore.TabClosedPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(name, delta, save_delay_in_millis_, save_delay_in_mins_, 50); if (use_long_period) { std::string long_name_("SessionRestore.TabClosedLongPeriod"); UMA_HISTOGRAM_CUSTOM_TIMES(long_name_, delta, save_delay_in_mins_, save_delay_in_hrs_, 50); } } Commit Message: Metrics for measuring how much overhead reading compressed content states adds. BUG=104293 TEST=NONE Review URL: https://chromiumcodereview.appspot.com/9426039 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@123733 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: pdf_show_image(fz_context *ctx, pdf_run_processor *pr, fz_image *image) { pdf_gstate *gstate = pr->gstate + pr->gtop; fz_matrix image_ctm; fz_rect bbox; softmask_save softmask = { NULL }; if (pr->super.hidden) return; break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); bbox = fz_unit_rect; fz_transform_rect(&bbox, &image_ctm); if (image->mask) { /* apply blend group even though we skip the soft mask */ if (gstate->blendmode) fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1); fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox); } else gstate = pdf_begin_group(ctx, pr, &bbox, &softmask); if (!image->colorspace) { switch (gstate->fill.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_fill_image_mask(ctx, pr->dev, image, &image_ctm, gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params); break; case PDF_MAT_PATTERN: if (gstate->fill.pattern) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params); fz_pop_clip(ctx, pr->dev); } break; } } else { fz_fill_image(ctx, pr->dev, image, &image_ctm, gstate->fill.alpha, &gstate->fill.color_params); } if (image->mask) { fz_pop_clip(ctx, pr->dev); if (gstate->blendmode) fz_end_group(ctx, pr->dev); } else pdf_end_group(ctx, pr, &softmask); } static void if (pr->clip) { gstate->clip_depth++; fz_clip_path(ctx, pr->dev, path, pr->clip_even_odd, &gstate->ctm, &bbox); pr->clip = 0; } if (pr->super.hidden) dostroke = dofill = 0; if (dofill || dostroke) gstate = pdf_begin_group(ctx, pr, &bbox, &softmask); if (dofill && dostroke) { /* We may need to push a knockout group */ if (gstate->stroke.alpha == 0) { /* No need for group, as stroke won't do anything */ } else if (gstate->stroke.alpha == 1.0f && gstate->blendmode == FZ_BLEND_NORMAL) { /* No need for group, as stroke won't show up */ } else { knockout_group = 1; fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 1, FZ_BLEND_NORMAL, 1); } } if (dofill) { switch (gstate->fill.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_fill_path(ctx, pr->dev, path, even_odd, &gstate->ctm, gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params); break; case PDF_MAT_PATTERN: if (gstate->fill.pattern) { fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox); /* The cluster and page 2 of patterns.pdf shows that fz_fill_shade should NOT be called with gstate->ctm. */ fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params); fz_pop_clip(ctx, pr->dev); } break; } } if (dostroke) { switch (gstate->stroke.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, gstate->stroke.colorspace, gstate->stroke.v, gstate->stroke.alpha, &gstate->stroke.color_params); break; case PDF_MAT_PATTERN: if (gstate->stroke.pattern) { fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->stroke.pattern, &pr->gstate[gstate->stroke.gstate_num], &bbox, PDF_STROKE); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->stroke.shade) { fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox); fz_fill_shade(ctx, pr->dev, gstate->stroke.shade, &pr->gstate[gstate->stroke.gstate_num].ctm, gstate->stroke.alpha, &gstate->stroke.color_params); fz_pop_clip(ctx, pr->dev); } break; } } if (knockout_group) fz_end_group(ctx, pr->dev); if (dofill || dostroke) pdf_end_group(ctx, pr, &softmask); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: void OnStreamGenerationFailed(int request_id, MediaStreamRequestResult result) { OnStreamGenerationFailure(request_id, result); if (!quit_closures_.empty()) { base::Closure quit_closure = quit_closures_.front(); quit_closures_.pop(); task_runner_->PostTask(FROM_HERE, base::ResetAndReturn(&quit_closure)); } label_.clear(); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} 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 hub_release(struct kref *kref) { struct usb_hub *hub = container_of(kref, struct usb_hub, kref); usb_put_dev(hub->hdev); usb_put_intf(to_usb_interface(hub->intfdev)); kfree(hub); } Commit Message: USB: fix invalid memory access in hub_activate() Commit 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") changed the hub_activate() routine to make part of it run in a workqueue. However, the commit failed to take a reference to the usb_hub structure or to lock the hub interface while doing so. As a result, if a hub is plugged in and quickly unplugged before the work routine can run, the routine will try to access memory that has been deallocated. Or, if the hub is unplugged while the routine is running, the memory may be deallocated while it is in active use. This patch fixes the problem by taking a reference to the usb_hub at the start of hub_activate() and releasing it at the end (when the work is finished), and by locking the hub interface while the work routine is running. It also adds a check at the start of the routine to see if the hub has already been disconnected, in which nothing should be done. Signed-off-by: Alan Stern <[email protected]> Reported-by: Alexandru Cornea <[email protected]> Tested-by: Alexandru Cornea <[email protected]> Fixes: 8520f38099cc ("USB: change hub initialization sleeps to delayed_work") CC: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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: static int get_client_master_key(SSL *s) { int is_export, i, n, keya; unsigned int num_encrypted_key_bytes, key_length; unsigned long len; unsigned char *p; const SSL_CIPHER *cp; const EVP_CIPHER *c; const EVP_MD *md; unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH]; unsigned char decrypt_good; size_t j; p = (unsigned char *)s->init_buf->data; if (s->state == SSL2_ST_GET_CLIENT_MASTER_KEY_A) { i = ssl2_read(s, (char *)&(p[s->init_num]), 10 - s->init_num); if (i < (10 - s->init_num)) return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i)); s->init_num = 10; if (*(p++) != SSL2_MT_CLIENT_MASTER_KEY) { if (p[-1] != SSL2_MT_ERROR) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_READ_WRONG_PACKET_TYPE); } else SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_PEER_ERROR); return (-1); } cp = ssl2_get_cipher_by_char(p); if (cp == NULL) { ssl2_return_error(s, SSL2_PE_NO_CIPHER); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_CIPHER_MATCH); return (-1); } s->session->cipher = cp; p += 3; n2s(p, i); s->s2->tmp.clear = i; n2s(p, i); s->s2->tmp.enc = i; n2s(p, i); if (i > SSL_MAX_KEY_ARG_LENGTH) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_KEY_ARG_TOO_LONG); return -1; } s->session->key_arg_length = i; s->state = SSL2_ST_GET_CLIENT_MASTER_KEY_B; } /* SSL2_ST_GET_CLIENT_MASTER_KEY_B */ p = (unsigned char *)s->init_buf->data; if (s->init_buf->length < SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR); return -1; } keya = s->session->key_arg_length; len = 10 + (unsigned long)s->s2->tmp.clear + (unsigned long)s->s2->tmp.enc + (unsigned long)keya; if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_MESSAGE_TOO_LONG); return -1; } n = (int)len - s->init_num; i = ssl2_read(s, (char *)&(p[s->init_num]), n); if (i != n) return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i)); if (s->msg_callback) { /* CLIENT-MASTER-KEY */ s->msg_callback(0, s->version, 0, p, (size_t)len, s, s->msg_callback_arg); } p += 10; memcpy(s->session->key_arg, &(p[s->s2->tmp.clear + s->s2->tmp.enc]), (unsigned int)keya); if (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_PRIVATEKEY); return (-1); } is_export = SSL_C_IS_EXPORT(s->session->cipher); if (!ssl_cipher_get_evp(s->session, &c, &md, NULL, NULL, NULL)) { ssl2_return_error(s, SSL2_PE_NO_CIPHER); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS); return (0); } /* * The format of the CLIENT-MASTER-KEY message is * 1 byte message type * 3 bytes cipher * 2-byte clear key length (stored in s->s2->tmp.clear) * 2-byte encrypted key length (stored in s->s2->tmp.enc) * 2-byte key args length (IV etc) * clear key * encrypted key * key args * * If the cipher is an export cipher, then the encrypted key bytes * are a fixed portion of the total key (5 or 8 bytes). The size of * this portion is in |num_encrypted_key_bytes|. If the cipher is not an * export cipher, then the entire key material is encrypted (i.e., clear * key length must be zero). */ key_length = (unsigned int)EVP_CIPHER_key_length(c); if (key_length > SSL_MAX_MASTER_KEY_LENGTH) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR); return -1; } if (s->session->cipher->algorithm2 & SSL2_CF_8_BYTE_ENC) { is_export = 1; num_encrypted_key_bytes = 8; } else if (is_export) { num_encrypted_key_bytes = 5; } else { num_encrypted_key_bytes = key_length; } if (s->s2->tmp.clear + num_encrypted_key_bytes != key_length) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_BAD_LENGTH); return -1; } /* * The encrypted blob must decrypt to the encrypted portion of the key. * Decryption can't be expanding, so if we don't have enough encrypted * bytes to fit the key in the buffer, stop now. */ if (s->s2->tmp.enc < num_encrypted_key_bytes) { ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_LENGTH_TOO_SHORT); return -1; } /* * We must not leak whether a decryption failure occurs because of * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246, * section 7.4.7.1). The code follows that advice of the TLS RFC and * generates a random premaster secret for the case that the decrypt * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */ /* * should be RAND_bytes, but we cannot work around a failure. */ if (RAND_pseudo_bytes(rand_premaster_secret, (int)num_encrypted_key_bytes) <= 0) return 0; i = ssl_rsa_private_decrypt(s->cert, s->s2->tmp.enc, &(p[s->s2->tmp.clear]), &(p[s->s2->tmp.clear]), (s->s2->ssl2_rollback) ? RSA_SSLV23_PADDING : RSA_PKCS1_PADDING); ERR_clear_error(); /* * If a bad decrypt, continue with protocol but with a random master * secret (Bleichenbacher attack) */ decrypt_good = constant_time_eq_int_8(i, (int)num_encrypted_key_bytes); for (j = 0; j < num_encrypted_key_bytes; j++) { p[s->s2->tmp.clear + j] = constant_time_select_8(decrypt_good, p[s->s2->tmp.clear + j], rand_premaster_secret[j]); } s->session->master_key_length = (int)key_length; memcpy(s->session->master_key, p, key_length); OPENSSL_cleanse(p, key_length); return 1; } Commit Message: CWE ID: CWE-310 Target: 1 Example 2: Code: void PaintController::GenerateRasterInvalidationsComparingChunks( PaintChunk& new_chunk, const PaintChunk& old_chunk) { DCHECK(RuntimeEnabledFeatures::SlimmingPaintV175Enabled()); struct OldAndNewDisplayItems { const DisplayItem* old_item = nullptr; const DisplayItem* new_item = nullptr; }; HashMap<const DisplayItemClient*, OldAndNewDisplayItems> clients_to_invalidate; size_t highest_moved_to_index = 0; for (size_t old_index = old_chunk.begin_index; old_index < old_chunk.end_index; ++old_index) { const DisplayItem& old_item = current_paint_artifact_.GetDisplayItemList()[old_index]; const DisplayItemClient* client_to_invalidate_old_visual_rect = nullptr; if (old_item.IsTombstone()) { size_t moved_to_index = items_moved_into_new_list_[old_index]; if (new_display_item_list_[moved_to_index].DrawsContent()) { if (moved_to_index < new_chunk.begin_index || moved_to_index >= new_chunk.end_index) { const auto& new_item = new_display_item_list_[moved_to_index]; PaintChunk& moved_to_chunk = new_paint_chunks_.FindChunkByDisplayItemIndex(moved_to_index); AddRasterInvalidation(new_item.Client(), moved_to_chunk, new_item.VisualRect(), PaintInvalidationReason::kAppeared); client_to_invalidate_old_visual_rect = &new_item.Client(); } else if (moved_to_index < highest_moved_to_index) { client_to_invalidate_old_visual_rect = &new_display_item_list_[moved_to_index].Client(); } else { highest_moved_to_index = moved_to_index; } } } else if (old_item.DrawsContent()) { client_to_invalidate_old_visual_rect = &old_item.Client(); } if (client_to_invalidate_old_visual_rect) { clients_to_invalidate .insert(client_to_invalidate_old_visual_rect, OldAndNewDisplayItems()) .stored_value->value.old_item = &old_item; } } for (size_t new_index = new_chunk.begin_index; new_index < new_chunk.end_index; ++new_index) { const DisplayItem& new_item = new_display_item_list_[new_index]; if (new_item.DrawsContent() && !ClientCacheIsValid(new_item.Client())) { clients_to_invalidate.insert(&new_item.Client(), OldAndNewDisplayItems()) .stored_value->value.new_item = &new_item; } } for (const auto& item : clients_to_invalidate) { GenerateRasterInvalidation(*item.key, new_chunk, item.value.old_item, item.value.new_item); } } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} 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: int dtls1_listen(SSL *s, struct sockaddr *client) { int ret; SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE); s->d1->listen = 1; (void)BIO_dgram_get_peer(SSL_get_rbio(s), client); return 1; } 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: int main(int argc, char **argv) { int result; int error = FALSE; int display_license = FALSE; int display_help = FALSE; int c = 0; struct tm *tm, tm_s; time_t now; char datestring[256]; nagios_macros *mac; const char *worker_socket = NULL; int i; #ifdef HAVE_SIGACTION struct sigaction sig_action; #endif #ifdef HAVE_GETOPT_H int option_index = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"license", no_argument, 0, 'V'}, {"verify-config", no_argument, 0, 'v'}, {"daemon", no_argument, 0, 'd'}, {"test-scheduling", no_argument, 0, 's'}, {"precache-objects", no_argument, 0, 'p'}, {"use-precached-objects", no_argument, 0, 'u'}, {"enable-timing-point", no_argument, 0, 'T'}, {"worker", required_argument, 0, 'W'}, {0, 0, 0, 0} }; #define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index) #endif memset(&loadctl, 0, sizeof(loadctl)); mac = get_global_macros(); /* make sure we have the correct number of command line arguments */ if(argc < 2) error = TRUE; /* get all command line arguments */ while(1) { c = getopt(argc, argv, "+hVvdspuxTW"); if(c == -1 || c == EOF) break; switch(c) { case '?': /* usage */ case 'h': display_help = TRUE; break; case 'V': /* version */ display_license = TRUE; break; case 'v': /* verify */ verify_config++; break; case 's': /* scheduling check */ test_scheduling = TRUE; break; case 'd': /* daemon mode */ daemon_mode = TRUE; break; case 'p': /* precache object config */ precache_objects = TRUE; break; case 'u': /* use precached object config */ use_precached_objects = TRUE; break; case 'T': enable_timing_point = TRUE; break; case 'W': worker_socket = optarg; break; case 'x': printf("Warning: -x is deprecated and will be removed\n"); break; default: break; } } #ifdef DEBUG_MEMORY mtrace(); #endif /* if we're a worker we can skip everything below */ if(worker_socket) { exit(nagios_core_worker(worker_socket)); } /* Initialize configuration variables */ init_main_cfg_vars(1); init_shared_cfg_vars(1); if(daemon_mode == FALSE) { printf("\nNagios Core %s\n", PROGRAM_VERSION); printf("Copyright (c) 2009-present Nagios Core Development Team and Community Contributors\n"); printf("Copyright (c) 1999-2009 Ethan Galstad\n"); printf("Last Modified: %s\n", PROGRAM_MODIFICATION_DATE); printf("License: GPL\n\n"); printf("Website: https://www.nagios.org\n"); } /* just display the license */ if(display_license == TRUE) { printf("This program is free software; you can redistribute it and/or modify\n"); printf("it under the terms of the GNU General Public License version 2 as\n"); printf("published by the Free Software Foundation.\n\n"); printf("This program is distributed in the hope that it will be useful,\n"); printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); printf("GNU General Public License for more details.\n\n"); printf("You should have received a copy of the GNU General Public License\n"); printf("along with this program; if not, write to the Free Software\n"); printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n"); exit(OK); } /* make sure we got the main config file on the command line... */ if(optind >= argc) error = TRUE; /* if there are no command line options (or if we encountered an error), print usage */ if(error == TRUE || display_help == TRUE) { printf("Usage: %s [options] <main_config_file>\n", argv[0]); printf("\n"); printf("Options:\n"); printf("\n"); printf(" -v, --verify-config Verify all configuration data (-v -v for more info)\n"); printf(" -s, --test-scheduling Shows projected/recommended check scheduling and other\n"); printf(" diagnostic info based on the current configuration files.\n"); printf(" -T, --enable-timing-point Enable timed commentary on initialization\n"); printf(" -x, --dont-verify-paths Deprecated (Don't check for circular object paths)\n"); printf(" -p, --precache-objects Precache object configuration\n"); printf(" -u, --use-precached-objects Use precached object config file\n"); printf(" -d, --daemon Starts Nagios in daemon mode, instead of as a foreground process\n"); printf(" -W, --worker /path/to/socket Act as a worker for an already running daemon\n"); printf("\n"); printf("Visit the Nagios website at https://www.nagios.org/ for bug fixes, new\n"); printf("releases, online documentation, FAQs, information on subscribing to\n"); printf("the mailing lists, and commercial support options for Nagios.\n"); printf("\n"); exit(ERROR); } /* * config file is last argument specified. * Make sure it uses an absolute path */ config_file = nspath_absolute(argv[optind], NULL); if(config_file == NULL) { printf("Error allocating memory.\n"); exit(ERROR); } config_file_dir = nspath_absolute_dirname(config_file, NULL); /* * Set the signal handler for the SIGXFSZ signal here because * we may encounter this signal before the other signal handlers * are set. */ #ifdef HAVE_SIGACTION sig_action.sa_sigaction = NULL; sig_action.sa_handler = handle_sigxfsz; sigfillset(&sig_action.sa_mask); sig_action.sa_flags = SA_NODEFER|SA_RESTART; sigaction(SIGXFSZ, &sig_action, NULL); #else signal(SIGXFSZ, handle_sigxfsz); #endif /* * let's go to town. We'll be noisy if we're verifying config * or running scheduling tests. */ if(verify_config || test_scheduling || precache_objects) { reset_variables(); /* * if we don't beef up our resource limits as much as * we can, it's quite possible we'll run headlong into * EAGAIN due to too many processes when we try to * drop privileges later. */ set_loadctl_defaults(); if(verify_config) printf("Reading configuration data...\n"); /* read our config file */ result = read_main_config_file(config_file); if(result != OK) { printf(" Error processing main config file!\n\n"); exit(EXIT_FAILURE); } if(verify_config) printf(" Read main config file okay...\n"); /* drop privileges */ if((result = drop_privileges(nagios_user, nagios_group)) == ERROR) { printf(" Failed to drop privileges. Aborting."); exit(EXIT_FAILURE); } /* * this must come after dropping privileges, so we make * sure to test access permissions as the right user. */ if (!verify_config && test_configured_paths() == ERROR) { printf(" One or more path problems detected. Aborting.\n"); exit(EXIT_FAILURE); } /* read object config files */ result = read_all_object_data(config_file); if(result != OK) { printf(" Error processing object config files!\n\n"); /* if the config filename looks fishy, warn the user */ if(!strstr(config_file, "nagios.cfg")) { printf("\n***> The name of the main configuration file looks suspicious...\n"); printf("\n"); printf(" Make sure you are specifying the name of the MAIN configuration file on\n"); printf(" the command line and not the name of another configuration file. The\n"); printf(" main configuration file is typically '%s'\n", DEFAULT_CONFIG_FILE); } printf("\n***> One or more problems was encountered while processing the config files...\n"); printf("\n"); printf(" Check your configuration file(s) to ensure that they contain valid\n"); printf(" directives and data definitions. If you are upgrading from a previous\n"); printf(" version of Nagios, you should be aware that some variables/definitions\n"); printf(" may have been removed or modified in this version. Make sure to read\n"); printf(" the HTML documentation regarding the config files, as well as the\n"); printf(" 'Whats New' section to find out what has changed.\n\n"); exit(EXIT_FAILURE); } if(verify_config) { printf(" Read object config files okay...\n\n"); printf("Running pre-flight check on configuration data...\n\n"); } /* run the pre-flight check to make sure things look okay... */ result = pre_flight_check(); if(result != OK) { printf("\n***> One or more problems was encountered while running the pre-flight check...\n"); printf("\n"); printf(" Check your configuration file(s) to ensure that they contain valid\n"); printf(" directives and data definitions. If you are upgrading from a previous\n"); printf(" version of Nagios, you should be aware that some variables/definitions\n"); printf(" may have been removed or modified in this version. Make sure to read\n"); printf(" the HTML documentation regarding the config files, as well as the\n"); printf(" 'Whats New' section to find out what has changed.\n\n"); exit(EXIT_FAILURE); } if(verify_config) { printf("\nThings look okay - No serious problems were detected during the pre-flight check\n"); } /* scheduling tests need a bit more than config verifications */ if(test_scheduling == TRUE) { /* we'll need the event queue here so we can time insertions */ init_event_queue(); timing_point("Done initializing event queue\n"); /* read initial service and host state information */ initialize_retention_data(config_file); read_initial_state_information(); timing_point("Retention data and initial state parsed\n"); /* initialize the event timing loop */ init_timing_loop(); timing_point("Timing loop initialized\n"); /* display scheduling information */ display_scheduling_info(); } if(precache_objects) { result = fcache_objects(object_precache_file); timing_point("Done precaching objects\n"); if(result == OK) { printf("Object precache file created:\n%s\n", object_precache_file); } else { printf("Failed to precache objects to '%s': %s\n", object_precache_file, strerror(errno)); } } /* clean up after ourselves */ cleanup(); /* exit */ timing_point("Exiting\n"); /* make valgrind shut up about still reachable memory */ neb_free_module_list(); free(config_file_dir); free(config_file); exit(result); } /* else start to monitor things... */ else { /* * if we're called with a relative path we must make * it absolute so we can launch our workers. * If not, we needn't bother, as we're using execvp() */ if (strchr(argv[0], '/')) nagios_binary_path = nspath_absolute(argv[0], NULL); else nagios_binary_path = strdup(argv[0]); if (!nagios_binary_path) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to allocate memory for nagios_binary_path\n"); exit(EXIT_FAILURE); } if (!(nagios_iobs = iobroker_create())) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to create IO broker set: %s\n", strerror(errno)); exit(EXIT_FAILURE); } /* keep monitoring things until we get a shutdown command */ do { /* reset internal book-keeping (in case we're restarting) */ wproc_num_workers_spawned = wproc_num_workers_online = 0; caught_signal = sigshutdown = FALSE; sig_id = 0; /* reset program variables */ reset_variables(); timing_point("Variables reset\n"); /* get PID */ nagios_pid = (int)getpid(); /* read in the configuration files (main and resource config files) */ result = read_main_config_file(config_file); if (result != OK) { logit(NSLOG_CONFIG_ERROR, TRUE, "Error: Failed to process config file '%s'. Aborting\n", config_file); exit(EXIT_FAILURE); } timing_point("Main config file read\n"); /* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */ /* get program (re)start time and save as macro */ program_start = time(NULL); my_free(mac->x[MACRO_PROCESSSTARTTIME]); asprintf(&mac->x[MACRO_PROCESSSTARTTIME], "%llu", (unsigned long long)program_start); /* drop privileges */ if(drop_privileges(nagios_user, nagios_group) == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Failed to drop privileges. Aborting."); cleanup(); exit(ERROR); } if (test_path_access(nagios_binary_path, X_OK)) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: failed to access() %s: %s\n", nagios_binary_path, strerror(errno)); logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Spawning workers will be impossible. Aborting.\n"); exit(EXIT_FAILURE); } if (test_configured_paths() == ERROR) { /* error has already been logged */ exit(EXIT_FAILURE); } /* enter daemon mode (unless we're restarting...) */ if(daemon_mode == TRUE && sigrestart == FALSE) { result = daemon_init(); /* we had an error daemonizing, so bail... */ if(result == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, "Bailing out due to failure to daemonize. (PID=%d)", (int)getpid()); cleanup(); exit(EXIT_FAILURE); } /* get new PID */ nagios_pid = (int)getpid(); } /* this must be logged after we read config data, as user may have changed location of main log file */ logit(NSLOG_PROCESS_INFO, TRUE, "Nagios %s starting... (PID=%d)\n", PROGRAM_VERSION, (int)getpid()); /* log the local time - may be different than clock time due to timezone offset */ now = time(NULL); tm = localtime_r(&now, &tm_s); strftime(datestring, sizeof(datestring), "%a %b %d %H:%M:%S %Z %Y", tm); logit(NSLOG_PROCESS_INFO, TRUE, "Local time is %s", datestring); /* write log version/info */ write_log_file_info(NULL); /* open debug log now that we're the right user */ open_debug_log(); #ifdef USE_EVENT_BROKER /* initialize modules */ neb_init_modules(); neb_init_callback_list(); #endif timing_point("NEB module API initialized\n"); /* handle signals (interrupts) before we do any socket I/O */ setup_sighandler(); /* * Initialize query handler and event subscription service. * This must be done before modules are initialized, so * the modules can use our in-core stuff properly */ if (qh_init(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET) != OK) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to initialize query handler. Aborting\n"); exit(EXIT_FAILURE); } timing_point("Query handler initialized\n"); nerd_init(); timing_point("NERD initialized\n"); /* initialize check workers */ if(init_workers(num_check_workers) < 0) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Failed to spawn workers. Aborting\n"); exit(EXIT_FAILURE); } timing_point("%u workers spawned\n", wproc_num_workers_spawned); i = 0; while (i < 50 && wproc_num_workers_online < wproc_num_workers_spawned) { iobroker_poll(nagios_iobs, 50); i++; } timing_point("%u workers connected\n", wproc_num_workers_online); /* now that workers have arrived we can set the defaults */ set_loadctl_defaults(); #ifdef USE_EVENT_BROKER /* load modules */ if (neb_load_all_modules() != OK) { logit(NSLOG_CONFIG_ERROR, ERROR, "Error: Module loading failed. Aborting.\n"); /* if we're dumping core, we must remove all dl-files */ if (daemon_dumps_core) neb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, NEBMODULE_NEB_SHUTDOWN); exit(EXIT_FAILURE); } timing_point("Modules loaded\n"); /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE, NULL); timing_point("First callback made\n"); #endif /* read in all object config data */ if(result == OK) result = read_all_object_data(config_file); /* there was a problem reading the config files */ if(result != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)", (int)getpid()); else { /* run the pre-flight check to make sure everything looks okay*/ if((result = pre_flight_check()) != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, TRUE, "Bailing out due to errors encountered while running the pre-flight check. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\n", (int)getpid()); } /* an error occurred that prevented us from (re)starting */ if(result != OK) { /* if we were restarting, we need to cleanup from the previous run */ if(sigrestart == TRUE) { /* clean up the status data */ cleanup_status_data(TRUE); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL); #endif cleanup(); exit(ERROR); } timing_point("Object configuration parsed and understood\n"); /* write the objects.cache file */ fcache_objects(object_cache_file); timing_point("Objects cached\n"); init_event_queue(); timing_point("Event queue initialized\n"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* initialize status data unless we're starting */ if(sigrestart == FALSE) { initialize_status_data(config_file); timing_point("Status data initialized\n"); } /* initialize scheduled downtime data */ initialize_downtime_data(); timing_point("Downtime data initialized\n"); /* read initial service and host state information */ initialize_retention_data(config_file); timing_point("Retention data initialized\n"); read_initial_state_information(); timing_point("Initial state information read\n"); /* initialize comment data */ initialize_comment_data(); timing_point("Comment data initialized\n"); /* initialize performance data */ initialize_performance_data(config_file); timing_point("Performance data initialized\n"); /* initialize the event timing loop */ init_timing_loop(); timing_point("Event timing loop initialized\n"); /* initialize check statistics */ init_check_stats(); timing_point("check stats initialized\n"); /* check for updates */ check_for_nagios_updates(FALSE, TRUE); timing_point("Update check concluded\n"); /* update all status data (with retained information) */ update_all_status_data(); timing_point("Status data updated\n"); /* log initial host and service state */ log_host_states(INITIAL_STATES, NULL); log_service_states(INITIAL_STATES, NULL); timing_point("Initial states logged\n"); /* reset the restart flag */ sigrestart = FALSE; /* fire up command file worker */ launch_command_file_worker(); timing_point("Command file worker launched\n"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* get event start time and save as macro */ event_start = time(NULL); my_free(mac->x[MACRO_EVENTSTARTTIME]); asprintf(&mac->x[MACRO_EVENTSTARTTIME], "%llu", (unsigned long long)event_start); timing_point("Entering event execution loop\n"); /***** start monitoring all services *****/ /* (doesn't return until a restart or shutdown signal is encountered) */ event_execution_loop(); /* * immediately deinitialize the query handler so it * can remove modules that have stashed data with it */ qh_deinit(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET); /* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */ /* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */ /* did we catch a signal? */ if(caught_signal == TRUE) { if(sig_id == SIGHUP) logit(NSLOG_PROCESS_INFO, TRUE, "Caught SIGHUP, restarting...\n"); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE, NULL); if(sigshutdown == TRUE) broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL, NULL); else if(sigrestart == TRUE) broker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL, NULL); #endif /* save service and host state information */ save_state_information(FALSE); cleanup_retention_data(); /* clean up performance data */ cleanup_performance_data(); /* clean up the scheduled downtime data */ cleanup_downtime_data(); /* clean up the status data unless we're restarting */ if(sigrestart == FALSE) { cleanup_status_data(TRUE); } free_worker_memory(WPROC_FORCE); /* shutdown stuff... */ if(sigshutdown == TRUE) { iobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS); nagios_iobs = NULL; /* log a shutdown message */ logit(NSLOG_PROCESS_INFO, TRUE, "Successfully shutdown... (PID=%d)\n", (int)getpid()); } /* clean up after ourselves */ cleanup(); /* close debug log */ close_debug_log(); } while(sigrestart == TRUE && sigshutdown == FALSE); if(daemon_mode == TRUE) unlink(lock_file); /* free misc memory */ my_free(lock_file); my_free(config_file); my_free(config_file_dir); my_free(nagios_binary_path); } return OK; } Commit Message: halfway revert hack/configure changes - switch order of daemon_init/drop_privileges CWE ID: CWE-665 Target: 1 Example 2: Code: static void arcmsr_done4abort_postqueue(struct AdapterControlBlock *acb) { int i = 0; uint32_t flag_ccb, ccb_cdb_phy; struct ARCMSR_CDB *pARCMSR_CDB; bool error; struct CommandControlBlock *pCCB; switch (acb->adapter_type) { case ACB_ADAPTER_TYPE_A: { struct MessageUnit_A __iomem *reg = acb->pmuA; uint32_t outbound_intstatus; outbound_intstatus = readl(&reg->outbound_intstatus) & acb->outbound_int_enable; /*clear and abort all outbound posted Q*/ writel(outbound_intstatus, &reg->outbound_intstatus);/*clear interrupt*/ while(((flag_ccb = readl(&reg->outbound_queueport)) != 0xFFFFFFFF) && (i++ < ARCMSR_MAX_OUTSTANDING_CMD)) { pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset + (flag_ccb << 5));/*frame must be 32 bytes aligned*/ pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb); error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false; arcmsr_drain_donequeue(acb, pCCB, error); } } break; case ACB_ADAPTER_TYPE_B: { struct MessageUnit_B *reg = acb->pmuB; /*clear all outbound posted Q*/ writel(ARCMSR_DOORBELL_INT_CLEAR_PATTERN, reg->iop2drv_doorbell); /* clear doorbell interrupt */ for (i = 0; i < ARCMSR_MAX_HBB_POSTQUEUE; i++) { flag_ccb = reg->done_qbuffer[i]; if (flag_ccb != 0) { reg->done_qbuffer[i] = 0; pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset+(flag_ccb << 5));/*frame must be 32 bytes aligned*/ pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb); error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE0) ? true : false; arcmsr_drain_donequeue(acb, pCCB, error); } reg->post_qbuffer[i] = 0; } reg->doneq_index = 0; reg->postq_index = 0; } break; case ACB_ADAPTER_TYPE_C: { struct MessageUnit_C __iomem *reg = acb->pmuC; while ((readl(&reg->host_int_status) & ARCMSR_HBCMU_OUTBOUND_POSTQUEUE_ISR) && (i++ < ARCMSR_MAX_OUTSTANDING_CMD)) { /*need to do*/ flag_ccb = readl(&reg->outbound_queueport_low); ccb_cdb_phy = (flag_ccb & 0xFFFFFFF0); pARCMSR_CDB = (struct ARCMSR_CDB *)(acb->vir2phy_offset+ccb_cdb_phy);/*frame must be 32 bytes aligned*/ pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb); error = (flag_ccb & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1) ? true : false; arcmsr_drain_donequeue(acb, pCCB, error); } } break; case ACB_ADAPTER_TYPE_D: { struct MessageUnit_D *pmu = acb->pmuD; uint32_t outbound_write_pointer; uint32_t doneq_index, index_stripped, addressLow, residual, toggle; unsigned long flags; residual = atomic_read(&acb->ccboutstandingcount); for (i = 0; i < residual; i++) { spin_lock_irqsave(&acb->doneq_lock, flags); outbound_write_pointer = pmu->done_qbuffer[0].addressLow + 1; doneq_index = pmu->doneq_index; if ((doneq_index & 0xFFF) != (outbound_write_pointer & 0xFFF)) { toggle = doneq_index & 0x4000; index_stripped = (doneq_index & 0xFFF) + 1; index_stripped %= ARCMSR_MAX_ARC1214_DONEQUEUE; pmu->doneq_index = index_stripped ? (index_stripped | toggle) : ((toggle ^ 0x4000) + 1); doneq_index = pmu->doneq_index; spin_unlock_irqrestore(&acb->doneq_lock, flags); addressLow = pmu->done_qbuffer[doneq_index & 0xFFF].addressLow; ccb_cdb_phy = (addressLow & 0xFFFFFFF0); pARCMSR_CDB = (struct ARCMSR_CDB *) (acb->vir2phy_offset + ccb_cdb_phy); pCCB = container_of(pARCMSR_CDB, struct CommandControlBlock, arcmsr_cdb); error = (addressLow & ARCMSR_CCBREPLY_FLAG_ERROR_MODE1) ? true : false; arcmsr_drain_donequeue(acb, pCCB, error); writel(doneq_index, pmu->outboundlist_read_pointer); } else { spin_unlock_irqrestore(&acb->doneq_lock, flags); mdelay(10); } } pmu->postq_index = 0; pmu->doneq_index = 0x40FF; } break; } } 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: bool AppCacheBackendImpl::SelectCacheForSharedWorker( int host_id, int64 appcache_id) { AppCacheHost* host = GetHost(host_id); if (!host || host->was_select_cache_called()) return false; host->SelectCacheForSharedWorker(appcache_id); return true; } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID: 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 l2tp_ip_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_l2tpip *addr = (struct sockaddr_l2tpip *) uaddr; struct net *net = sock_net(sk); int ret; int chk_addr_ret; if (!sock_flag(sk, SOCK_ZAPPED)) return -EINVAL; if (addr_len < sizeof(struct sockaddr_l2tpip)) return -EINVAL; if (addr->l2tp_family != AF_INET) return -EINVAL; ret = -EADDRINUSE; read_lock_bh(&l2tp_ip_lock); if (__l2tp_ip_bind_lookup(net, addr->l2tp_addr.s_addr, sk->sk_bound_dev_if, addr->l2tp_conn_id)) goto out_in_use; read_unlock_bh(&l2tp_ip_lock); lock_sock(sk); if (sk->sk_state != TCP_CLOSE || addr_len < sizeof(struct sockaddr_l2tpip)) goto out; chk_addr_ret = inet_addr_type(net, addr->l2tp_addr.s_addr); ret = -EADDRNOTAVAIL; if (addr->l2tp_addr.s_addr && chk_addr_ret != RTN_LOCAL && chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST) goto out; if (addr->l2tp_addr.s_addr) inet->inet_rcv_saddr = inet->inet_saddr = addr->l2tp_addr.s_addr; if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST) inet->inet_saddr = 0; /* Use device */ sk_dst_reset(sk); l2tp_ip_sk(sk)->conn_id = addr->l2tp_conn_id; write_lock_bh(&l2tp_ip_lock); sk_add_bind_node(sk, &l2tp_ip_bind_table); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip_lock); ret = 0; sock_reset_flag(sk, SOCK_ZAPPED); out: release_sock(sk); return ret; out_in_use: read_unlock_bh(&l2tp_ip_lock); return ret; } Commit Message: l2tp: fix racy SOCK_ZAPPED flag check in l2tp_ip{,6}_bind() Lock socket before checking the SOCK_ZAPPED flag in l2tp_ip6_bind(). Without lock, a concurrent call could modify the socket flags between the sock_flag(sk, SOCK_ZAPPED) test and the lock_sock() call. This way, a socket could be inserted twice in l2tp_ip6_bind_table. Releasing it would then leave a stale pointer there, generating use-after-free errors when walking through the list or modifying adjacent entries. BUG: KASAN: use-after-free in l2tp_ip6_close+0x22e/0x290 at addr ffff8800081b0ed8 Write of size 8 by task syz-executor/10987 CPU: 0 PID: 10987 Comm: syz-executor Not tainted 4.8.0+ #39 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014 ffff880031d97838 ffffffff829f835b ffff88001b5a1640 ffff8800081b0ec0 ffff8800081b15a0 ffff8800081b6d20 ffff880031d97860 ffffffff8174d3cc ffff880031d978f0 ffff8800081b0e80 ffff88001b5a1640 ffff880031d978e0 Call Trace: [<ffffffff829f835b>] dump_stack+0xb3/0x118 lib/dump_stack.c:15 [<ffffffff8174d3cc>] kasan_object_err+0x1c/0x70 mm/kasan/report.c:156 [< inline >] print_address_description mm/kasan/report.c:194 [<ffffffff8174d666>] kasan_report_error+0x1f6/0x4d0 mm/kasan/report.c:283 [< inline >] kasan_report mm/kasan/report.c:303 [<ffffffff8174db7e>] __asan_report_store8_noabort+0x3e/0x40 mm/kasan/report.c:329 [< inline >] __write_once_size ./include/linux/compiler.h:249 [< inline >] __hlist_del ./include/linux/list.h:622 [< inline >] hlist_del_init ./include/linux/list.h:637 [<ffffffff8579047e>] l2tp_ip6_close+0x22e/0x290 net/l2tp/l2tp_ip6.c:239 [<ffffffff850b2dfd>] inet_release+0xed/0x1c0 net/ipv4/af_inet.c:415 [<ffffffff851dc5a0>] inet6_release+0x50/0x70 net/ipv6/af_inet6.c:422 [<ffffffff84c4581d>] sock_release+0x8d/0x1d0 net/socket.c:570 [<ffffffff84c45976>] sock_close+0x16/0x20 net/socket.c:1017 [<ffffffff817a108c>] __fput+0x28c/0x780 fs/file_table.c:208 [<ffffffff817a1605>] ____fput+0x15/0x20 fs/file_table.c:244 [<ffffffff813774f9>] task_work_run+0xf9/0x170 [<ffffffff81324aae>] do_exit+0x85e/0x2a00 [<ffffffff81326dc8>] do_group_exit+0x108/0x330 [<ffffffff81348cf7>] get_signal+0x617/0x17a0 kernel/signal.c:2307 [<ffffffff811b49af>] do_signal+0x7f/0x18f0 [<ffffffff810039bf>] exit_to_usermode_loop+0xbf/0x150 arch/x86/entry/common.c:156 [< inline >] prepare_exit_to_usermode arch/x86/entry/common.c:190 [<ffffffff81006060>] syscall_return_slowpath+0x1a0/0x1e0 arch/x86/entry/common.c:259 [<ffffffff85e4d726>] entry_SYSCALL_64_fastpath+0xc4/0xc6 Object at ffff8800081b0ec0, in cache L2TP/IPv6 size: 1448 Allocated: PID = 10987 [ 1116.897025] [<ffffffff811ddcb6>] save_stack_trace+0x16/0x20 [ 1116.897025] [<ffffffff8174c736>] save_stack+0x46/0xd0 [ 1116.897025] [<ffffffff8174c9ad>] kasan_kmalloc+0xad/0xe0 [ 1116.897025] [<ffffffff8174cee2>] kasan_slab_alloc+0x12/0x20 [ 1116.897025] [< inline >] slab_post_alloc_hook mm/slab.h:417 [ 1116.897025] [< inline >] slab_alloc_node mm/slub.c:2708 [ 1116.897025] [< inline >] slab_alloc mm/slub.c:2716 [ 1116.897025] [<ffffffff817476a8>] kmem_cache_alloc+0xc8/0x2b0 mm/slub.c:2721 [ 1116.897025] [<ffffffff84c4f6a9>] sk_prot_alloc+0x69/0x2b0 net/core/sock.c:1326 [ 1116.897025] [<ffffffff84c58ac8>] sk_alloc+0x38/0xae0 net/core/sock.c:1388 [ 1116.897025] [<ffffffff851ddf67>] inet6_create+0x2d7/0x1000 net/ipv6/af_inet6.c:182 [ 1116.897025] [<ffffffff84c4af7b>] __sock_create+0x37b/0x640 net/socket.c:1153 [ 1116.897025] [< inline >] sock_create net/socket.c:1193 [ 1116.897025] [< inline >] SYSC_socket net/socket.c:1223 [ 1116.897025] [<ffffffff84c4b46f>] SyS_socket+0xef/0x1b0 net/socket.c:1203 [ 1116.897025] [<ffffffff85e4d685>] entry_SYSCALL_64_fastpath+0x23/0xc6 Freed: PID = 10987 [ 1116.897025] [<ffffffff811ddcb6>] save_stack_trace+0x16/0x20 [ 1116.897025] [<ffffffff8174c736>] save_stack+0x46/0xd0 [ 1116.897025] [<ffffffff8174cf61>] kasan_slab_free+0x71/0xb0 [ 1116.897025] [< inline >] slab_free_hook mm/slub.c:1352 [ 1116.897025] [< inline >] slab_free_freelist_hook mm/slub.c:1374 [ 1116.897025] [< inline >] slab_free mm/slub.c:2951 [ 1116.897025] [<ffffffff81748b28>] kmem_cache_free+0xc8/0x330 mm/slub.c:2973 [ 1116.897025] [< inline >] sk_prot_free net/core/sock.c:1369 [ 1116.897025] [<ffffffff84c541eb>] __sk_destruct+0x32b/0x4f0 net/core/sock.c:1444 [ 1116.897025] [<ffffffff84c5aca4>] sk_destruct+0x44/0x80 net/core/sock.c:1452 [ 1116.897025] [<ffffffff84c5ad33>] __sk_free+0x53/0x220 net/core/sock.c:1460 [ 1116.897025] [<ffffffff84c5af23>] sk_free+0x23/0x30 net/core/sock.c:1471 [ 1116.897025] [<ffffffff84c5cb6c>] sk_common_release+0x28c/0x3e0 ./include/net/sock.h:1589 [ 1116.897025] [<ffffffff8579044e>] l2tp_ip6_close+0x1fe/0x290 net/l2tp/l2tp_ip6.c:243 [ 1116.897025] [<ffffffff850b2dfd>] inet_release+0xed/0x1c0 net/ipv4/af_inet.c:415 [ 1116.897025] [<ffffffff851dc5a0>] inet6_release+0x50/0x70 net/ipv6/af_inet6.c:422 [ 1116.897025] [<ffffffff84c4581d>] sock_release+0x8d/0x1d0 net/socket.c:570 [ 1116.897025] [<ffffffff84c45976>] sock_close+0x16/0x20 net/socket.c:1017 [ 1116.897025] [<ffffffff817a108c>] __fput+0x28c/0x780 fs/file_table.c:208 [ 1116.897025] [<ffffffff817a1605>] ____fput+0x15/0x20 fs/file_table.c:244 [ 1116.897025] [<ffffffff813774f9>] task_work_run+0xf9/0x170 [ 1116.897025] [<ffffffff81324aae>] do_exit+0x85e/0x2a00 [ 1116.897025] [<ffffffff81326dc8>] do_group_exit+0x108/0x330 [ 1116.897025] [<ffffffff81348cf7>] get_signal+0x617/0x17a0 kernel/signal.c:2307 [ 1116.897025] [<ffffffff811b49af>] do_signal+0x7f/0x18f0 [ 1116.897025] [<ffffffff810039bf>] exit_to_usermode_loop+0xbf/0x150 arch/x86/entry/common.c:156 [ 1116.897025] [< inline >] prepare_exit_to_usermode arch/x86/entry/common.c:190 [ 1116.897025] [<ffffffff81006060>] syscall_return_slowpath+0x1a0/0x1e0 arch/x86/entry/common.c:259 [ 1116.897025] [<ffffffff85e4d726>] entry_SYSCALL_64_fastpath+0xc4/0xc6 Memory state around the buggy address: ffff8800081b0d80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc ffff8800081b0e00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc >ffff8800081b0e80: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb ^ ffff8800081b0f00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8800081b0f80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ================================================================== The same issue exists with l2tp_ip_bind() and l2tp_ip_bind_table. Fixes: c51ce49735c1 ("l2tp: fix oops in L2TP IP sockets for connect() AF_UNSPEC case") Reported-by: Baozeng Ding <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Tested-by: Baozeng Ding <[email protected]> Signed-off-by: Guillaume Nault <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: bool HTMLFormControlElement::IsSuccessfulSubmitButton() const { return CanBeSuccessfulSubmitButton() && !IsDisabledFormControl(); } Commit Message: autofocus: Fix a crash with an autofocus element in a document without browsing context. ShouldAutofocus() should check existence of the browsing context. Otherwise, doc.TopFrameOrigin() returns null. Before crrev.com/695830, ShouldAutofocus() was called only for rendered elements. That is to say, the document always had browsing context. Bug: 1003228 Change-Id: I2a941c34e9707d44869a6d7585dc7fb9f06e3bf4 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1800902 Commit-Queue: Kent Tamura <[email protected]> Reviewed-by: Keishi Hattori <[email protected]> Cr-Commit-Position: refs/heads/master@{#696291} 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: static void br_multicast_port_group_query_expired(unsigned long data) { struct net_bridge_port_group *pg = (void *)data; struct net_bridge_port *port = pg->port; struct net_bridge *br = port->br; spin_lock(&br->multicast_lock); if (!netif_running(br->dev) || hlist_unhashed(&pg->mglist) || pg->queries_sent >= br->multicast_last_member_count) goto out; br_multicast_send_port_group_query(pg); out: spin_unlock(&br->multicast_lock); } Commit Message: bridge: Fix mglist corruption that leads to memory corruption The list mp->mglist is used to indicate whether a multicast group is active on the bridge interface itself as opposed to one of the constituent interfaces in the bridge. Unfortunately the operation that adds the mp->mglist node to the list neglected to check whether it has already been added. This leads to list corruption in the form of nodes pointing to itself. Normally this would be quite obvious as it would cause an infinite loop when walking the list. However, as this list is never actually walked (which means that we don't really need it, I'll get rid of it in a subsequent patch), this instead is hidden until we perform a delete operation on the affected nodes. As the same node may now be pointed to by more than one node, the delete operations can then cause modification of freed memory. This was observed in practice to cause corruption in 512-byte slabs, most commonly leading to crashes in jbd2. Thanks to Josef Bacik for pointing me in the right direction. Reported-by: Ian Page Hands <[email protected]> Signed-off-by: Herbert Xu <[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 void LongOrNullAttributeAttributeSetter( v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); ALLOW_UNUSED_LOCAL(isolate); v8::Local<v8::Object> holder = info.Holder(); ALLOW_UNUSED_LOCAL(holder); TestObject* impl = V8TestObject::ToImpl(holder); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "longOrNullAttribute"); int32_t cpp_value = NativeValueTraits<IDLLong>::NativeValue(info.GetIsolate(), v8_value, exception_state); if (exception_state.HadException()) return; bool is_null = IsUndefinedOrNull(v8_value); impl->setLongOrNullAttribute(cpp_value, is_null); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <[email protected]> Commit-Queue: Yuki Shiino <[email protected]> Cr-Commit-Position: refs/heads/master@{#718676} CWE ID: Target: 1 Example 2: Code: static int check_crl(X509_STORE_CTX *ctx, X509_CRL *crl) { X509 *issuer = NULL; EVP_PKEY *ikey = NULL; int ok = 0, chnum, cnum; cnum = ctx->error_depth; chnum = sk_X509_num(ctx->chain) - 1; /* if we have an alternative CRL issuer cert use that */ if (ctx->current_issuer) issuer = ctx->current_issuer; /* * Else find CRL issuer: if not last certificate then issuer is next * certificate in chain. */ else if (cnum < chnum) issuer = sk_X509_value(ctx->chain, cnum + 1); else { issuer = sk_X509_value(ctx->chain, chnum); /* If not self signed, can't check signature */ if (!ctx->check_issued(ctx, issuer, issuer)) { ctx->error = X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } } if (issuer) { /* * Skip most tests for deltas because they have already been done */ if (!crl->base_crl_number) { /* Check for cRLSign bit if keyUsage present */ if ((issuer->ex_flags & EXFLAG_KUSAGE) && !(issuer->ex_kusage & KU_CRL_SIGN)) { ctx->error = X509_V_ERR_KEYUSAGE_NO_CRL_SIGN; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } if (!(ctx->current_crl_score & CRL_SCORE_SCOPE)) { ctx->error = X509_V_ERR_DIFFERENT_CRL_SCOPE; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } if (!(ctx->current_crl_score & CRL_SCORE_SAME_PATH)) { if (check_crl_path(ctx, ctx->current_issuer) <= 0) { ctx->error = X509_V_ERR_CRL_PATH_VALIDATION_ERROR; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } } if (crl->idp_flags & IDP_INVALID) { ctx->error = X509_V_ERR_INVALID_EXTENSION; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } } if (!(ctx->current_crl_score & CRL_SCORE_TIME)) { ok = check_crl_time(ctx, crl, 1); if (!ok) goto err; } /* Attempt to get issuer certificate public key */ ikey = X509_get_pubkey(issuer); if (!ikey) { ctx->error = X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } else { /* Verify CRL signature */ if (X509_CRL_verify(crl, ikey) <= 0) { ctx->error = X509_V_ERR_CRL_SIGNATURE_FAILURE; ok = ctx->verify_cb(0, ctx); if (!ok) goto err; } } } ok = 1; err: EVP_PKEY_free(ikey); return ok; } Commit Message: 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: DateTimeFieldElement::DateTimeFieldElement(Document* document, FieldOwner& fieldOwner) : HTMLElement(spanTag, document) , m_fieldOwner(&fieldOwner) { setAttribute(roleAttr, "spinbutton"); } Commit Message: INPUT_MULTIPLE_FIELDS_UI: Inconsistent value of aria-valuetext attribute https://bugs.webkit.org/show_bug.cgi?id=107897 Reviewed by Kentaro Hara. Source/WebCore: aria-valuetext and aria-valuenow attributes had inconsistent values in a case of initial empty state and a case that a user clears a field. - aria-valuetext attribute should have "blank" message in the initial empty state. - aria-valuenow attribute should be removed in the cleared empty state. Also, we have a bug that aira-valuenow had a symbolic value such as "AM" "January". It should always have a numeric value according to the specification. http://www.w3.org/TR/wai-aria/states_and_properties#aria-valuenow No new tests. Updates fast/forms/*-multiple-fields/*-multiple-fields-ax-aria-attributes.html. * html/shadow/DateTimeFieldElement.cpp: (WebCore::DateTimeFieldElement::DateTimeFieldElement): Set "blank" message to aria-valuetext attribute. (WebCore::DateTimeFieldElement::updateVisibleValue): aria-valuenow attribute should be a numeric value. Apply String::number to the return value of valueForARIAValueNow. Remove aria-valuenow attribute if nothing is selected. (WebCore::DateTimeFieldElement::valueForARIAValueNow): Added. * html/shadow/DateTimeFieldElement.h: (DateTimeFieldElement): Declare valueForARIAValueNow. * html/shadow/DateTimeSymbolicFieldElement.cpp: (WebCore::DateTimeSymbolicFieldElement::valueForARIAValueNow): Added. Returns 1 + internal selection index. For example, the function returns 1 for January. * html/shadow/DateTimeSymbolicFieldElement.h: (DateTimeSymbolicFieldElement): Declare valueForARIAValueNow. LayoutTests: Fix existing tests to show aria-valuenow attribute values. * fast/forms/resources/multiple-fields-ax-aria-attributes.js: Added. * fast/forms/date-multiple-fields/date-multiple-fields-ax-aria-attributes-expected.txt: * fast/forms/date-multiple-fields/date-multiple-fields-ax-aria-attributes.html: Use multiple-fields-ax-aria-attributes.js. Add tests for initial empty-value state. * fast/forms/month-multiple-fields/month-multiple-fields-ax-aria-attributes-expected.txt: * fast/forms/month-multiple-fields/month-multiple-fields-ax-aria-attributes.html: Use multiple-fields-ax-aria-attributes.js. * fast/forms/time-multiple-fields/time-multiple-fields-ax-aria-attributes-expected.txt: * fast/forms/time-multiple-fields/time-multiple-fields-ax-aria-attributes.html: Use multiple-fields-ax-aria-attributes.js. git-svn-id: svn://svn.chromium.org/blink/trunk@140803 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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 BluetoothDeviceChooserController::OnBluetoothChooserEvent( BluetoothChooser::Event event, const std::string& device_address) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(chooser_.get()); switch (event) { case BluetoothChooser::Event::RESCAN: RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); device_ids_.clear(); PopulateConnectedDevices(); DCHECK(chooser_); StartDeviceDiscovery(); return; case BluetoothChooser::Event::DENIED_PERMISSION: RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(blink::mojom::WebBluetoothResult:: CHOOSER_NOT_SHOWN_USER_DENIED_PERMISSION_TO_SCAN); break; case BluetoothChooser::Event::CANCELLED: RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SHOW_OVERVIEW_HELP: DVLOG(1) << "Overview Help link pressed."; RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SHOW_ADAPTER_OFF_HELP: DVLOG(1) << "Adapter Off Help link pressed."; RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SHOW_NEED_LOCATION_HELP: DVLOG(1) << "Need Location Help link pressed."; RecordRequestDeviceOutcome(OutcomeFromChooserEvent(event)); PostErrorCallback(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); break; case BluetoothChooser::Event::SELECTED: RecordNumOfDevices(options_->accept_all_devices, device_ids_.size()); PostSuccessCallback(device_address); break; } chooser_.reset(); } 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: 1 Example 2: Code: static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu) { if (ple_gap) shrink_ple_window(vcpu); } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[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: UpdatedExtensionPermissionsInfo::UpdatedExtensionPermissionsInfo( const Extension* extension, const PermissionSet* permissions, Reason reason) : reason(reason), extension(extension), permissions(permissions) {} Commit Message: Tighten restrictions on hosted apps calling extension APIs Only allow component apps to make any API calls, and for them only allow the namespaces they explicitly have permission for (plus chrome.test - I need to see if I can rework some WebStore tests to remove even this). BUG=172369 Review URL: https://chromiumcodereview.appspot.com/12095095 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180426 0039d316-1c4b-4281-b951-d872f2087c98 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: pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision, char *errbuf, int *err) { bpf_u_int32 magic_int; size_t amt_read; bpf_u_int32 total_length; bpf_u_int32 byte_order_magic; struct block_header *bhdrp; struct section_header_block *shbp; pcap_t *p; int swapped = 0; struct pcap_ng_sf *ps; int status; struct block_cursor cursor; struct interface_description_block *idbp; /* * Assume no read errors. */ *err = 0; /* * Check whether the first 4 bytes of the file are the block * type for a pcapng savefile. */ memcpy(&magic_int, magic, sizeof(magic_int)); if (magic_int != BT_SHB) { /* * XXX - check whether this looks like what the block * type would be after being munged by mapping between * UN*X and DOS/Windows text file format and, if it * does, look for the byte-order magic number in * the appropriate place and, if we find it, report * this as possibly being a pcapng file transferred * between UN*X and Windows in text file format? */ return (NULL); /* nope */ } /* * OK, they are. However, that's just \n\r\r\n, so it could, * conceivably, be an ordinary text file. * * It could not, however, conceivably be any other type of * capture file, so we can read the rest of the putative * Section Header Block; put the block type in the common * header, read the rest of the common header and the * fixed-length portion of the SHB, and look for the byte-order * magic value. */ amt_read = fread(&total_length, 1, sizeof(total_length), fp); if (amt_read < sizeof(total_length)) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); *err = 1; return (NULL); /* fail */ } /* * Possibly a weird short text file, so just say * "not pcapng". */ return (NULL); } amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp); if (amt_read < sizeof(byte_order_magic)) { if (ferror(fp)) { pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno, "error reading dump file"); *err = 1; return (NULL); /* fail */ } /* * Possibly a weird short text file, so just say * "not pcapng". */ return (NULL); } if (byte_order_magic != BYTE_ORDER_MAGIC) { byte_order_magic = SWAPLONG(byte_order_magic); if (byte_order_magic != BYTE_ORDER_MAGIC) { /* * Not a pcapng file. */ return (NULL); } swapped = 1; total_length = SWAPLONG(total_length); } /* * Check the sanity of the total length. */ if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Section Header Block in pcapng dump file has a length of %u < %" PRIsize, total_length, sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer)); *err = 1; return (NULL); } /* * Make sure it's not too big. */ if (total_length > INITIAL_MAX_BLOCKSIZE) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "pcapng block size %u > maximum %u", total_length, INITIAL_MAX_BLOCKSIZE); *err = 1; return (NULL); } /* * OK, this is a good pcapng file. * Allocate a pcap_t for it. */ p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf)); if (p == NULL) { /* Allocation failed. */ *err = 1; return (NULL); } p->swapped = swapped; ps = p->priv; /* * What precision does the user want? */ switch (precision) { case PCAP_TSTAMP_PRECISION_MICRO: ps->user_tsresol = 1000000; break; case PCAP_TSTAMP_PRECISION_NANO: ps->user_tsresol = 1000000000; break; default: pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "unknown time stamp resolution %u", precision); free(p); *err = 1; return (NULL); } p->opt.tstamp_precision = precision; /* * Allocate a buffer into which to read blocks. We default to * the maximum of: * * the total length of the SHB for which we read the header; * * 2K, which should be more than large enough for an Enhanced * Packet Block containing a full-size Ethernet frame, and * leaving room for some options. * * If we find a bigger block, we reallocate the buffer, up to * the maximum size. We start out with a maximum size of * INITIAL_MAX_BLOCKSIZE; if we see any link-layer header types * with a maximum snapshot that results in a larger maximum * block length, we boost the maximum. */ p->bufsize = 2048; if (p->bufsize < total_length) p->bufsize = total_length; p->buffer = malloc(p->bufsize); if (p->buffer == NULL) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory"); free(p); *err = 1; return (NULL); } ps->max_blocksize = INITIAL_MAX_BLOCKSIZE; /* * Copy the stuff we've read to the buffer, and read the rest * of the SHB. */ bhdrp = (struct block_header *)p->buffer; shbp = (struct section_header_block *)((u_char *)p->buffer + sizeof(struct block_header)); bhdrp->block_type = magic_int; bhdrp->total_length = total_length; shbp->byte_order_magic = byte_order_magic; if (read_bytes(fp, (u_char *)p->buffer + (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)), total_length - (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)), 1, errbuf) == -1) goto fail; if (p->swapped) { /* * Byte-swap the fields we've read. */ shbp->major_version = SWAPSHORT(shbp->major_version); shbp->minor_version = SWAPSHORT(shbp->minor_version); /* * XXX - we don't care about the section length. */ } /* currently only SHB version 1.0 is supported */ if (! (shbp->major_version == PCAP_NG_VERSION_MAJOR && shbp->minor_version == PCAP_NG_VERSION_MINOR)) { pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "unsupported pcapng savefile version %u.%u", shbp->major_version, shbp->minor_version); goto fail; } p->version_major = shbp->major_version; p->version_minor = shbp->minor_version; /* * Save the time stamp resolution the user requested. */ p->opt.tstamp_precision = precision; /* * Now start looking for an Interface Description Block. */ for (;;) { /* * Read the next block. */ status = read_block(fp, p, &cursor, errbuf); if (status == 0) { /* EOF - no IDB in this file */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "the capture file has no Interface Description Blocks"); goto fail; } if (status == -1) goto fail; /* error */ switch (cursor.block_type) { case BT_IDB: /* * Get a pointer to the fixed-length portion of the * IDB. */ idbp = get_from_block_data(&cursor, sizeof(*idbp), errbuf); if (idbp == NULL) goto fail; /* error */ /* * Byte-swap it if necessary. */ if (p->swapped) { idbp->linktype = SWAPSHORT(idbp->linktype); idbp->snaplen = SWAPLONG(idbp->snaplen); } /* * Try to add this interface. */ if (!add_interface(p, &cursor, errbuf)) goto fail; goto done; case BT_EPB: case BT_SPB: case BT_PB: /* * Saw a packet before we saw any IDBs. That's * not valid, as we don't know what link-layer * encapsulation the packet has. */ pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "the capture file has a packet block before any Interface Description Blocks"); goto fail; default: /* * Just ignore it. */ break; } } done: p->tzoff = 0; /* XXX - not used in pcap */ p->linktype = linktype_to_dlt(idbp->linktype); p->snapshot = pcap_adjust_snapshot(p->linktype, idbp->snaplen); p->linktype_ext = 0; /* * If the maximum block size for a packet with the maximum * snapshot length for this DLT_ is bigger than the current * maximum block size, increase the maximum. */ if (MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)) > ps->max_blocksize) ps->max_blocksize = MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)); p->next_packet_op = pcap_ng_next_packet; p->cleanup_op = pcap_ng_cleanup; return (p); fail: free(ps->ifaces); free(p->buffer); free(p); *err = 1; return (NULL); } Commit Message: do sanity checks on PHB header length before allocating memory. There was no fault; but doing the check results in a more consistent error CWE ID: CWE-20 Target: 1 Example 2: Code: pdf14_forward_device_procs(gx_device * dev) { gx_device_forward * pdev = (gx_device_forward *)dev; /* * We are using gx_device_forward_fill_in_procs to set the various procs. * This will ensure that any new device procs are also set. However that * routine only changes procs which are NULL. Thus we start by setting all * procs to NULL. */ memset(&(pdev->procs), 0, size_of(pdev->procs)); gx_device_forward_fill_in_procs(pdev); /* * gx_device_forward_fill_in_procs does not forward all procs. * Set the remainding procs to also forward. */ set_dev_proc(dev, close_device, gx_forward_close_device); set_dev_proc(dev, fill_rectangle, gx_forward_fill_rectangle); set_dev_proc(dev, fill_rectangle_hl_color, gx_forward_fill_rectangle_hl_color); set_dev_proc(dev, tile_rectangle, gx_forward_tile_rectangle); set_dev_proc(dev, copy_mono, gx_forward_copy_mono); set_dev_proc(dev, copy_color, gx_forward_copy_color); set_dev_proc(dev, get_page_device, gx_forward_get_page_device); set_dev_proc(dev, strip_tile_rectangle, gx_forward_strip_tile_rectangle); set_dev_proc(dev, copy_alpha, gx_forward_copy_alpha); set_dev_proc(dev, get_profile, gx_forward_get_profile); set_dev_proc(dev, set_graphics_type_tag, gx_forward_set_graphics_type_tag); /* These are forwarding devices with minor tweaks. */ set_dev_proc(dev, open_device, pdf14_forward_open_device); set_dev_proc(dev, put_params, pdf14_forward_put_params); } 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: static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } Commit Message: ccpp: open file for dump_fd_info with O_EXCL To avoid possible races. Related: #1211835 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-59 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: base::ProcessHandle StartProcessWithAccess(CommandLine* cmd_line, const FilePath& exposed_dir) { const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); content::ProcessType type; std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType); if (type_str == switches::kRendererProcess) { type = content::PROCESS_TYPE_RENDERER; } else if (type_str == switches::kPluginProcess) { type = content::PROCESS_TYPE_PLUGIN; } else if (type_str == switches::kWorkerProcess) { type = content::PROCESS_TYPE_WORKER; } else if (type_str == switches::kNaClLoaderProcess) { type = content::PROCESS_TYPE_NACL_LOADER; } else if (type_str == switches::kUtilityProcess) { type = content::PROCESS_TYPE_UTILITY; } else if (type_str == switches::kNaClBrokerProcess) { type = content::PROCESS_TYPE_NACL_BROKER; } else if (type_str == switches::kGpuProcess) { type = content::PROCESS_TYPE_GPU; } else if (type_str == switches::kPpapiPluginProcess) { type = content::PROCESS_TYPE_PPAPI_PLUGIN; } else if (type_str == switches::kPpapiBrokerProcess) { type = content::PROCESS_TYPE_PPAPI_BROKER; } else { NOTREACHED(); return 0; } TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str); bool in_sandbox = (type != content::PROCESS_TYPE_NACL_BROKER) && (type != content::PROCESS_TYPE_PLUGIN) && (type != content::PROCESS_TYPE_PPAPI_BROKER); if ((type == content::PROCESS_TYPE_GPU) && (cmd_line->HasSwitch(switches::kDisableGpuSandbox))) { in_sandbox = false; DVLOG(1) << "GPU sandbox is disabled"; } if (browser_command_line.HasSwitch(switches::kNoSandbox) || cmd_line->HasSwitch(switches::kNoSandbox)) { in_sandbox = false; } #if !defined (GOOGLE_CHROME_BUILD) if (browser_command_line.HasSwitch(switches::kInProcessPlugins)) { in_sandbox = false; } #endif if (!browser_command_line.HasSwitch(switches::kDisable3DAPIs) && !browser_command_line.HasSwitch(switches::kDisableExperimentalWebGL) && browser_command_line.HasSwitch(switches::kInProcessWebGL)) { in_sandbox = false; } if (browser_command_line.HasSwitch(switches::kChromeFrame)) { if (!cmd_line->HasSwitch(switches::kChromeFrame)) { cmd_line->AppendSwitch(switches::kChromeFrame); } } bool child_needs_help = DebugFlags::ProcessDebugFlags(cmd_line, type, in_sandbox); cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", type)); sandbox::ResultCode result; base::win::ScopedProcessInformation target; sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy(); #if !defined(NACL_WIN64) // We don't need this code on win nacl64. if (type == content::PROCESS_TYPE_PLUGIN && !browser_command_line.HasSwitch(switches::kNoSandbox) && content::GetContentClient()->SandboxPlugin(cmd_line, policy)) { in_sandbox = true; } #endif if (!in_sandbox) { policy->Release(); base::ProcessHandle process = 0; base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process); return process; } if (type == content::PROCESS_TYPE_PLUGIN) { AddGenericDllEvictionPolicy(policy); AddPluginDllEvictionPolicy(policy); } else if (type == content::PROCESS_TYPE_GPU) { if (!AddPolicyForGPU(cmd_line, policy)) return 0; } else { if (!AddPolicyForRenderer(policy)) return 0; if (type == content::PROCESS_TYPE_RENDERER || type == content::PROCESS_TYPE_WORKER) { AddBaseHandleClosePolicy(policy); } else if (type == content::PROCESS_TYPE_PPAPI_PLUGIN) { if (!AddPolicyForPepperPlugin(policy)) return 0; } if (type_str != switches::kRendererProcess) { cmd_line->AppendSwitchASCII("ignored", " --type=renderer "); } } if (!exposed_dir.empty()) { result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, sandbox::TargetPolicy::FILES_ALLOW_ANY, exposed_dir.value().c_str()); if (result != sandbox::SBOX_ALL_OK) return 0; FilePath exposed_files = exposed_dir.AppendASCII("*"); result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, sandbox::TargetPolicy::FILES_ALLOW_ANY, exposed_files.value().c_str()); if (result != sandbox::SBOX_ALL_OK) return 0; } if (!AddGenericPolicy(policy)) { NOTREACHED(); return 0; } TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0); result = g_broker_services->SpawnTarget( cmd_line->GetProgram().value().c_str(), cmd_line->GetCommandLineString().c_str(), policy, target.Receive()); policy->Release(); TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0); if (sandbox::SBOX_ALL_OK != result) { DLOG(ERROR) << "Failed to launch process. Error: " << result; return 0; } if (type == content::PROCESS_TYPE_NACL_LOADER && (base::win::OSInfo::GetInstance()->wow64_status() == base::win::OSInfo::WOW64_DISABLED)) { const SIZE_T kOneGigabyte = 1 << 30; void* nacl_mem = VirtualAllocEx(target.process_handle(), NULL, kOneGigabyte, MEM_RESERVE, PAGE_NOACCESS); if (!nacl_mem) { DLOG(WARNING) << "Failed to reserve address space for Native Client"; } } ResumeThread(target.thread_handle()); if (child_needs_help) base::debug::SpawnDebuggerOnProcess(target.process_id()); return target.TakeProcessHandle(); } 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: 1 Example 2: Code: copy_shmid_from_user(struct shmid64_ds *out, void __user *buf, int version) { switch (version) { case IPC_64: if (copy_from_user(out, buf, sizeof(*out))) return -EFAULT; return 0; case IPC_OLD: { struct shmid_ds tbuf_old; if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old))) return -EFAULT; out->shm_perm.uid = tbuf_old.shm_perm.uid; out->shm_perm.gid = tbuf_old.shm_perm.gid; out->shm_perm.mode = tbuf_old.shm_perm.mode; return 0; } default: return -EINVAL; } } Commit Message: Initialize msg/shm IPC objects before doing ipc_addid() As reported by Dmitry Vyukov, we really shouldn't do ipc_addid() before having initialized the IPC object state. Yes, we initialize the IPC object in a locked state, but with all the lockless RCU lookup work, that IPC object lock no longer means that the state cannot be seen. We already did this for the IPC semaphore code (see commit e8577d1f0329: "ipc/sem.c: fully initialize sem_array before making it visible") but we clearly forgot about msg and shm. Reported-by: Dmitry Vyukov <[email protected]> Cc: Manfred Spraul <[email protected]> Cc: Davidlohr Bueso <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[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 ieee754dp fpemu_dp_rsqrt(ieee754dp d) { return ieee754dp_div(ieee754dp_one(0), ieee754dp_sqrt(d)); } 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: void ExtensionTtsPlatformImpl::clear_error() { error_ = std::string(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: void btrfs_inherit_iflags(struct inode *inode, struct inode *dir) { unsigned int flags; if (!dir) return; flags = BTRFS_I(dir)->flags; if (flags & BTRFS_INODE_NOCOMPRESS) { BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS; BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS; } else if (flags & BTRFS_INODE_COMPRESS) { BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS; BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS; } if (flags & BTRFS_INODE_NODATACOW) BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW; btrfs_update_iflags(inode); } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <[email protected]> Reported-by: Pascal Junod <[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: void InspectorNetworkAgent::DidBlockRequest( ExecutionContext* execution_context, const ResourceRequest& request, DocumentLoader* loader, const FetchInitiatorInfo& initiator_info, ResourceRequestBlockedReason reason) { unsigned long identifier = CreateUniqueIdentifier(); WillSendRequestInternal(execution_context, identifier, loader, request, ResourceResponse(), initiator_info); String request_id = IdentifiersFactory::RequestId(identifier); String protocol_reason = BuildBlockedReason(reason); GetFrontend()->loadingFailed( request_id, MonotonicallyIncreasingTime(), InspectorPageAgent::ResourceTypeJson( resources_data_->GetResourceType(request_id)), String(), false, protocol_reason); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119 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 bmdma_prepare_buf(IDEDMA *dma, int is_write) { BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); IDEState *s = bmdma_active_if(bm); uint32_t size; } prd; Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: static int mp_wait_modem_status(struct sb_uart_state *state, unsigned long arg) { struct sb_uart_port *port = state->port; DECLARE_WAITQUEUE(wait, current); struct sb_uart_icount cprev, cnow; int ret; spin_lock_irq(&port->lock); memcpy(&cprev, &port->icount, sizeof(struct sb_uart_icount)); port->ops->enable_ms(port); spin_unlock_irq(&port->lock); add_wait_queue(&state->info->delta_msr_wait, &wait); for (;;) { spin_lock_irq(&port->lock); memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount)); spin_unlock_irq(&port->lock); set_current_state(TASK_INTERRUPTIBLE); if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) || ((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) || ((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) || ((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) { ret = 0; break; } schedule(); if (signal_pending(current)) { ret = -ERESTARTSYS; break; } cprev = cnow; } current->state = TASK_RUNNING; remove_wait_queue(&state->info->delta_msr_wait, &wait); return ret; } Commit Message: Staging: sb105x: info leak in mp_get_count() The icount.reserved[] array isn't initialized so it leaks stack information to userspace. Reported-by: Nico Golde <[email protected]> Reported-by: Fabian Yamaguchi <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[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: base::PlatformFileError ModifyCacheState( const FilePath& source_path, const FilePath& dest_path, GDataCache::FileOperationType file_operation_type, const FilePath& symlink_path, bool create_symlink) { if (source_path != dest_path) { bool success = false; if (file_operation_type == GDataCache::FILE_OPERATION_MOVE) success = file_util::Move(source_path, dest_path); else if (file_operation_type == GDataCache::FILE_OPERATION_COPY) success = file_util::CopyFile(source_path, dest_path); if (!success) { base::PlatformFileError error = SystemToPlatformError(errno); PLOG(ERROR) << "Error " << (file_operation_type == GDataCache::FILE_OPERATION_MOVE ? "moving " : "copying ") << source_path.value() << " to " << dest_path.value(); return error; } else { DVLOG(1) << (file_operation_type == GDataCache::FILE_OPERATION_MOVE ? "Moved " : "Copied ") << source_path.value() << " to " << dest_path.value(); } } else { DVLOG(1) << "No need to move file: source = destination"; } if (symlink_path.empty()) return base::PLATFORM_FILE_OK; bool deleted = util::DeleteSymlink(symlink_path); if (deleted) { DVLOG(1) << "Deleted symlink " << symlink_path.value(); } else { if (errno != ENOENT) PLOG(WARNING) << "Error deleting symlink " << symlink_path.value(); } if (!create_symlink) return base::PLATFORM_FILE_OK; if (!file_util::CreateSymbolicLink(dest_path, symlink_path)) { base::PlatformFileError error = SystemToPlatformError(errno); PLOG(ERROR) << "Error creating symlink " << symlink_path.value() << " for " << dest_path.value(); return error; } else { DVLOG(1) << "Created symlink " << symlink_path.value() << " to " << dest_path.value(); } return base::PLATFORM_FILE_OK; } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 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: const BlockEntry* Cluster::GetEntry(const CuePoint& cp, const CuePoint::TrackPosition& tp) const { assert(m_pSegment); #if 0 LoadBlockEntries(); if (m_entries == NULL) return NULL; const long long count = m_entries_count; if (count <= 0) return NULL; const long long tc = cp.GetTimeCode(); if ((tp.m_block > 0) && (tp.m_block <= count)) { const size_t block = static_cast<size_t>(tp.m_block); const size_t index = block - 1; const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if ((pBlock->GetTrackNumber() == tp.m_track) && (pBlock->GetTimeCode(this) == tc)) { return pEntry; } } const BlockEntry* const* i = m_entries; const BlockEntry* const* const j = i + count; while (i != j) { #ifdef _DEBUG const ptrdiff_t idx = i - m_entries; idx; #endif const BlockEntry* const pEntry = *i++; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != tp.m_track) continue; const long long tc_ = pBlock->GetTimeCode(this); assert(tc_ >= 0); if (tc_ < tc) continue; if (tc_ > tc) return NULL; const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast<long>(tp.m_track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return NULL; const long long type = pTrack->GetType(); if (type == 2) //audio return pEntry; if (type != 1) //not video return NULL; if (!pBlock->IsKey()) return NULL; return pEntry; } return NULL; #else const long long tc = cp.GetTimeCode(); if (tp.m_block > 0) { const long block = static_cast<long>(tp.m_block); const long index = block - 1; while (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) // TODO: can this happen? return NULL; if (status > 0) // nothing remains to be parsed return NULL; } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if ((pBlock->GetTrackNumber() == tp.m_track) && (pBlock->GetTimeCode(this) == tc)) { return pEntry; } } long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) // TODO: can this happen? return NULL; if (status > 0) // nothing remains to be parsed return NULL; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != tp.m_track) { ++index; continue; } const long long tc_ = pBlock->GetTimeCode(this); if (tc_ < tc) { ++index; continue; } if (tc_ > tc) return NULL; const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast<long>(tp.m_track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return NULL; const long long type = pTrack->GetType(); if (type == 2) // audio return pEntry; if (type != 1) // not video return NULL; if (!pBlock->IsKey()) return NULL; return pEntry; } #endif } 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 void nfs_increment_seqid(int status, struct nfs_seqid *seqid) { BUG_ON(list_first_entry(&seqid->sequence->sequence->list, struct nfs_seqid, list) != seqid); switch (status) { case 0: break; case -NFS4ERR_BAD_SEQID: if (seqid->sequence->flags & NFS_SEQID_CONFIRMED) return; printk(KERN_WARNING "NFS: v4 server returned a bad" " sequence-id error on an" " unconfirmed sequence %p!\n", seqid->sequence); case -NFS4ERR_STALE_CLIENTID: case -NFS4ERR_STALE_STATEID: case -NFS4ERR_BAD_STATEID: case -NFS4ERR_BADXDR: case -NFS4ERR_RESOURCE: case -NFS4ERR_NOFILEHANDLE: /* Non-seqid mutating errors */ return; }; /* * Note: no locking needed as we are guaranteed to be first * on the sequence list */ seqid->sequence->counter++; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[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: bool Extension::IsSyncable() const { bool is_syncable = (location() == Manifest::INTERNAL && !was_installed_by_default()); is_syncable |= (id() == extension_misc::kWebStoreAppId); return is_syncable; } Commit Message: Tighten restrictions on hosted apps calling extension APIs Only allow component apps to make any API calls, and for them only allow the namespaces they explicitly have permission for (plus chrome.test - I need to see if I can rework some WebStore tests to remove even this). BUG=172369 Review URL: https://chromiumcodereview.appspot.com/12095095 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180426 0039d316-1c4b-4281-b951-d872f2087c98 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: static void Sp_match(js_State *J) { js_Regexp *re; const char *text; int len; const char *a, *b, *c, *e; Resub m; text = checkstring(J, 0); if (js_isregexp(J, 1)) js_copy(J, 1); else if (js_isundefined(J, 1)) js_newregexp(J, "", 0); else js_newregexp(J, js_tostring(J, 1), 0); re = js_toregexp(J, -1); if (!(re->flags & JS_REGEXP_G)) { js_RegExp_prototype_exec(J, re, text); return; } re->last = 0; js_newarray(J); len = 0; a = text; e = text + strlen(text); while (a <= e) { if (js_regexec(re->prog, a, &m, a > text ? REG_NOTBOL : 0)) break; b = m.sub[0].sp; c = m.sub[0].ep; js_pushlstring(J, b, c - b); js_setindex(J, -2, len++); a = c; if (c - b == 0) ++a; } if (len == 0) { js_pop(J, 1); js_pushnull(J); } } Commit Message: Bug 700937: Limit recursion in regexp matcher. Also handle negative return code as an error in the JS bindings. CWE ID: CWE-400 Target: 1 Example 2: Code: static void pdf_run_Tr(fz_context *ctx, pdf_processor *proc, int render) { pdf_run_processor *pr = (pdf_run_processor *)proc; pdf_gstate *gstate = pr->gstate + pr->gtop; gstate->text.render = render; } 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: feed_table(struct table *tbl, char *line, struct table_mode *mode, int width, int internal) { int i; char *p; Str tmp; struct table_linfo *linfo = &tbl->linfo; if (*line == '<' && line[1] && REALLY_THE_BEGINNING_OF_A_TAG(line)) { struct parsed_tag *tag; p = line; tag = parse_tag(&p, internal); if (tag) { switch (feed_table_tag(tbl, line, mode, width, tag)) { case TAG_ACTION_NONE: return -1; case TAG_ACTION_N_TABLE: return 0; case TAG_ACTION_TABLE: return 1; case TAG_ACTION_PLAIN: break; case TAG_ACTION_FEED: default: if (parsedtag_need_reconstruct(tag)) line = parsedtag2str(tag)->ptr; } } else { if (!(mode->pre_mode & (TBLM_PLAIN | TBLM_INTXTA | TBLM_INSELECT | TBLM_SCRIPT | TBLM_STYLE))) return -1; } } else { if (mode->pre_mode & (TBLM_DEL | TBLM_S)) return -1; } if (mode->caption) { Strcat_charp(tbl->caption, line); return -1; } if (mode->pre_mode & TBLM_SCRIPT) return -1; if (mode->pre_mode & TBLM_STYLE) return -1; if (mode->pre_mode & TBLM_INTXTA) { feed_textarea(line); return -1; } if (mode->pre_mode & TBLM_INSELECT) { feed_select(line); return -1; } if (!(mode->pre_mode & TBLM_PLAIN) && !(*line == '<' && line[strlen(line) - 1] == '>') && strchr(line, '&') != NULL) { tmp = Strnew(); for (p = line; *p;) { char *q, *r; if (*p == '&') { if (!strncasecmp(p, "&amp;", 5) || !strncasecmp(p, "&gt;", 4) || !strncasecmp(p, "&lt;", 4)) { /* do not convert */ Strcat_char(tmp, *p); p++; } else { int ec; q = p; switch (ec = getescapechar(&p)) { case '<': Strcat_charp(tmp, "&lt;"); break; case '>': Strcat_charp(tmp, "&gt;"); break; case '&': Strcat_charp(tmp, "&amp;"); break; case '\r': Strcat_char(tmp, '\n'); break; default: r = conv_entity(ec); if (r != NULL && strlen(r) == 1 && ec == (unsigned char)*r) { Strcat_char(tmp, *r); break; } case -1: Strcat_char(tmp, *q); p = q + 1; break; } } } else { Strcat_char(tmp, *p); p++; } } line = tmp->ptr; } if (!(mode->pre_mode & (TBLM_SPECIAL & ~TBLM_NOBR))) { if (!(tbl->flag & TBL_IN_COL) || linfo->prev_spaces != 0) while (IS_SPACE(*line)) line++; if (*line == '\0') return -1; check_rowcol(tbl, mode); if (mode->pre_mode & TBLM_NOBR && mode->nobr_offset < 0) mode->nobr_offset = tbl->tabcontentssize; /* count of number of spaces skipped in normal mode */ i = skip_space(tbl, line, linfo, !(mode->pre_mode & TBLM_NOBR)); addcontentssize(tbl, visible_length(line) - i); setwidth(tbl, mode); pushdata(tbl, tbl->row, tbl->col, line); } else if (mode->pre_mode & TBLM_PRE_INT) { check_rowcol(tbl, mode); if (mode->nobr_offset < 0) mode->nobr_offset = tbl->tabcontentssize; addcontentssize(tbl, maximum_visible_length(line, tbl->tabcontentssize)); setwidth(tbl, mode); pushdata(tbl, tbl->row, tbl->col, line); } else { /* <pre> mode or something like it */ check_rowcol(tbl, mode); while (*line) { int nl = FALSE; if ((p = strchr(line, '\r')) || (p = strchr(line, '\n'))) { if (*p == '\r' && p[1] == '\n') p++; if (p[1]) { p++; tmp = Strnew_charp_n(line, p - line); line = p; p = tmp->ptr; } else { p = line; line = ""; } nl = TRUE; } else { p = line; line = ""; } if (mode->pre_mode & TBLM_PLAIN) i = maximum_visible_length_plain(p, tbl->tabcontentssize); else i = maximum_visible_length(p, tbl->tabcontentssize); addcontentssize(tbl, i); setwidth(tbl, mode); if (nl) clearcontentssize(tbl, mode); pushdata(tbl, tbl->row, tbl->col, p); } } return -1; } Commit Message: Prevent negative indent value in feed_table_block_tag() Bug-Debian: https://github.com/tats/w3m/issues/88 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: bool BluetoothDeviceChromeOS::RunPairingCallbacks(Status status) { if (!agent_.get()) return false; bool callback_run = false; if (!pincode_callback_.is_null()) { pincode_callback_.Run(status, ""); pincode_callback_.Reset(); callback_run = true; } if (!passkey_callback_.is_null()) { passkey_callback_.Run(status, 0); passkey_callback_.Reset(); callback_run = true; } if (!confirmation_callback_.is_null()) { confirmation_callback_.Run(status); confirmation_callback_.Reset(); callback_run = true; } return callback_run; } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc, struct sshmac *mac, size_t mac_already, u_int discard) { struct session_state *state = ssh->state; int r; if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) { if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0) return r; return SSH_ERR_MAC_INVALID; } /* * Record number of bytes over which the mac has already * been computed in order to minimize timing attacks. */ if (mac && mac->enabled) { state->packet_discard_mac = mac; state->packet_discard_mac_already = mac_already; } if (sshbuf_len(state->input) >= discard) return ssh_packet_stop_discard(ssh); state->packet_discard = discard - sshbuf_len(state->input); return 0; } Commit Message: 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: xmlFatalErrMsgInt(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *msg, int val) { if ((ctxt != NULL) && (ctxt->disableSAX != 0) && (ctxt->instate == XML_PARSER_EOF)) return; if (ctxt != NULL) ctxt->errNo = error; __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_PARSER, error, XML_ERR_FATAL, NULL, 0, NULL, NULL, NULL, val, 0, msg, val); if (ctxt != NULL) { ctxt->wellFormed = 0; if (ctxt->recovery == 0) ctxt->disableSAX = 1; } } Commit Message: Detect infinite recursion in parameter entities When expanding a parameter entity in a DTD, infinite recursion could lead to an infinite loop or memory exhaustion. Thanks to Wei Lei for the first of many reports. Fixes bug 759579. 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: bool CheckClientDownloadRequest::ShouldUploadForMalwareScan( DownloadCheckResultReason reason) { if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads)) return false; if (reason != DownloadCheckResultReason::REASON_DOWNLOAD_SAFE && reason != DownloadCheckResultReason::REASON_DOWNLOAD_UNCOMMON && reason != DownloadCheckResultReason::REASON_VERDICT_UNKNOWN) return false; content::BrowserContext* browser_context = content::DownloadItemUtils::GetBrowserContext(item_); if (!browser_context) return false; Profile* profile = Profile::FromBrowserContext(browser_context); if (!profile) return false; int send_files_for_malware_check = profile->GetPrefs()->GetInteger( prefs::kSafeBrowsingSendFilesForMalwareCheck); if (send_files_for_malware_check != SendFilesForMalwareCheckValues::SEND_DOWNLOADS && send_files_for_malware_check != SendFilesForMalwareCheckValues::SEND_UPLOADS_AND_DOWNLOADS) return false; return !policy::BrowserDMTokenStorage::Get()->RetrieveDMToken().empty(); } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <[email protected]> Reviewed-by: Tien Mai <[email protected]> Reviewed-by: Daniel Rubery <[email protected]> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20 Target: 1 Example 2: Code: void V8TestObject::Float32ArrayMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_float32ArrayMethod"); test_object_v8_internal::Float32ArrayMethodMethod(info); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <[email protected]> Commit-Queue: Yuki Shiino <[email protected]> Cr-Commit-Position: refs/heads/master@{#718676} 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 int futex_unlock_pi(u32 __user *uaddr, int fshared) { struct futex_hash_bucket *hb; struct futex_q *this, *next; u32 uval; struct plist_head *head; union futex_key key = FUTEX_KEY_INIT; int ret; retry: if (get_user(uval, uaddr)) return -EFAULT; /* * We release only a lock we actually own: */ if ((uval & FUTEX_TID_MASK) != task_pid_vnr(current)) return -EPERM; ret = get_futex_key(uaddr, fshared, &key); if (unlikely(ret != 0)) goto out; hb = hash_futex(&key); spin_lock(&hb->lock); /* * To avoid races, try to do the TID -> 0 atomic transition * again. If it succeeds then we can return without waking * anyone else up: */ if (!(uval & FUTEX_OWNER_DIED)) uval = cmpxchg_futex_value_locked(uaddr, task_pid_vnr(current), 0); if (unlikely(uval == -EFAULT)) goto pi_faulted; /* * Rare case: we managed to release the lock atomically, * no need to wake anyone else up: */ if (unlikely(uval == task_pid_vnr(current))) goto out_unlock; /* * Ok, other tasks may need to be woken up - check waiters * and do the wakeup if necessary: */ head = &hb->chain; plist_for_each_entry_safe(this, next, head, list) { if (!match_futex (&this->key, &key)) continue; ret = wake_futex_pi(uaddr, uval, this); /* * The atomic access to the futex value * generated a pagefault, so retry the * user-access and the wakeup: */ if (ret == -EFAULT) goto pi_faulted; goto out_unlock; } /* * No waiters - kernel unlocks the futex: */ if (!(uval & FUTEX_OWNER_DIED)) { ret = unlock_futex_pi(uaddr, uval); if (ret == -EFAULT) goto pi_faulted; } out_unlock: spin_unlock(&hb->lock); put_futex_key(fshared, &key); out: return ret; pi_faulted: spin_unlock(&hb->lock); put_futex_key(fshared, &key); ret = fault_in_user_writeable(uaddr); if (!ret) goto retry; return ret; } Commit Message: futex: Fix errors in nested key ref-counting futex_wait() is leaking key references due to futex_wait_setup() acquiring an additional reference via the queue_lock() routine. The nested key ref-counting has been masking bugs and complicating code analysis. queue_lock() is only called with a previously ref-counted key, so remove the additional ref-counting from the queue_(un)lock() functions. Also futex_wait_requeue_pi() drops one key reference too many in unqueue_me_pi(). Remove the key reference handling from unqueue_me_pi(). This was paired with a queue_lock() in futex_lock_pi(), so the count remains unchanged. Document remaining nested key ref-counting sites. Signed-off-by: Darren Hart <[email protected]> Reported-and-tested-by: Matthieu Fertré<[email protected]> Reported-by: Louis Rilling<[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Eric Dumazet <[email protected]> Cc: John Kacur <[email protected]> Cc: Rusty Russell <[email protected]> LKML-Reference: <[email protected]> Signed-off-by: Thomas Gleixner <[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: static int do_devinfo_ioctl(struct comedi_device *dev, struct comedi_devinfo __user *arg, struct file *file) { struct comedi_devinfo devinfo; const unsigned minor = iminor(file->f_dentry->d_inode); struct comedi_device_file_info *dev_file_info = comedi_get_device_file_info(minor); struct comedi_subdevice *read_subdev = comedi_get_read_subdevice(dev_file_info); struct comedi_subdevice *write_subdev = comedi_get_write_subdevice(dev_file_info); memset(&devinfo, 0, sizeof(devinfo)); /* fill devinfo structure */ devinfo.version_code = COMEDI_VERSION_CODE; devinfo.n_subdevs = dev->n_subdevices; memcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN); memcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN); if (read_subdev) devinfo.read_subdevice = read_subdev - dev->subdevices; else devinfo.read_subdevice = -1; if (write_subdev) devinfo.write_subdevice = write_subdev - dev->subdevices; else devinfo.write_subdevice = -1; if (copy_to_user(arg, &devinfo, sizeof(struct comedi_devinfo))) return -EFAULT; return 0; } Commit Message: staging: comedi: fix infoleak to userspace driver_name and board_name are pointers to strings, not buffers of size COMEDI_NAMELEN. Copying COMEDI_NAMELEN bytes of a string containing less than COMEDI_NAMELEN-1 bytes would leak some unrelated bytes. Signed-off-by: Vasiliy Kulikov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: static void nlmsvc_release_block(struct nlm_block *block) { if (block != NULL) kref_put_mutex(&block->b_count, nlmsvc_free_block, &block->b_file->f_mutex); } 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: static int em_imul_3op(struct x86_emulate_ctxt *ctxt) { ctxt->dst.val = ctxt->src2.val; return fastop(ctxt, em_imul); } Commit Message: KVM: emulate: avoid accessing NULL ctxt->memopp A failure to decode the instruction can cause a NULL pointer access. This is fixed simply by moving the "done" label as close as possible to the return. This fixes CVE-2014-8481. Reported-by: Andy Lutomirski <[email protected]> Cc: [email protected] Fixes: 41061cdb98a0bec464278b4db8e894a3121671f5 Signed-off-by: Paolo Bonzini <[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 ssize_t cm_write(struct file *file, const char __user * user_buf, size_t count, loff_t *ppos) { static char *buf; static u32 max_size; static u32 uncopied_bytes; struct acpi_table_header table; acpi_status status; if (!(*ppos)) { /* parse the table header to get the table length */ if (count <= sizeof(struct acpi_table_header)) return -EINVAL; if (copy_from_user(&table, user_buf, sizeof(struct acpi_table_header))) return -EFAULT; uncopied_bytes = max_size = table.length; buf = kzalloc(max_size, GFP_KERNEL); if (!buf) return -ENOMEM; } if (buf == NULL) return -EINVAL; if ((*ppos > max_size) || (*ppos + count > max_size) || (*ppos + count < count) || (count > uncopied_bytes)) return -EINVAL; if (copy_from_user(buf + (*ppos), user_buf, count)) { kfree(buf); buf = NULL; return -EFAULT; } uncopied_bytes -= count; *ppos += count; if (!uncopied_bytes) { status = acpi_install_method(buf); kfree(buf); buf = NULL; if (ACPI_FAILURE(status)) return -EINVAL; add_taint(TAINT_OVERRIDDEN_ACPI_TABLE); } return count; } Commit Message: ACPI: Split out custom_method functionality into an own driver With /sys/kernel/debug/acpi/custom_method root can write to arbitrary memory and increase his priveleges, even if these are restricted. -> Make this an own debug .config option and warn about the security issue in the config description. -> Still keep acpi/debugfs.c which now only creates an empty /sys/kernel/debug/acpi directory. There might be other users of it later. Signed-off-by: Thomas Renninger <[email protected]> Acked-by: Rafael J. Wysocki <[email protected]> Acked-by: [email protected] Signed-off-by: Len Brown <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void HTMLFormControlElement::AttributeChanged( const AttributeModificationParams& params) { HTMLElement::AttributeChanged(params); if (params.name == kDisabledAttr && params.old_value.IsNull() != params.new_value.IsNull()) { DisabledAttributeChanged(); if (params.reason == AttributeModificationReason::kDirectly && IsDisabledFormControl() && AdjustedFocusedElementInTreeScope() == this) blur(); } } Commit Message: autofocus: Fix a crash with an autofocus element in a document without browsing context. ShouldAutofocus() should check existence of the browsing context. Otherwise, doc.TopFrameOrigin() returns null. Before crrev.com/695830, ShouldAutofocus() was called only for rendered elements. That is to say, the document always had browsing context. Bug: 1003228 Change-Id: I2a941c34e9707d44869a6d7585dc7fb9f06e3bf4 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1800902 Commit-Queue: Kent Tamura <[email protected]> Reviewed-by: Keishi Hattori <[email protected]> Cr-Commit-Position: refs/heads/master@{#696291} 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: WandExport MagickBooleanType MogrifyImageInfo(ImageInfo *image_info, const int argc,const char **argv,ExceptionInfo *exception) { const char *option; GeometryInfo geometry_info; ssize_t count; register ssize_t i; /* Initialize method variables. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); if (argc < 0) return(MagickTrue); /* Set the image settings. */ for (i=0; i < (ssize_t) argc; i++) { option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; switch (*(option+1)) { case 'a': { if (LocaleCompare("adjoin",option+1) == 0) { image_info->adjoin=(*option == '-') ? MagickTrue : MagickFalse; break; } if (LocaleCompare("antialias",option+1) == 0) { image_info->antialias=(*option == '-') ? MagickTrue : MagickFalse; break; } if (LocaleCompare("attenuate",option+1) == 0) { if (*option == '+') { (void) DeleteImageOption(image_info,option+1); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("authenticate",option+1) == 0) { if (*option == '+') (void) CloneString(&image_info->authenticate,(char *) NULL); else (void) CloneString(&image_info->authenticate,argv[i+1]); break; } break; } case 'b': { if (LocaleCompare("background",option+1) == 0) { if (*option == '+') { (void) DeleteImageOption(image_info,option+1); (void) QueryColorDatabase(MogrifyBackgroundColor, &image_info->background_color,exception); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); (void) QueryColorDatabase(argv[i+1],&image_info->background_color, exception); break; } if (LocaleCompare("bias",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"0.0"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("black-point-compensation",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"false"); break; } (void) SetImageOption(image_info,option+1,"true"); break; } if (LocaleCompare("blue-primary",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"0.0"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("bordercolor",option+1) == 0) { if (*option == '+') { (void) DeleteImageOption(image_info,option+1); (void) QueryColorDatabase(MogrifyBorderColor, &image_info->border_color,exception); break; } (void) QueryColorDatabase(argv[i+1],&image_info->border_color, exception); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("box",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,"undercolor","none"); break; } (void) SetImageOption(image_info,"undercolor",argv[i+1]); break; } break; } case 'c': { if (LocaleCompare("cache",option+1) == 0) { MagickSizeType limit; limit=MagickResourceInfinity; if (LocaleCompare("unlimited",argv[i+1]) != 0) limit=(MagickSizeType) SiPrefixToDoubleInterval(argv[i+1],100.0); (void) SetMagickResourceLimit(MemoryResource,limit); (void) SetMagickResourceLimit(MapResource,2*limit); break; } if (LocaleCompare("caption",option+1) == 0) { if (*option == '+') { (void) DeleteImageOption(image_info,option+1); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("channel",option+1) == 0) { if (*option == '+') { image_info->channel=DefaultChannels; break; } image_info->channel=(ChannelType) ParseChannelOption(argv[i+1]); break; } if (LocaleCompare("colors",option+1) == 0) { image_info->colors=StringToUnsignedLong(argv[i+1]); break; } if (LocaleCompare("colorspace",option+1) == 0) { if (*option == '+') { image_info->colorspace=UndefinedColorspace; (void) SetImageOption(image_info,option+1,"undefined"); break; } image_info->colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("comment",option+1) == 0) { if (*option == '+') { (void) DeleteImageOption(image_info,option+1); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("compose",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("compress",option+1) == 0) { if (*option == '+') { image_info->compression=UndefinedCompression; (void) SetImageOption(image_info,option+1,"undefined"); break; } image_info->compression=(CompressionType) ParseCommandOption( MagickCompressOptions,MagickFalse,argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } case 'd': { if (LocaleCompare("debug",option+1) == 0) { if (*option == '+') (void) SetLogEventMask("none"); else (void) SetLogEventMask(argv[i+1]); image_info->debug=IsEventLogging(); break; } if (LocaleCompare("define",option+1) == 0) { if (*option == '+') { if (LocaleNCompare(argv[i+1],"registry:",9) == 0) (void) DeleteImageRegistry(argv[i+1]+9); else (void) DeleteImageOption(image_info,argv[i+1]); break; } if (LocaleNCompare(argv[i+1],"registry:",9) == 0) { (void) DefineImageRegistry(StringRegistryType,argv[i+1]+9, exception); break; } (void) DefineImageOption(image_info,argv[i+1]); break; } if (LocaleCompare("delay",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"0"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("density",option+1) == 0) { /* Set image density. */ if (*option == '+') { if (image_info->density != (char *) NULL) image_info->density=DestroyString(image_info->density); (void) SetImageOption(image_info,option+1,"72"); break; } (void) CloneString(&image_info->density,argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("depth",option+1) == 0) { if (*option == '+') { image_info->depth=MAGICKCORE_QUANTUM_DEPTH; break; } image_info->depth=StringToUnsignedLong(argv[i+1]); break; } if (LocaleCompare("direction",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("display",option+1) == 0) { if (*option == '+') { if (image_info->server_name != (char *) NULL) image_info->server_name=DestroyString( image_info->server_name); break; } (void) CloneString(&image_info->server_name,argv[i+1]); break; } if (LocaleCompare("dispose",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("dither",option+1) == 0) { if (*option == '+') { image_info->dither=MagickFalse; (void) SetImageOption(image_info,option+1,"none"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); image_info->dither=MagickTrue; break; } break; } case 'e': { if (LocaleCompare("encoding",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("endian",option+1) == 0) { if (*option == '+') { image_info->endian=UndefinedEndian; (void) SetImageOption(image_info,option+1,"undefined"); break; } image_info->endian=(EndianType) ParseCommandOption( MagickEndianOptions,MagickFalse,argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("extract",option+1) == 0) { /* Set image extract geometry. */ if (*option == '+') { if (image_info->extract != (char *) NULL) image_info->extract=DestroyString(image_info->extract); break; } (void) CloneString(&image_info->extract,argv[i+1]); break; } break; } case 'f': { if (LocaleCompare("family",option+1) == 0) { if (*option != '+') (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("fill",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"none"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("filter",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("font",option+1) == 0) { if (*option == '+') { if (image_info->font != (char *) NULL) image_info->font=DestroyString(image_info->font); break; } (void) CloneString(&image_info->font,argv[i+1]); break; } if (LocaleCompare("format",option+1) == 0) { register const char *q; for (q=strchr(argv[i+1],'%'); q != (char *) NULL; q=strchr(q+1,'%')) if (strchr("Agkrz@[#",*(q+1)) != (char *) NULL) image_info->ping=MagickFalse; (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("fuzz",option+1) == 0) { if (*option == '+') { image_info->fuzz=0.0; (void) SetImageOption(image_info,option+1,"0"); break; } image_info->fuzz=StringToDoubleInterval(argv[i+1],(double) QuantumRange+1.0); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } case 'g': { if (LocaleCompare("gravity",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("green-primary",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"0.0"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } case 'i': { if (LocaleCompare("intensity",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("intent",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("interlace",option+1) == 0) { if (*option == '+') { image_info->interlace=UndefinedInterlace; (void) SetImageOption(image_info,option+1,"undefined"); break; } image_info->interlace=(InterlaceType) ParseCommandOption( MagickInterlaceOptions,MagickFalse,argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("interline-spacing",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("interpolate",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("interword-spacing",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } case 'k': { if (LocaleCompare("kerning",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"undefined"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare("label",option+1) == 0) { if (*option == '+') { (void) DeleteImageOption(image_info,option+1); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("limit",option+1) == 0) { MagickSizeType limit; ResourceType type; if (*option == '+') break; type=(ResourceType) ParseCommandOption(MagickResourceOptions, MagickFalse,argv[i+1]); limit=MagickResourceInfinity; if (LocaleCompare("unlimited",argv[i+2]) != 0) limit=(MagickSizeType) SiPrefixToDoubleInterval(argv[i+2],100.0); (void) SetMagickResourceLimit(type,limit); break; } if (LocaleCompare("list",option+1) == 0) { ssize_t list; /* Display configuration list. */ list=ParseCommandOption(MagickListOptions,MagickFalse,argv[i+1]); switch (list) { case MagickCoderOptions: { (void) ListCoderInfo((FILE *) NULL,exception); break; } case MagickColorOptions: { (void) ListColorInfo((FILE *) NULL,exception); break; } case MagickConfigureOptions: { (void) ListConfigureInfo((FILE *) NULL,exception); break; } case MagickDelegateOptions: { (void) ListDelegateInfo((FILE *) NULL,exception); break; } case MagickFontOptions: { (void) ListTypeInfo((FILE *) NULL,exception); break; } case MagickFormatOptions: { (void) ListMagickInfo((FILE *) NULL,exception); break; } case MagickLocaleOptions: { (void) ListLocaleInfo((FILE *) NULL,exception); break; } case MagickLogOptions: { (void) ListLogInfo((FILE *) NULL,exception); break; } case MagickMagicOptions: { (void) ListMagicInfo((FILE *) NULL,exception); break; } case MagickMimeOptions: { (void) ListMimeInfo((FILE *) NULL,exception); break; } case MagickModuleOptions: { (void) ListModuleInfo((FILE *) NULL,exception); break; } case MagickPolicyOptions: { (void) ListPolicyInfo((FILE *) NULL,exception); break; } case MagickResourceOptions: { (void) ListMagickResourceInfo((FILE *) NULL,exception); break; } case MagickThresholdOptions: { (void) ListThresholdMaps((FILE *) NULL,exception); break; } default: { (void) ListCommandOptions((FILE *) NULL,(CommandOption) list, exception); break; } } break; } if (LocaleCompare("log",option+1) == 0) { if (*option == '+') break; (void) SetLogFormat(argv[i+1]); break; } if (LocaleCompare("loop",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"0"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } case 'm': { if (LocaleCompare("matte",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"false"); break; } (void) SetImageOption(image_info,option+1,"true"); break; } if (LocaleCompare("mattecolor",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,argv[i+1]); (void) QueryColorDatabase(MogrifyMatteColor, &image_info->matte_color,exception); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); (void) QueryColorDatabase(argv[i+1],&image_info->matte_color, exception); break; } if (LocaleCompare("metric",option+1) == 0) { if (*option == '+') { (void) DeleteImageOption(image_info,option+1); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("monitor",option+1) == 0) { (void) SetImageInfoProgressMonitor(image_info,MonitorProgress, (void *) NULL); break; } if (LocaleCompare("monochrome",option+1) == 0) { image_info->monochrome=(*option == '-') ? MagickTrue : MagickFalse; break; } break; } case 'o': { if (LocaleCompare("orient",option+1) == 0) { if (*option == '+') { image_info->orientation=UndefinedOrientation; (void) SetImageOption(image_info,option+1,"undefined"); break; } image_info->orientation=(OrientationType) ParseCommandOption( MagickOrientationOptions,MagickFalse,argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } } case 'p': { if (LocaleCompare("page",option+1) == 0) { char *canonical_page, page[MaxTextExtent]; const char *image_option; MagickStatusType flags; RectangleInfo geometry; if (*option == '+') { (void) DeleteImageOption(image_info,option+1); (void) CloneString(&image_info->page,(char *) NULL); break; } (void) memset(&geometry,0,sizeof(geometry)); image_option=GetImageOption(image_info,"page"); if (image_option != (const char *) NULL) (void) ParseAbsoluteGeometry(image_option,&geometry); canonical_page=GetPageGeometry(argv[i+1]); flags=ParseAbsoluteGeometry(canonical_page,&geometry); canonical_page=DestroyString(canonical_page); (void) FormatLocaleString(page,MaxTextExtent,"%lux%lu", (unsigned long) geometry.width,(unsigned long) geometry.height); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) (void) FormatLocaleString(page,MaxTextExtent,"%lux%lu%+ld%+ld", (unsigned long) geometry.width,(unsigned long) geometry.height, (long) geometry.x,(long) geometry.y); (void) SetImageOption(image_info,option+1,page); (void) CloneString(&image_info->page,page); break; } if (LocaleCompare("pen",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"none"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("ping",option+1) == 0) { image_info->ping=(*option == '-') ? MagickTrue : MagickFalse; break; } if (LocaleCompare("pointsize",option+1) == 0) { if (*option == '+') geometry_info.rho=0.0; else (void) ParseGeometry(argv[i+1],&geometry_info); image_info->pointsize=geometry_info.rho; break; } if (LocaleCompare("precision",option+1) == 0) { (void) SetMagickPrecision(StringToInteger(argv[i+1])); break; } if (LocaleCompare("preview",option+1) == 0) { /* Preview image. */ if (*option == '+') { image_info->preview_type=UndefinedPreview; break; } image_info->preview_type=(PreviewType) ParseCommandOption( MagickPreviewOptions,MagickFalse,argv[i+1]); break; } break; } case 'q': { if (LocaleCompare("quality",option+1) == 0) { /* Set image compression quality. */ if (*option == '+') { image_info->quality=UndefinedCompressionQuality; (void) SetImageOption(image_info,option+1,"0"); break; } image_info->quality=StringToUnsignedLong(argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("quiet",option+1) == 0) { static WarningHandler warning_handler = (WarningHandler) NULL; if (*option == '+') { /* Restore error or warning messages. */ warning_handler=SetWarningHandler(warning_handler); break; } /* Suppress error or warning messages. */ warning_handler=SetWarningHandler((WarningHandler) NULL); break; } break; } case 'r': { if (LocaleCompare("red-primary",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"0.0"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } case 's': { if (LocaleCompare("sampling-factor",option+1) == 0) { /* Set image sampling factor. */ if (*option == '+') { if (image_info->sampling_factor != (char *) NULL) image_info->sampling_factor=DestroyString( image_info->sampling_factor); break; } (void) CloneString(&image_info->sampling_factor,argv[i+1]); break; } if (LocaleCompare("scene",option+1) == 0) { /* Set image scene. */ if (*option == '+') { image_info->scene=0; (void) SetImageOption(image_info,option+1,"0"); break; } image_info->scene=StringToUnsignedLong(argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("seed",option+1) == 0) { unsigned long seed; if (*option == '+') { seed=(unsigned long) time((time_t *) NULL); SetRandomSecretKey(seed); break; } seed=StringToUnsignedLong(argv[i+1]); SetRandomSecretKey(seed); break; } if (LocaleCompare("size",option+1) == 0) { if (*option == '+') { if (image_info->size != (char *) NULL) image_info->size=DestroyString(image_info->size); break; } (void) CloneString(&image_info->size,argv[i+1]); break; } if (LocaleCompare("stroke",option+1) == 0) { if (*option == '+') (void) SetImageOption(image_info,option+1,"none"); else (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("strokewidth",option+1) == 0) { if (*option == '+') (void) SetImageOption(image_info,option+1,"0"); else (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("style",option+1) == 0) { if (*option == '+') (void) SetImageOption(image_info,option+1,"none"); else (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("synchronize",option+1) == 0) { if (*option == '+') { image_info->synchronize=MagickFalse; break; } image_info->synchronize=MagickTrue; break; } break; } case 't': { if (LocaleCompare("taint",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"false"); break; } (void) SetImageOption(image_info,option+1,"true"); break; } if (LocaleCompare("texture",option+1) == 0) { if (*option == '+') { if (image_info->texture != (char *) NULL) image_info->texture=DestroyString(image_info->texture); break; } (void) CloneString(&image_info->texture,argv[i+1]); break; } if (LocaleCompare("tile-offset",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"0"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("transparent-color",option+1) == 0) { if (*option == '+') { (void) QueryColorDatabase("none",&image_info->transparent_color, exception); (void) SetImageOption(image_info,option+1,"none"); break; } (void) QueryColorDatabase(argv[i+1],&image_info->transparent_color, exception); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("type",option+1) == 0) { if (*option == '+') { image_info->type=UndefinedType; (void) SetImageOption(image_info,option+1,"undefined"); break; } image_info->type=(ImageType) ParseCommandOption(MagickTypeOptions, MagickFalse,argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } case 'u': { if (LocaleCompare("undercolor",option+1) == 0) { if (*option == '+') { (void) DeleteImageOption(image_info,option+1); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("units",option+1) == 0) { if (*option == '+') { image_info->units=UndefinedResolution; (void) SetImageOption(image_info,option+1,"undefined"); break; } image_info->units=(ResolutionType) ParseCommandOption( MagickResolutionOptions,MagickFalse,argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } case 'v': { if (LocaleCompare("verbose",option+1) == 0) { if (*option == '+') { image_info->verbose=MagickFalse; break; } image_info->verbose=MagickTrue; image_info->ping=MagickFalse; break; } if (LocaleCompare("view",option+1) == 0) { if (*option == '+') { if (image_info->view != (char *) NULL) image_info->view=DestroyString(image_info->view); break; } (void) CloneString(&image_info->view,argv[i+1]); break; } if (LocaleCompare("virtual-pixel",option+1) == 0) { if (*option == '+') { image_info->virtual_pixel_method=UndefinedVirtualPixelMethod; (void) SetImageOption(image_info,option+1,"undefined"); break; } image_info->virtual_pixel_method=(VirtualPixelMethod) ParseCommandOption(MagickVirtualPixelOptions,MagickFalse, argv[i+1]); (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } case 'w': { if (LocaleCompare("weight",option+1) == 0) { if (*option == '+') (void) SetImageOption(image_info,option+1,"0"); else (void) SetImageOption(image_info,option+1,argv[i+1]); break; } if (LocaleCompare("white-point",option+1) == 0) { if (*option == '+') { (void) SetImageOption(image_info,option+1,"0.0"); break; } (void) SetImageOption(image_info,option+1,argv[i+1]); break; } break; } default: break; } i+=count; } return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1623 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: int sanity_check_ckpt(struct f2fs_sb_info *sbi) { unsigned int total, fsmeta; struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi); struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi); unsigned int ovp_segments, reserved_segments; total = le32_to_cpu(raw_super->segment_count); fsmeta = le32_to_cpu(raw_super->segment_count_ckpt); fsmeta += le32_to_cpu(raw_super->segment_count_sit); fsmeta += le32_to_cpu(raw_super->segment_count_nat); fsmeta += le32_to_cpu(ckpt->rsvd_segment_count); fsmeta += le32_to_cpu(raw_super->segment_count_ssa); if (unlikely(fsmeta >= total)) return 1; ovp_segments = le32_to_cpu(ckpt->overprov_segment_count); reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count); if (unlikely(fsmeta < F2FS_MIN_SEGMENTS || ovp_segments == 0 || reserved_segments == 0)) { f2fs_msg(sbi->sb, KERN_ERR, "Wrong layout: check mkfs.f2fs version"); return 1; } if (unlikely(f2fs_cp_error(sbi))) { f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck"); return 1; } return 0; } Commit Message: f2fs: sanity check checkpoint segno and blkoff Make sure segno and blkoff read from raw image are valid. Cc: [email protected] Signed-off-by: Jin Qian <[email protected]> [Jaegeuk Kim: adjust minor coding style] Signed-off-by: Jaegeuk Kim <[email protected]> CWE ID: CWE-129 Target: 1 Example 2: Code: void big_key_describe(const struct key *key, struct seq_file *m) { unsigned long datalen = key->type_data.x[1]; seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %lu [%s]", datalen, datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff"); } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <[email protected]> Acked-by: Vivek Goyal <[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 store_updates_sp(struct pt_regs *regs) { unsigned int inst; if (get_user(inst, (unsigned int __user *)regs->nip)) return 0; /* check for 1 in the rA field */ if (((inst >> 16) & 0x1f) != 1) return 0; /* check major opcode */ switch (inst >> 26) { case 37: /* stwu */ case 39: /* stbu */ case 45: /* sthu */ case 53: /* stfsu */ case 55: /* stfdu */ return 1; case 62: /* std or stdu */ return (inst & 3) == 1; case 31: /* check minor opcode */ switch ((inst >> 1) & 0x3ff) { case 181: /* stdux */ case 183: /* stwux */ case 247: /* stbux */ case 439: /* sthux */ case 695: /* stfsux */ case 759: /* stfdux */ return 1; } } 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: FLACParser::FLACParser( const sp<DataSource> &dataSource, const sp<MetaData> &fileMetadata, const sp<MetaData> &trackMetadata) : mDataSource(dataSource), mFileMetadata(fileMetadata), mTrackMetadata(trackMetadata), mInitCheck(false), mMaxBufferSize(0), mGroup(NULL), mCopy(copyTrespass), mDecoder(NULL), mCurrentPos(0LL), mEOF(false), mStreamInfoValid(false), mWriteRequested(false), mWriteCompleted(false), mWriteBuffer(NULL), mErrorStatus((FLAC__StreamDecoderErrorStatus) -1) { ALOGV("FLACParser::FLACParser"); memset(&mStreamInfo, 0, sizeof(mStreamInfo)); memset(&mWriteHeader, 0, sizeof(mWriteHeader)); mInitCheck = init(); } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119 Target: 1 Example 2: Code: void RTCPeerConnectionHandler::OnConnectionChange( webrtc::PeerConnectionInterface::PeerConnectionState new_state) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); if (!is_closed_) client_->DidChangePeerConnectionState(new_state); } Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl Bug: 912074 Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8 Reviewed-on: https://chromium-review.googlesource.com/c/1411916 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#622945} 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: void CWebServer::Cmd_UpdateUserVariable(WebEmSession & session, const request& req, Json::Value &root) { if (session.rights != 2) { session.reply_status = reply::forbidden; return; //Only admin user allowed } std::string idx = request::findValue(&req, "idx"); std::string variablename = request::findValue(&req, "vname"); std::string variablevalue = request::findValue(&req, "vvalue"); std::string variabletype = request::findValue(&req, "vtype"); if ( (variablename.empty()) || (variabletype.empty()) || ((variablevalue.empty()) && (variabletype != "2")) ) return; std::vector<std::vector<std::string> > result; if (idx.empty()) { result = m_sql.safe_query("SELECT ID FROM UserVariables WHERE Name='%q'", variablename.c_str()); if (result.empty()) return; idx = result[0][0]; } result = m_sql.safe_query("SELECT Name, ValueType FROM UserVariables WHERE ID='%q'", idx.c_str()); if (result.empty()) return; bool bTypeNameChanged = false; if (variablename != result[0][0]) bTypeNameChanged = true; //new name else if (variabletype != result[0][1]) bTypeNameChanged = true; //new type root["title"] = "UpdateUserVariable"; std::string errorMessage; if (!m_sql.UpdateUserVariable(idx, variablename, (const _eUsrVariableType)atoi(variabletype.c_str()), variablevalue, !bTypeNameChanged, errorMessage)) { root["status"] = "ERR"; root["message"] = errorMessage; } else { root["status"] = "OK"; if (bTypeNameChanged) { if (m_sql.m_bEnableEventSystem) m_mainworker.m_eventsystem.GetCurrentUserVariables(); } } } Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!) CWE ID: CWE-89 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: Cues::Cues( Segment* pSegment, long long start_, long long size_, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(start_), m_size(size_), m_element_start(element_start), m_element_size(element_size), m_cue_points(NULL), m_count(0), m_preload_count(0), m_pos(start_) { } 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: request_remove_header (struct request *req, const char *name) { int i; for (i = 0; i < req->hcount; i++) { struct request_header *hdr = &req->headers[i]; if (0 == c_strcasecmp (name, hdr->name)) { release_header (hdr); /* Move the remaining headers by one. */ if (i < req->hcount - 1) memmove (hdr, hdr + 1, (req->hcount - i - 1) * sizeof (*hdr)); --req->hcount; return true; } } return false; } 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: unsigned getChannels() const { return mStreamInfo.channels; } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 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: MagickExport int LocaleUppercase(const int c) { #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(toupper_l((int) ((unsigned char) c),c_locale)); #endif return(toupper((int) ((unsigned char) c))); } Commit Message: ... CWE ID: CWE-125 Target: 1 Example 2: Code: int regulator_force_disable(struct regulator *regulator) { struct regulator_dev *rdev = regulator->rdev; int ret; mutex_lock(&rdev->mutex); regulator->uA_load = 0; ret = _regulator_force_disable(regulator->rdev); mutex_unlock(&rdev->mutex); if (rdev->supply) while (rdev->open_count--) regulator_disable(rdev->supply); return ret; } Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing After freeing pin from regulator_ena_gpio_free, loop can access the pin. So this patch fixes not to access pin after freeing. Signed-off-by: Seung-Woo Kim <[email protected]> Signed-off-by: Mark Brown <[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: static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; Quantum index; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* 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); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { PixelInfo quantum_bits; PixelPacket shift; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MagickPathExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MagickPathExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } (void) ReadBlobLSBLong(image); /* Profile data */ (void) ReadBlobLSBLong(image); /* Profile size */ (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnrecognizedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->alpha_trait=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait : UndefinedPixelTrait; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->resolution.x=(double) bmp_info.x_pixels/100.0; image->resolution.y=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if (((MagickSizeType) length/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->alpha_trait=BlendPixelTrait; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register unsigned int sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red >= 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green >= 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue >= 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0) { shift.alpha++; if (shift.alpha >= 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.red=(MagickRealType) (sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.green=(MagickRealType) (sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.blue=(MagickRealType) (sample-shift.blue); sample=shift.alpha; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.alpha=(MagickRealType) (sample-shift.alpha); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; x++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns; x != 0; --x) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha == 8) alpha|=(alpha >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1268 CWE ID: CWE-770 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: status_t CameraService::dump(int fd, const Vector<String16>& args) { String8 result; if (checkCallingPermission(String16("android.permission.DUMP")) == false) { result.appendFormat("Permission Denial: " "can't dump CameraService from pid=%d, uid=%d\n", getCallingPid(), getCallingUid()); write(fd, result.string(), result.size()); } else { bool locked = tryLock(mServiceLock); if (!locked) { result.append("CameraService may be deadlocked\n"); write(fd, result.string(), result.size()); } bool hasClient = false; if (!mModule) { result = String8::format("No camera module available!\n"); write(fd, result.string(), result.size()); return NO_ERROR; } result = String8::format("Camera module HAL API version: 0x%x\n", mModule->common.hal_api_version); result.appendFormat("Camera module API version: 0x%x\n", mModule->common.module_api_version); result.appendFormat("Camera module name: %s\n", mModule->common.name); result.appendFormat("Camera module author: %s\n", mModule->common.author); result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras); write(fd, result.string(), result.size()); for (int i = 0; i < mNumberOfCameras; i++) { result = String8::format("Camera %d static information:\n", i); camera_info info; status_t rc = mModule->get_camera_info(i, &info); if (rc != OK) { result.appendFormat(" Error reading static information!\n"); write(fd, result.string(), result.size()); } else { result.appendFormat(" Facing: %s\n", info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT"); result.appendFormat(" Orientation: %d\n", info.orientation); int deviceVersion; if (mModule->common.module_api_version < CAMERA_MODULE_API_VERSION_2_0) { deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; } else { deviceVersion = info.device_version; } result.appendFormat(" Device version: 0x%x\n", deviceVersion); if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) { result.appendFormat(" Device static metadata:\n"); write(fd, result.string(), result.size()); dump_indented_camera_metadata(info.static_camera_characteristics, fd, 2, 4); } else { write(fd, result.string(), result.size()); } } sp<BasicClient> client = mClient[i].promote(); if (client == 0) { result = String8::format(" Device is closed, no client instance\n"); write(fd, result.string(), result.size()); continue; } hasClient = true; result = String8::format(" Device is open. Client instance dump:\n"); write(fd, result.string(), result.size()); client->dump(fd, args); } if (!hasClient) { result = String8::format("\nNo active camera clients yet.\n"); write(fd, result.string(), result.size()); } if (locked) mServiceLock.unlock(); write(fd, "\n", 1); camera3::CameraTraces::dump(fd, args); int n = args.size(); for (int i = 0; i + 1 < n; i++) { String16 verboseOption("-v"); if (args[i] == verboseOption) { String8 levelStr(args[i+1]); int level = atoi(levelStr.string()); result = String8::format("\nSetting log level to %d.\n", level); setLogLevel(level); write(fd, result.string(), result.size()); } } } return NO_ERROR; } Commit Message: Camera: Disallow dumping clients directly Camera service dumps should only be initiated through ICameraService::dump. Bug: 26265403 Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803 CWE ID: CWE-264 Target: 1 Example 2: Code: static ZIPARCHIVE_METHOD(locateName) { struct zip *intern; zval *this = getThis(); char *name; int name_len; long flags = 0; long idx = -1; if (!this) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, this); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|l", &name, &name_len, &flags) == FAILURE) { return; } if (name_len<1) { RETURN_FALSE; } idx = (long)zip_name_locate(intern, (const char *)name, flags); if (idx >= 0) { RETURN_LONG(idx); } else { RETURN_FALSE; } } Commit Message: Fix bug #72434: ZipArchive class Use After Free Vulnerability in PHP's GC algorithm and unserialize 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: T42_Open_Face( T42_Face face ) { T42_LoaderRec loader; T42_Parser parser; T1_Font type1 = &face->type1; FT_Memory memory = face->root.memory; FT_Error error; PSAux_Service psaux = (PSAux_Service)face->psaux; t42_loader_init( &loader, face ); parser = &loader.parser; if ( FT_ALLOC( face->ttf_data, 12 ) ) goto Exit; error = t42_parser_init( parser, face->root.stream, memory, if ( error ) goto Exit; if ( type1->font_type != 42 ) { FT_ERROR(( "T42_Open_Face: cannot handle FontType %d\n", type1->font_type )); error = FT_THROW( Unknown_File_Format ); goto Exit; } /* now, propagate the charstrings and glyphnames tables */ /* to the Type1 data */ type1->num_glyphs = loader.num_glyphs; if ( !loader.charstrings.init ) { FT_ERROR(( "T42_Open_Face: no charstrings array in face\n" )); error = FT_THROW( Invalid_File_Format ); } loader.charstrings.init = 0; type1->charstrings_block = loader.charstrings.block; type1->charstrings = loader.charstrings.elements; type1->charstrings_len = loader.charstrings.lengths; /* we copy the glyph names `block' and `elements' fields; */ /* the `lengths' field must be released later */ type1->glyph_names_block = loader.glyph_names.block; type1->glyph_names = (FT_String**)loader.glyph_names.elements; loader.glyph_names.block = 0; loader.glyph_names.elements = 0; /* we must now build type1.encoding when we have a custom array */ if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY ) { FT_Int charcode, idx, min_char, max_char; FT_Byte* glyph_name; /* OK, we do the following: for each element in the encoding */ /* table, look up the index of the glyph having the same name */ /* as defined in the CharStrings array. */ /* The index is then stored in type1.encoding.char_index, and */ /* the name in type1.encoding.char_name */ min_char = 0; max_char = 0; charcode = 0; for ( ; charcode < loader.encoding_table.max_elems; charcode++ ) { FT_Byte* char_name; type1->encoding.char_index[charcode] = 0; type1->encoding.char_name [charcode] = (char *)".notdef"; char_name = loader.encoding_table.elements[charcode]; if ( char_name ) for ( idx = 0; idx < type1->num_glyphs; idx++ ) { glyph_name = (FT_Byte*)type1->glyph_names[idx]; if ( ft_strcmp( (const char*)char_name, (const char*)glyph_name ) == 0 ) { type1->encoding.char_index[charcode] = (FT_UShort)idx; type1->encoding.char_name [charcode] = (char*)glyph_name; /* Change min/max encoded char only if glyph name is */ /* not /.notdef */ if ( ft_strcmp( (const char*)".notdef", (const char*)glyph_name ) != 0 ) { if ( charcode < min_char ) min_char = charcode; if ( charcode >= max_char ) max_char = charcode + 1; } break; } } } type1->encoding.code_first = min_char; type1->encoding.code_last = max_char; type1->encoding.num_chars = loader.num_chars; } Exit: t42_loader_done( &loader ); return error; } 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: static long vop_ioctl(struct file *f, unsigned int cmd, unsigned long arg) { struct vop_vdev *vdev = f->private_data; struct vop_info *vi = vdev->vi; void __user *argp = (void __user *)arg; int ret; switch (cmd) { case MIC_VIRTIO_ADD_DEVICE: { struct mic_device_desc dd, *dd_config; if (copy_from_user(&dd, argp, sizeof(dd))) return -EFAULT; if (mic_aligned_desc_size(&dd) > MIC_MAX_DESC_BLK_SIZE || dd.num_vq > MIC_MAX_VRINGS) return -EINVAL; dd_config = kzalloc(mic_desc_size(&dd), GFP_KERNEL); if (!dd_config) return -ENOMEM; if (copy_from_user(dd_config, argp, mic_desc_size(&dd))) { ret = -EFAULT; goto free_ret; } mutex_lock(&vdev->vdev_mutex); mutex_lock(&vi->vop_mutex); ret = vop_virtio_add_device(vdev, dd_config); if (ret) goto unlock_ret; list_add_tail(&vdev->list, &vi->vdev_list); unlock_ret: mutex_unlock(&vi->vop_mutex); mutex_unlock(&vdev->vdev_mutex); free_ret: kfree(dd_config); return ret; } case MIC_VIRTIO_COPY_DESC: { struct mic_copy_desc copy; mutex_lock(&vdev->vdev_mutex); ret = vop_vdev_inited(vdev); if (ret) goto _unlock_ret; if (copy_from_user(&copy, argp, sizeof(copy))) { ret = -EFAULT; goto _unlock_ret; } ret = vop_virtio_copy_desc(vdev, &copy); if (ret < 0) goto _unlock_ret; if (copy_to_user( &((struct mic_copy_desc __user *)argp)->out_len, &copy.out_len, sizeof(copy.out_len))) ret = -EFAULT; _unlock_ret: mutex_unlock(&vdev->vdev_mutex); return ret; } case MIC_VIRTIO_CONFIG_CHANGE: { void *buf; mutex_lock(&vdev->vdev_mutex); ret = vop_vdev_inited(vdev); if (ret) goto __unlock_ret; buf = kzalloc(vdev->dd->config_len, GFP_KERNEL); if (!buf) { ret = -ENOMEM; goto __unlock_ret; } if (copy_from_user(buf, argp, vdev->dd->config_len)) { ret = -EFAULT; goto done; } ret = vop_virtio_config_change(vdev, buf); done: kfree(buf); __unlock_ret: mutex_unlock(&vdev->vdev_mutex); return ret; } default: return -ENOIOCTLCMD; }; return 0; } Commit Message: misc: mic: Fix for double fetch security bug in VOP driver The MIC VOP driver does two successive reads from user space to read a variable length data structure. Kernel memory corruption can result if the data structure changes between the two reads. This patch disallows the chance of this happening. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=116651 Reported by: Pengfei Wang <[email protected]> Reviewed-by: Sudeep Dutt <[email protected]> Signed-off-by: Ashutosh Dixit <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void ArcVoiceInteractionFrameworkService::SetVoiceInteractionEnabled( bool enable, VoiceInteractionSettingCompleteCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); PrefService* prefs = Profile::FromBrowserContext(context_)->GetPrefs(); prefs->SetBoolean(prefs::kVoiceInteractionEnabled, enable); if (!enable) prefs->SetBoolean(prefs::kVoiceInteractionContextEnabled, false); mojom::VoiceInteractionFrameworkInstance* framework_instance = ARC_GET_INSTANCE_FOR_METHOD( arc_bridge_service_->voice_interaction_framework(), SetVoiceInteractionEnabled); if (!framework_instance) { std::move(callback).Run(false); return; } framework_instance->SetVoiceInteractionEnabled( enable, base::BindOnce(std::move(callback), true)); } Commit Message: arc: add test for blocking incognito windows in screenshot BUG=778852 TEST=ArcVoiceInteractionFrameworkServiceUnittest. CapturingScreenshotBlocksIncognitoWindows Change-Id: I0bfa5a486759783d7c8926a309c6b5da9b02dcc6 Reviewed-on: https://chromium-review.googlesource.com/914983 Commit-Queue: Muyuan Li <[email protected]> Reviewed-by: Luis Hector Chavez <[email protected]> Cr-Commit-Position: refs/heads/master@{#536438} 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: void efx_remove_tx_queue(struct efx_tx_queue *tx_queue) { if (!tx_queue->buffer) return; netif_dbg(tx_queue->efx, drv, tx_queue->efx->net_dev, "destroying TX queue %d\n", tx_queue->queue); efx_nic_remove_tx(tx_queue); kfree(tx_queue->buffer); tx_queue->buffer = NULL; } Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size [ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ] Currently an skb requiring TSO may not fit within a minimum-size TX queue. The TX queue selected for the skb may stall and trigger the TX watchdog repeatedly (since the problem skb will be retried after the TX reset). This issue is designated as CVE-2012-3412. Set the maximum number of TSO segments for our devices to 100. This should make no difference to behaviour unless the actual MSS is less than about 700. Increase the minimum TX queue size accordingly to allow for 2 worst-case skbs, so that there will definitely be space to add an skb after we wake a queue. To avoid invalidating existing configurations, change efx_ethtool_set_ringparam() to fix up values that are too small rather than returning -EINVAL. Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> CWE ID: CWE-189 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 l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_l2 *la = (struct sockaddr_l2 *) addr; struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; BT_DBG("sock %p, sk %p", sock, sk); addr->sa_family = AF_BLUETOOTH; *len = sizeof(struct sockaddr_l2); if (peer) { la->l2_psm = chan->psm; bacpy(&la->l2_bdaddr, &bt_sk(sk)->dst); la->l2_cid = cpu_to_le16(chan->dcid); } else { la->l2_psm = chan->sport; bacpy(&la->l2_bdaddr, &bt_sk(sk)->src); la->l2_cid = cpu_to_le16(chan->scid); } return 0; } Commit Message: Bluetooth: L2CAP - Fix info leak via getsockname() The L2CAP code fails to initialize the l2_bdaddr_type member of struct sockaddr_l2 and the padding byte added for alignment. It that for leaks two bytes kernel stack via the getsockname() syscall. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Marcel Holtmann <[email protected]> Cc: Gustavo Padovan <[email protected]> Cc: Johan Hedberg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: void Browser::OpenTaskManager(bool highlight_background_resources) { UserMetrics::RecordAction(UserMetricsAction("TaskManager"), profile_); if (highlight_background_resources) window_->ShowBackgroundPages(); else window_->ShowTaskManager(); } 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 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 const char *addr2str(hwaddr addr) { return nr2str(ehci_mmio_names, ARRAY_SIZE(ehci_mmio_names), addr); } Commit Message: CWE ID: CWE-772 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: METHODDEF(JDIMENSION) get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PPM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr)sinfo; register JSAMPROW ptr; register U_CHAR *bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; unsigned int maxval = source->maxval; if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register unsigned int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); *ptr++ = rescale[temp]; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); *ptr++ = rescale[temp]; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); *ptr++ = rescale[temp]; } return 1; } Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP ... in which one or more of the color indices is out of range for the number of palette entries. Fix partly borrowed from jpeg-9c. This commit also adopts Guido's JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific JERR_PPM_TOOLARGE enum value. Fixes #258 CWE ID: CWE-125 Target: 1 Example 2: Code: void TabStripModelObserver::TabSelectionChanged( TabStripModel* tab_strip_model, const TabStripSelectionModel& model) { } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 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 RenderBox::pixelSnappedOffsetHeight() const { return snapSizeToPixel(offsetHeight(), y() + clientTop()); } 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: static void locationWithPerWorldBindingsAttributeSetterForMainWorld(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: bool RenderWidgetHostViewAura::TransformPointToLocalCoordSpace( const gfx::Point& point, const cc::SurfaceId& original_surface, gfx::Point* transformed_point) { gfx::Point point_in_pixels = gfx::ConvertPointToPixel(device_scale_factor_, point); if (delegated_frame_host_ && !delegated_frame_host_->TransformPointToLocalCoordSpace( point_in_pixels, original_surface, transformed_point)) return false; *transformed_point = gfx::ConvertPointToDIP(device_scale_factor_, *transformed_point); return true; } Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash RenderWidgetHostViewChildFrame expects its parent to have a valid FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even if DelegatedFrameHost is not used (in mus+ash). BUG=706553 [email protected] Review-Url: https://codereview.chromium.org/2847253003 Cr-Commit-Position: refs/heads/master@{#468179} 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: void ewk_frame_redirect_provisional_load(Evas_Object* ewkFrame) { evas_object_smart_callback_call(ewkFrame, "redirect,load,provisional", 0); } Commit Message: [EFL] fast/frames/frame-crash-with-page-cache.html is crashing https://bugs.webkit.org/show_bug.cgi?id=85879 Patch by Mikhail Pozdnyakov <[email protected]> on 2012-05-17 Reviewed by Noam Rosenthal. Source/WebKit/efl: _ewk_frame_smart_del() is considering now that the frame can be present in cache. loader()->detachFromParent() is only applied for the main frame. loader()->cancelAndClear() is not used anymore. * ewk/ewk_frame.cpp: (_ewk_frame_smart_del): LayoutTests: * platform/efl/test_expectations.txt: Removed fast/frames/frame-crash-with-page-cache.html. git-svn-id: svn://svn.chromium.org/blink/trunk@117409 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: fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count = cc; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); assert((cc%(bps*stride))==0); if (!tmp) return; while (count > stride) { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++) count -= stride; } _TIFFmemcpy(tmp, cp0, cc); cp = (uint8 *) cp0; for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[bps * count + byte] = tmp[byte * wc + count]; #else cp[bps * count + byte] = tmp[(bps - byte - 1) * wc + count]; #endif } } _TIFFfree(tmp); } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119 Target: 1 Example 2: Code: static inline void wanxl_cable_intr(port_t *port) { u32 value = get_status(port)->cable; int valid = 1; const char *cable, *pm, *dte = "", *dsr = "", *dcd = ""; switch(value & 0x7) { case STATUS_CABLE_V35: cable = "V.35"; break; case STATUS_CABLE_X21: cable = "X.21"; break; case STATUS_CABLE_V24: cable = "V.24"; break; case STATUS_CABLE_EIA530: cable = "EIA530"; break; case STATUS_CABLE_NONE: cable = "no"; break; default: cable = "invalid"; } switch((value >> STATUS_CABLE_PM_SHIFT) & 0x7) { case STATUS_CABLE_V35: pm = "V.35"; break; case STATUS_CABLE_X21: pm = "X.21"; break; case STATUS_CABLE_V24: pm = "V.24"; break; case STATUS_CABLE_EIA530: pm = "EIA530"; break; case STATUS_CABLE_NONE: pm = "no personality"; valid = 0; break; default: pm = "invalid personality"; valid = 0; } if (valid) { if ((value & 7) == ((value >> STATUS_CABLE_PM_SHIFT) & 7)) { dsr = (value & STATUS_CABLE_DSR) ? ", DSR ON" : ", DSR off"; dcd = (value & STATUS_CABLE_DCD) ? ", carrier ON" : ", carrier off"; } dte = (value & STATUS_CABLE_DCE) ? " DCE" : " DTE"; } netdev_info(port->dev, "%s%s module, %s cable%s%s\n", pm, dte, cable, dsr, dcd); if (value & STATUS_CABLE_DCD) netif_carrier_on(port->dev); else netif_carrier_off(port->dev); } Commit Message: wanxl: fix info leak in ioctl The wanxl_ioctl() code fails to initialize the two padding bytes of struct sync_serial_settings after the ->loopback member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Salva Peiró <[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: base::TimeDelta Textfield::GetCaretBlinkInterval() { static constexpr base::TimeDelta default_value = base::TimeDelta::FromMilliseconds(500); #if defined(OS_WIN) static const size_t system_value = ::GetCaretBlinkTime(); if (system_value != 0) { return (system_value == INFINITE) ? base::TimeDelta() : base::TimeDelta::FromMilliseconds(system_value); } #endif return default_value; } 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:
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 set_task_cpu(struct task_struct *p, unsigned int new_cpu) { #ifdef CONFIG_SCHED_DEBUG /* * We should never call set_task_cpu() on a blocked task, * ttwu() will sort out the placement. */ WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING && !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE)); #ifdef CONFIG_LOCKDEP /* * The caller should hold either p->pi_lock or rq->lock, when changing * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks. * * sched_move_task() holds both and thus holding either pins the cgroup, * see set_task_rq(). * * Furthermore, all task_rq users should acquire both locks, see * task_rq_lock(). */ WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) || lockdep_is_held(&task_rq(p)->lock))); #endif #endif trace_sched_migrate_task(p, new_cpu); if (task_cpu(p) != new_cpu) { p->se.nr_migrations++; perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 1, NULL, 0); } __set_task_cpu(p, new_cpu); } 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 Target: 1 Example 2: Code: static ssize_t aac_show_max_id(struct device *device, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", class_to_shost(device)->max_id); } Commit Message: aacraid: missing capable() check in compat ioctl In commit d496f94d22d1 ('[SCSI] aacraid: fix security weakness') we added a check on CAP_SYS_RAWIO to the ioctl. The compat ioctls need the check as well. Signed-off-by: Dan Carpenter <[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 GamepadProvider::AddGamepadDataFetcher( std::unique_ptr<GamepadDataFetcher> fetcher) { polling_thread_->task_runner()->PostTask( FROM_HERE, base::Bind(&GamepadProvider::DoAddGamepadDataFetcher, base::Unretained(this), base::Passed(&fetcher))); } 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 struct svcxprt_rdma *rdma_create_xprt(struct svc_serv *serv, int listener) { struct svcxprt_rdma *cma_xprt = kzalloc(sizeof *cma_xprt, GFP_KERNEL); if (!cma_xprt) return NULL; svc_xprt_init(&init_net, &svc_rdma_class, &cma_xprt->sc_xprt, serv); INIT_LIST_HEAD(&cma_xprt->sc_accept_q); INIT_LIST_HEAD(&cma_xprt->sc_rq_dto_q); INIT_LIST_HEAD(&cma_xprt->sc_read_complete_q); INIT_LIST_HEAD(&cma_xprt->sc_frmr_q); INIT_LIST_HEAD(&cma_xprt->sc_ctxts); INIT_LIST_HEAD(&cma_xprt->sc_maps); init_waitqueue_head(&cma_xprt->sc_send_wait); spin_lock_init(&cma_xprt->sc_lock); spin_lock_init(&cma_xprt->sc_rq_dto_lock); spin_lock_init(&cma_xprt->sc_frmr_q_lock); spin_lock_init(&cma_xprt->sc_ctxt_lock); spin_lock_init(&cma_xprt->sc_map_lock); /* * Note that this implies that the underlying transport support * has some form of congestion control (see RFC 7530 section 3.1 * paragraph 2). For now, we assume that all supported RDMA * transports are suitable here. */ set_bit(XPT_CONG_CTRL, &cma_xprt->sc_xprt.xpt_flags); if (listener) set_bit(XPT_LISTENER, &cma_xprt->sc_xprt.xpt_flags); return cma_xprt; } 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: 1 Example 2: Code: psf_f2s_clip_array (const float *src, short *dest, int count, int normalize) { float normfact, scaled_value ; normfact = normalize ? (1.0 * 0x8000) : 1.0 ; while (--count >= 0) { scaled_value = src [count] * normfact ; if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFF)) { dest [count] = 0x7FFF ; continue ; } ; if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x1000)) { dest [count] = 0x8000 ; continue ; } ; dest [count] = lrintf (scaled_value) ; } ; return ; } /* psf_f2s_clip_array */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119 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 ext3_journal_abort_handle(const char *caller, const char *err_fn, struct buffer_head *bh, handle_t *handle, int err) { char nbuf[16]; const char *errstr = ext3_decode_error(NULL, err, nbuf); if (bh) BUFFER_TRACE(bh, "abort"); if (!handle->h_err) handle->h_err = err; if (is_handle_aborted(handle)) return; printk(KERN_ERR "EXT3-fs: %s: aborting transaction: %s in %s\n", caller, errstr, err_fn); journal_abort_handle(handle); } Commit Message: ext3: Fix format string issues ext3_msg() takes the printk prefix as the second parameter and the format string as the third parameter. Two callers of ext3_msg omit the prefix and pass the format string as the second parameter and the first parameter to the format string as the third parameter. In both cases this string comes from an arbitrary source. Which means the string may contain format string characters, which will lead to undefined and potentially harmful behavior. The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages in ext3") and is fixed by this patch. CC: [email protected] Signed-off-by: Lars-Peter Clausen <[email protected]> Signed-off-by: Jan Kara <[email protected]> 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: int btsock_thread_wakeup(int h) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("thread handle:%d, cmd socket is not created", h); return FALSE; } sock_cmd_t cmd = {CMD_WAKEUP, 0, 0, 0, 0}; return send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Target: 1 Example 2: Code: bool PasswordAutofillAgent::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PasswordAutofillAgent, message) IPC_MESSAGE_HANDLER(AutofillMsg_FillPasswordForm, OnFillPasswordForm) IPC_MESSAGE_HANDLER(AutofillMsg_SetLoggingState, OnSetLoggingState) IPC_MESSAGE_HANDLER(AutofillMsg_AutofillUsernameAndPasswordDataReceived, OnAutofillUsernameAndPasswordDataReceived) IPC_MESSAGE_HANDLER(AutofillMsg_FindFocusedPasswordForm, OnFindFocusedPasswordForm) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Remove WeakPtrFactory from PasswordAutofillAgent Unlike in AutofillAgent, the factory is no longer used in PAA. [email protected] BUG=609010,609007,608100,608101,433486 Review-Url: https://codereview.chromium.org/1945723003 Cr-Commit-Position: refs/heads/master@{#391475} 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: MojoResult Core::NotifyBadMessage(MojoMessageHandle message_handle, const char* error, size_t error_num_bytes) { if (!message_handle) return MOJO_RESULT_INVALID_ARGUMENT; auto* message_event = reinterpret_cast<ports::UserMessageEvent*>(message_handle); auto* message = message_event->GetMessage<UserMessageImpl>(); if (message->source_node() == ports::kInvalidNodeName) { DVLOG(1) << "Received invalid message from unknown node."; if (!default_process_error_callback_.is_null()) default_process_error_callback_.Run(std::string(error, error_num_bytes)); return MOJO_RESULT_OK; } GetNodeController()->NotifyBadMessageFrom( message->source_node(), std::string(error, error_num_bytes)); return MOJO_RESULT_OK; } 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: virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 8; fwd_txfm_ref = fdct8x8_ref; } 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: gpc_Preq(Pixel *out, const Pixel *in, const Background *back) { (void)back; out->r = ilineara_g22(in->r, in->a); if (in->g == in->r) { out->g = out->r; if (in->b == in->r) out->b = out->r; else out->b = ilineara_g22(in->b, in->a); } else { out->g = ilineara_g22(in->g, in->a); if (in->b == in->r) out->b = out->r; else if (in->b == in->g) out->b = out->g; else out->b = ilineara_g22(in->b, in->a); } out->a = 65535; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) 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: bool ParamTraits<AudioParameters>::Read(const Message* m, PickleIterator* iter, AudioParameters* r) { int format, channel_layout, sample_rate, bits_per_sample, frames_per_buffer, channels; if (!m->ReadInt(iter, &format) || !m->ReadInt(iter, &channel_layout) || !m->ReadInt(iter, &sample_rate) || !m->ReadInt(iter, &bits_per_sample) || !m->ReadInt(iter, &frames_per_buffer) || !m->ReadInt(iter, &channels)) return false; r->Reset(static_cast<AudioParameters::Format>(format), static_cast<ChannelLayout>(channel_layout), sample_rate, bits_per_sample, frames_per_buffer); return true; } Commit Message: Improve validation when creating audio streams. BUG=166795 Review URL: https://codereview.chromium.org/11647012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 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 __init acpi_initrd_override(void *data, size_t size) { int sig, no, table_nr = 0, total_offset = 0; long offset = 0; struct acpi_table_header *table; char cpio_path[32] = "kernel/firmware/acpi/"; struct cpio_data file; if (data == NULL || size == 0) return; for (no = 0; no < ACPI_OVERRIDE_TABLES; no++) { file = find_cpio_data(cpio_path, data, size, &offset); if (!file.data) break; data += offset; size -= offset; if (file.size < sizeof(struct acpi_table_header)) { pr_err("ACPI OVERRIDE: Table smaller than ACPI header [%s%s]\n", cpio_path, file.name); continue; } table = file.data; for (sig = 0; table_sigs[sig]; sig++) if (!memcmp(table->signature, table_sigs[sig], 4)) break; if (!table_sigs[sig]) { pr_err("ACPI OVERRIDE: Unknown signature [%s%s]\n", cpio_path, file.name); continue; } if (file.size != table->length) { pr_err("ACPI OVERRIDE: File length does not match table length [%s%s]\n", cpio_path, file.name); continue; } if (acpi_table_checksum(file.data, table->length)) { pr_err("ACPI OVERRIDE: Bad table checksum [%s%s]\n", cpio_path, file.name); continue; } pr_info("%4.4s ACPI table found in initrd [%s%s][0x%x]\n", table->signature, cpio_path, file.name, table->length); all_tables_size += table->length; acpi_initrd_files[table_nr].data = file.data; acpi_initrd_files[table_nr].size = file.size; table_nr++; } if (table_nr == 0) return; acpi_tables_addr = memblock_find_in_range(0, max_low_pfn_mapped << PAGE_SHIFT, all_tables_size, PAGE_SIZE); if (!acpi_tables_addr) { WARN_ON(1); return; } /* * Only calling e820_add_reserve does not work and the * tables are invalid (memory got used) later. * memblock_reserve works as expected and the tables won't get modified. * But it's not enough on X86 because ioremap will * complain later (used by acpi_os_map_memory) that the pages * that should get mapped are not marked "reserved". * Both memblock_reserve and e820_add_region (via arch_reserve_mem_area) * works fine. */ memblock_reserve(acpi_tables_addr, all_tables_size); arch_reserve_mem_area(acpi_tables_addr, all_tables_size); /* * early_ioremap only can remap 256k one time. If we map all * tables one time, we will hit the limit. Need to map chunks * one by one during copying the same as that in relocate_initrd(). */ for (no = 0; no < table_nr; no++) { unsigned char *src_p = acpi_initrd_files[no].data; phys_addr_t size = acpi_initrd_files[no].size; phys_addr_t dest_addr = acpi_tables_addr + total_offset; phys_addr_t slop, clen; char *dest_p; total_offset += size; while (size) { slop = dest_addr & ~PAGE_MASK; clen = size; if (clen > MAP_CHUNK_SIZE - slop) clen = MAP_CHUNK_SIZE - slop; dest_p = early_ioremap(dest_addr & PAGE_MASK, clen + slop); memcpy(dest_p + slop, src_p, clen); early_iounmap(dest_p, clen + slop); src_p += clen; dest_addr += clen; size -= clen; } } } Commit Message: acpi: Disable ACPI table override if securelevel is set From the kernel documentation (initrd_table_override.txt): If the ACPI_INITRD_TABLE_OVERRIDE compile option is true, it is possible to override nearly any ACPI table provided by the BIOS with an instrumented, modified one. When securelevel is set, the kernel should disallow any unauthenticated changes to kernel space. ACPI tables contain code invoked by the kernel, so do not allow ACPI tables to be overridden if securelevel is set. Signed-off-by: Linn Crosetto <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static int qcow2_set_key(BlockDriverState *bs, const char *key) { BDRVQcowState *s = bs->opaque; uint8_t keybuf[16]; int len, i; memset(keybuf, 0, 16); len = strlen(key); if (len > 16) len = 16; /* XXX: we could compress the chars to 7 bits to increase entropy */ for(i = 0;i < len;i++) { keybuf[i] = key[i]; } s->crypt_method = s->crypt_method_header; if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0) return -1; if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0) return -1; #if 0 /* test */ { uint8_t in[16]; uint8_t out[16]; uint8_t tmp[16]; for(i=0;i<16;i++) in[i] = i; AES_encrypt(in, tmp, &s->aes_encrypt_key); AES_decrypt(tmp, out, &s->aes_decrypt_key); for(i = 0; i < 16; i++) printf(" %02x", tmp[i]); printf("\n"); for(i = 0; i < 16; i++) printf(" %02x", out[i]); printf("\n"); } #endif return 0; } Commit Message: 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: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ { if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } } ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { WORD32 buf_size; pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ buflen = MIN(buflen, buf_size); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T)) { break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && (ret != IVD_MEM_ALLOC_FAILED) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T)) { return IV_FAIL; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); if(ret != 0) { return IV_FAIL; } } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Commit Message: Decoder: Do not conceal slices with invalid SPS/PPS Bug: 28835995 CWE ID: CWE-172 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 adjust_branches(struct bpf_prog *prog, int pos, int delta) { struct bpf_insn *insn = prog->insnsi; int insn_cnt = prog->len; int i; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) != BPF_JMP || BPF_OP(insn->code) == BPF_CALL || BPF_OP(insn->code) == BPF_EXIT) continue; /* adjust offset of jmps if necessary */ if (i < pos && i + insn->off + 1 > pos) insn->off += delta; else if (i > pos && i + insn->off + 1 < pos) insn->off -= delta; } } Commit Message: bpf: fix branch offset adjustment on backjumps after patching ctx expansion When ctx access is used, the kernel often needs to expand/rewrite instructions, so after that patching, branch offsets have to be adjusted for both forward and backward jumps in the new eBPF program, but for backward jumps it fails to account the delta. Meaning, for example, if the expansion happens exactly on the insn that sits at the jump target, it doesn't fix up the back jump offset. Analysis on what the check in adjust_branches() is currently doing: /* adjust offset of jmps if necessary */ if (i < pos && i + insn->off + 1 > pos) insn->off += delta; else if (i > pos && i + insn->off + 1 < pos) insn->off -= delta; First condition (forward jumps): Before: After: insns[0] insns[0] insns[1] <--- i/insn insns[1] <--- i/insn insns[2] <--- pos insns[P] <--- pos insns[3] insns[P] `------| delta insns[4] <--- target_X insns[P] `-----| insns[5] insns[3] insns[4] <--- target_X insns[5] First case is if we cross pos-boundary and the jump instruction was before pos. This is handeled correctly. I.e. if i == pos, then this would mean our jump that we currently check was the patchlet itself that we just injected. Since such patchlets are self-contained and have no awareness of any insns before or after the patched one, the delta is correctly not adjusted. Also, for the second condition in case of i + insn->off + 1 == pos, means we jump to that newly patched instruction, so no offset adjustment are needed. That part is correct. Second condition (backward jumps): Before: After: insns[0] insns[0] insns[1] <--- target_X insns[1] <--- target_X insns[2] <--- pos <-- target_Y insns[P] <--- pos <-- target_Y insns[3] insns[P] `------| delta insns[4] <--- i/insn insns[P] `-----| insns[5] insns[3] insns[4] <--- i/insn insns[5] Second interesting case is where we cross pos-boundary and the jump instruction was after pos. Backward jump with i == pos would be impossible and pose a bug somewhere in the patchlet, so the first condition checking i > pos is okay only by itself. However, i + insn->off + 1 < pos does not always work as intended to trigger the adjustment. It works when jump targets would be far off where the delta wouldn't matter. But, for example, where the fixed insn->off before pointed to pos (target_Y), it now points to pos + delta, so that additional room needs to be taken into account for the check. This means that i) both tests here need to be adjusted into pos + delta, and ii) for the second condition, the test needs to be <= as pos itself can be a target in the backjump, too. Fixes: 9bac3d6d548e ("bpf: allow extended BPF programs access skb fields") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: void tipc_socket_stop(void) { sock_unregister(tipc_family_ops.family); proto_unregister(&tipc_proto); } Commit Message: tipc: check nl sock before parsing nested attributes Make sure the socket for which the user is listing publication exists before parsing the socket netlink attributes. Prior to this patch a call without any socket caused a NULL pointer dereference in tipc_nl_publ_dump(). Tested-and-reported-by: Baozeng Ding <[email protected]> Signed-off-by: Richard Alpe <[email protected]> Acked-by: Jon Maloy <[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: FLAC__StreamDecoderWriteStatus FLACParser::writeCallback( const FLAC__Frame *frame, const FLAC__int32 * const buffer[]) { if (mWriteRequested) { mWriteRequested = false; mWriteHeader = frame->header; mWriteBuffer = buffer; mWriteCompleted = true; return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE; } else { ALOGE("FLACParser::writeCallback unexpected"); return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT; } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 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: juniper_services_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_services_header { uint8_t svc_id; uint8_t flags_len; uint8_t svc_set_id[2]; uint8_t dir_iif[4]; }; const struct juniper_services_header *sh; l2info.pictype = DLT_JUNIPER_SERVICES; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; sh = (const struct juniper_services_header *)p; if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ", sh->svc_id, sh->flags_len, EXTRACT_16BITS(&sh->svc_set_id), EXTRACT_24BITS(&sh->dir_iif[1]))); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: static void fill32(uint8_t *dst, int len) { uint32_t v = AV_RN32(dst - 4); while (len >= 4) { AV_WN32(dst, v); dst += 4; len -= 4; } while (len--) { *dst = dst[-4]; dst++; } } Commit Message: avutil/mem: Fix flipped condition Fixes return code and later null pointer dereference Found-by: Laurent Butti <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: 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 omx_vdec::release_output_done(void) { bool bRet = false; unsigned i=0,j=0; DEBUG_PRINT_LOW("Value of m_out_mem_ptr %p",m_inp_mem_ptr); if (m_out_mem_ptr) { for (; j < drv_ctx.op_buf.actualcount ; j++) { if (BITMASK_PRESENT(&m_out_bm_count,j)) { break; } } if (j == drv_ctx.op_buf.actualcount) { m_out_bm_count = 0; bRet = true; } } else { m_out_bm_count = 0; bRet = true; } return bRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vdec: add safety checks for freeing buffers Allow only up to 64 buffers on input/output port (since the allocation bitmap is only 64-wide). Do not allow changing theactual buffer count while still holding allocation (Client can technically negotiate buffer count on a free/disabled port) Add safety checks to free only as many buffers were allocated. Fixes: Security Vulnerability - Heap Overflow and Possible Local Privilege Escalation in MediaServer (libOmxVdec problem #3) Bug: 27532282 27661749 Change-Id: I06dd680d43feaef3efdc87311e8a6703e234b523 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: bool NaClProcessHost::SendStart() { if (!enable_ipc_proxy_) { if (!ReplyToRenderer(IPC::ChannelHandle())) return false; } return StartNaClExecution(); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: nfsd4_decode_readdir(struct nfsd4_compoundargs *argp, struct nfsd4_readdir *readdir) { DECODE_HEAD; READ_BUF(24); p = xdr_decode_hyper(p, &readdir->rd_cookie); COPYMEM(readdir->rd_verf.data, sizeof(readdir->rd_verf.data)); readdir->rd_dircount = be32_to_cpup(p++); readdir->rd_maxcount = be32_to_cpup(p++); if ((status = nfsd4_decode_bitmap(argp, readdir->rd_bmval))) goto out; DECODE_TAIL; } 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: do_REMOTE_syscall() { int condor_sysnum; int rval = -1, result = -1, fd = -1, mode = -1, uid = -1, gid = -1; int length = -1; condor_errno_t terrno; char *path = NULL, *buffer = NULL; void *buf = NULL; syscall_sock->decode(); dprintf(D_SYSCALLS, "About to decode condor_sysnum\n"); rval = syscall_sock->code(condor_sysnum); if (!rval) { MyString err_msg; err_msg = "Can no longer talk to condor_starter <"; err_msg += syscall_sock->peer_ip_str(); err_msg += ':'; err_msg += syscall_sock->peer_port(); err_msg += '>'; thisRemoteResource->closeClaimSock(); /* It is possible that we are failing to read the syscall number because the starter went away because we *asked* it to go away. Don't be shocked and surprised if the startd/starter actually did what we asked when we deactivated the claim */ if ( thisRemoteResource->wasClaimDeactivated() ) { return 0; } if( Shadow->supportsReconnect() ) { dprintf( D_ALWAYS, "%s\n", err_msg.Value() ); const char* txt = "Socket between submit and execute hosts " "closed unexpectedly"; Shadow->logDisconnectedEvent( txt ); if (!Shadow->shouldAttemptReconnect(thisRemoteResource)) { dprintf(D_ALWAYS, "This job cannot reconnect to starter, so job exiting\n"); Shadow->gracefulShutDown(); EXCEPT( "%s", err_msg.Value() ); } Shadow->reconnect(); return 0; } else { EXCEPT( "%s", err_msg.Value() ); } } dprintf(D_SYSCALLS, "Got request for syscall %s (%d)\n", shadow_syscall_name(condor_sysnum), condor_sysnum); switch( condor_sysnum ) { case CONDOR_register_starter_info: { ClassAd ad; result = ( ad.initFromStream(*syscall_sock) ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = pseudo_register_starter_info( &ad ); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_register_job_info: { ClassAd ad; result = ( ad.initFromStream(*syscall_sock) ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = pseudo_register_job_info( &ad ); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_get_job_info: { ClassAd *ad = NULL; bool delete_ad; result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = pseudo_get_job_info(ad, delete_ad); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( ad->put(*syscall_sock) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); if ( delete_ad ) { delete ad; } return 0; } case CONDOR_get_user_info: { ClassAd *ad = NULL; result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = pseudo_get_user_info(ad); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( ad->put(*syscall_sock) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_job_exit: { int status=0; int reason=0; ClassAd ad; result = ( syscall_sock->code(status) ); ASSERT( result ); result = ( syscall_sock->code(reason) ); ASSERT( result ); result = ( ad.initFromStream(*syscall_sock) ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = pseudo_job_exit(status, reason, &ad); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return -1; } case CONDOR_job_termination: { ClassAd ad; result = ( ad.initFromStream(*syscall_sock) ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = pseudo_job_termination( &ad ); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_begin_execution: { result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = pseudo_begin_execution(); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_open: { open_flags_t flags; int lastarg; result = ( syscall_sock->code(flags) ); ASSERT( result ); dprintf( D_SYSCALLS, " flags = %d\n", flags ); result = ( syscall_sock->code(lastarg) ); ASSERT( result ); dprintf( D_SYSCALLS, " lastarg = %d\n", lastarg ); path = NULL; result = ( syscall_sock->code(path) ); dprintf( D_SYSCALLS, " path = %s\n", path ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); bool access_ok; if ( flags & O_RDONLY ) { access_ok = read_access(path); } else { access_ok = write_access(path); } errno = 0; if ( access_ok ) { rval = safe_open_wrapper_follow( path , flags , lastarg); } else { rval = -1; errno = EACCES; } terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char *)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_close: { result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = close( fd); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_read: { size_t len; result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->code(len) ); ASSERT( result ); dprintf( D_SYSCALLS, " len = %ld\n", (long)len ); buf = (void *)malloc( (unsigned)len ); memset( buf, 0, (unsigned)len ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = read( fd , buf , len); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } if( rval >= 0 ) { result = ( syscall_sock->code_bytes_bool(buf, rval) ); ASSERT( result ); } free( buf ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_write: { size_t len; result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->code(len) ); ASSERT( result ); dprintf( D_SYSCALLS, " len = %ld\n", (long)len ); buf = (void *)malloc( (unsigned)len ); memset( buf, 0, (unsigned)len ); result = ( syscall_sock->code_bytes_bool(buf, len) ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = write( fd , buf , len); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( buf ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_lseek: case CONDOR_lseek64: case CONDOR_llseek: { off_t offset; int whence; result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->code(offset) ); ASSERT( result ); dprintf( D_SYSCALLS, " offset = %ld\n", (long)offset ); result = ( syscall_sock->code(whence) ); ASSERT( result ); dprintf( D_SYSCALLS, " whence = %d\n", whence ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = lseek( fd , offset , whence); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_unlink: { path = NULL; result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); if ( write_access(path) ) { errno = 0; rval = unlink( path); } else { rval = -1; errno = EACCES; } terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char *)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_rename: { char * from; char * to; to = NULL; from = NULL; result = ( syscall_sock->code(from) ); ASSERT( result ); dprintf( D_SYSCALLS, " from = %s\n", from ); result = ( syscall_sock->code(to) ); ASSERT( result ); dprintf( D_SYSCALLS, " to = %s\n", to ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); if ( write_access(from) && write_access(to) ) { errno = 0; rval = rename( from , to); } else { rval = -1; errno = EACCES; } terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char *)to ); free( (char *)from ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_register_mpi_master_info: { ClassAd ad; result = ( ad.initFromStream(*syscall_sock) ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = pseudo_register_mpi_master_info( &ad ); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_mkdir: { path = NULL; result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->code(mode) ); ASSERT( result ); dprintf( D_SYSCALLS, " mode = %d\n", mode ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); if ( write_access(path) ) { errno = 0; rval = mkdir(path,mode); } else { rval = -1; errno = EACCES; } terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char *)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_rmdir: { path = NULL; result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); if ( write_access(path) ) { errno = 0; rval = rmdir( path); } else { rval = -1; errno = EACCES; } terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_fsync: { result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fs = %d\n", fd ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = fsync(fd); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_get_file_info_new: { char * logical_name; char * actual_url; actual_url = NULL; logical_name = NULL; ASSERT( syscall_sock->code(logical_name) ); ASSERT( syscall_sock->end_of_message() );; errno = (condor_errno_t)0; rval = pseudo_get_file_info_new( logical_name , actual_url ); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, (int)terrno ); syscall_sock->encode(); ASSERT( syscall_sock->code(rval) ); if( rval < 0 ) { ASSERT( syscall_sock->code(terrno) ); } if( rval >= 0 ) { ASSERT( syscall_sock->code(actual_url) ); } free( (char *)actual_url ); free( (char *)logical_name ); ASSERT( syscall_sock->end_of_message() );; return 0; } case CONDOR_ulog: { ClassAd ad; result = ( ad.initFromStream(*syscall_sock) ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); rval = pseudo_ulog(&ad); dprintf( D_SYSCALLS, "\trval = %d\n", rval ); return 0; } case CONDOR_get_job_attr: { char * attrname = 0; assert( syscall_sock->code(attrname) ); assert( syscall_sock->end_of_message() );; errno = (condor_errno_t)0; MyString expr; if ( thisRemoteResource->allowRemoteReadAttributeAccess(attrname) ) { rval = pseudo_get_job_attr( attrname , expr); terrno = (condor_errno_t)errno; } else { rval = -1; terrno = (condor_errno_t)EACCES; } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, (int)terrno ); syscall_sock->encode(); assert( syscall_sock->code(rval) ); if( rval < 0 ) { assert( syscall_sock->code(terrno) ); } if( rval >= 0 ) { assert( syscall_sock->put(expr.Value()) ); } free( (char *)attrname ); assert( syscall_sock->end_of_message() );; return 0; } case CONDOR_set_job_attr: { char * attrname = 0; char * expr = 0; assert( syscall_sock->code(expr) ); assert( syscall_sock->code(attrname) ); assert( syscall_sock->end_of_message() );; errno = (condor_errno_t)0; if ( thisRemoteResource->allowRemoteWriteAttributeAccess(attrname) ) { rval = pseudo_set_job_attr( attrname , expr , true ); terrno = (condor_errno_t)errno; } else { rval = -1; terrno = (condor_errno_t)EACCES; } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, (int)terrno ); syscall_sock->encode(); assert( syscall_sock->code(rval) ); if( rval < 0 ) { assert( syscall_sock->code(terrno) ); } free( (char *)expr ); free( (char *)attrname ); assert( syscall_sock->end_of_message() );; return 0; } case CONDOR_constrain: { char * expr = 0; assert( syscall_sock->code(expr) ); assert( syscall_sock->end_of_message() );; errno = (condor_errno_t)0; if ( thisRemoteResource->allowRemoteWriteAttributeAccess(ATTR_REQUIREMENTS) ) { rval = pseudo_constrain( expr); terrno = (condor_errno_t)errno; } else { rval = -1; terrno = (condor_errno_t)EACCES; } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, (int)terrno ); syscall_sock->encode(); assert( syscall_sock->code(rval) ); if( rval < 0 ) { assert( syscall_sock->code(terrno) ); } free( (char *)expr ); assert( syscall_sock->end_of_message() );; return 0; } case CONDOR_get_sec_session_info: { MyString starter_reconnect_session_info; MyString starter_filetrans_session_info; MyString reconnect_session_id; MyString reconnect_session_info; MyString reconnect_session_key; MyString filetrans_session_id; MyString filetrans_session_info; MyString filetrans_session_key; bool socket_default_crypto = syscall_sock->get_encryption(); if( !socket_default_crypto ) { syscall_sock->set_crypto_mode(true); } assert( syscall_sock->code(starter_reconnect_session_info) ); assert( syscall_sock->code(starter_filetrans_session_info) ); assert( syscall_sock->end_of_message() ); errno = (condor_errno_t)0; rval = pseudo_get_sec_session_info( starter_reconnect_session_info.Value(), reconnect_session_id, reconnect_session_info, reconnect_session_key, starter_filetrans_session_info.Value(), filetrans_session_id, filetrans_session_info, filetrans_session_key ); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, (int)terrno ); syscall_sock->encode(); assert( syscall_sock->code(rval) ); if( rval < 0 ) { assert( syscall_sock->code(terrno) ); } else { assert( syscall_sock->code(reconnect_session_id) ); assert( syscall_sock->code(reconnect_session_info) ); assert( syscall_sock->code(reconnect_session_key) ); assert( syscall_sock->code(filetrans_session_id) ); assert( syscall_sock->code(filetrans_session_info) ); assert( syscall_sock->code(filetrans_session_key) ); } assert( syscall_sock->end_of_message() ); if( !socket_default_crypto ) { syscall_sock->set_crypto_mode( false ); // restore default } return 0; } #ifdef WIN32 #else case CONDOR_pread: { size_t len, offset; result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->code(len) ); ASSERT( result ); dprintf( D_SYSCALLS, " len = %ld\n", (long)len ); result = ( syscall_sock->code(offset) ); ASSERT( result ); dprintf( D_SYSCALLS, " offset = %ld\n", (long)offset ); buf = (void *)malloc( (unsigned)len ); memset( buf, 0, (unsigned)len ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = pread( fd , buf , len, offset ); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->code_bytes_bool(buf, rval) ); ASSERT( result ); } free( buf ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_pwrite: { size_t len, offset; result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->code(len) ); ASSERT( result ); dprintf( D_SYSCALLS, " len = %ld\n", (long)len ); result = ( syscall_sock->code(offset) ); ASSERT( result ); dprintf( D_SYSCALLS, " offset = %ld\n", (long)offset); buf = malloc( (unsigned)len ); memset( buf, 0, (unsigned)len ); result = ( syscall_sock->code_bytes_bool(buf, len) ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = pwrite( fd , buf , len, offset); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( buf ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_sread: { size_t len, offset, stride_length, stride_skip; result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->code(len) ); ASSERT( result ); dprintf( D_SYSCALLS, " len = %ld\n", (long)len ); result = ( syscall_sock->code(offset) ); ASSERT( result ); dprintf( D_SYSCALLS, " offset = %ld\n", (long)offset ); result = ( syscall_sock->code(stride_length) ); ASSERT( result ); dprintf( D_SYSCALLS, " stride_length = %ld\n", (long)stride_length); result = ( syscall_sock->code(stride_skip) ); ASSERT( result ); dprintf( D_SYSCALLS, " stride_skip = %ld\n", (long)stride_skip); buf = (void *)malloc( (unsigned)len ); memset( buf, 0, (unsigned)len ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = EINVAL; rval = -1; unsigned int total = 0; buffer = (char*)buf; while(total < len && stride_length > 0) { if(len - total < stride_length) { stride_length = len - total; } rval = pread( fd, (void*)&buffer[total], stride_length, offset ); if(rval >= 0) { total += rval; offset += stride_skip; } else { break; } } syscall_sock->encode(); if( rval < 0 ) { result = ( syscall_sock->code(rval) ); ASSERT( result ); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", total, terrno ); result = ( syscall_sock->code(total) ); ASSERT( result ); dprintf( D_ALWAYS, "buffer: %s\n", buffer); result = ( syscall_sock->code_bytes_bool(buf, total) ); ASSERT( result ); } free( buf ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_swrite: { size_t len, offset, stride_length, stride_skip; result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->code(len) ); ASSERT( result ); dprintf( D_SYSCALLS, " len = %ld\n", (long)len ); result = ( syscall_sock->code(offset) ); ASSERT( result ); dprintf( D_SYSCALLS, " offset = %ld\n", (long)offset); result = ( syscall_sock->code(stride_length) ); ASSERT( result ); dprintf( D_SYSCALLS, " stride_length = %ld\n", (long)stride_length); result = ( syscall_sock->code(stride_skip) ); ASSERT( result ); dprintf( D_SYSCALLS, " stride_skip = %ld\n", (long)stride_skip); buf = (void *)malloc( (unsigned)len ); memset( buf, 0, (unsigned)len ); result = ( syscall_sock->code_bytes_bool(buf, len) ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = EINVAL; rval = -1; unsigned int total = 0; buffer = (char*)buf; while(total < len && stride_length > 0) { if(len - total < stride_length) { stride_length = len - total; } rval = pwrite( fd, (void*)&buffer[total], stride_length, offset); if(rval >= 0) { total += rval; offset += stride_skip; } else { break; } } syscall_sock->encode(); if( rval < 0 ) { terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d (%s)\n", rval, terrno, strerror(errno)); result = ( syscall_sock->code(rval) ); ASSERT( result ); result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { dprintf( D_SYSCALLS, "\trval = %d, errno = %d (%s)\n", total, terrno, strerror(errno)); result = ( syscall_sock->code(total) ); ASSERT( result ); } free( buf ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_rmall: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; if ( write_access(path) ) { rval = rmdir(path); if(rval == -1) { Directory dir(path); if(dir.Remove_Entire_Directory()) { rval = rmdir(path); } } } else { rval = -1; errno = EACCES; } terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char *)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_getfile: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; fd = safe_open_wrapper_follow( path, O_RDONLY ); if(fd >= 0) { struct stat info; stat(path, &info); length = info.st_size; buf = (void *)malloc( (unsigned)length ); memset( buf, 0, (unsigned)length ); errno = 0; rval = read( fd , buf , length); } else { rval = fd; } terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->code_bytes_bool(buf, rval) ); ASSERT( result ); } free( (char *)path ); free( buf ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_putfile: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf(D_SYSCALLS, " path: %s\n", path); result = ( syscall_sock->code(mode) ); ASSERT( result ); dprintf(D_SYSCALLS, " mode: %d\n", mode); result = ( syscall_sock->code(length) ); ASSERT( result ); dprintf(D_SYSCALLS, " length: %d\n", length); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; fd = safe_open_wrapper_follow(path, O_CREAT | O_WRONLY | O_TRUNC, mode); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(fd) ); ASSERT( result ); if( fd < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); int num = -1; if(fd >= 0) { syscall_sock->decode(); buffer = (char*)malloc( (unsigned)length ); memset( buffer, 0, (unsigned)length ); result = ( syscall_sock->code_bytes_bool(buffer, length) ); ASSERT( result ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); num = write(fd, buffer, length); } else { dprintf(D_SYSCALLS, "Unable to put file %s\n", path); } close(fd); syscall_sock->encode(); result = ( syscall_sock->code(num) ); ASSERT( result ); if( num < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free((char*)path); free((char*)buffer); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_getlongdir: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = -1; MyString msg, check; const char *next; Directory directory(path); struct stat stat_buf; char line[1024]; while((next = directory.Next())) { dprintf(D_ALWAYS, "next: %s\n", next); msg.sprintf_cat("%s\n", next); check.sprintf("%s%c%s", path, DIR_DELIM_CHAR, next); rval = stat(check.Value(), &stat_buf); terrno = (condor_errno_t)errno; if(rval == -1) { break; } if(stat_string(line, &stat_buf) < 0) { rval = -1; break; } msg.sprintf_cat("%s", line); } terrno = (condor_errno_t)errno; if(msg.Length() > 0) { msg.sprintf_cat("\n"); // Needed to signify end of data rval = msg.Length(); } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->put(msg.Value()) ); ASSERT( result ); } free((char*)path); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_getdir: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = -1; MyString msg; const char *next; Directory directory(path); while((next = directory.Next())) { msg.sprintf_cat(next); msg.sprintf_cat("\n"); } terrno = (condor_errno_t)errno; if(msg.Length() > 0) { msg.sprintf_cat("\n"); // Needed to signify end of data rval = msg.Length(); } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->put(msg.Value()) ); ASSERT( result ); } free((char*)path); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_whoami: { result = ( syscall_sock->code(length) ); ASSERT( result ); dprintf( D_SYSCALLS, " length = %d\n", length ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; buffer = (char*)malloc( (unsigned)length ); int size = 6; if(length < size) { rval = -1; terrno = (condor_errno_t) ENOSPC; } else { rval = sprintf(buffer, "CONDOR"); terrno = (condor_errno_t) errno; } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval != size) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->code_bytes_bool(buffer, rval)); ASSERT( result ); } free((char*)buffer); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_whoareyou: { char *host = NULL; result = ( syscall_sock->code(host) ); ASSERT( result ); dprintf( D_SYSCALLS, " host = %s\n", host ); result = ( syscall_sock->code(length) ); ASSERT( result ); dprintf( D_SYSCALLS, " length = %d\n", length ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; buffer = (char*)malloc( (unsigned)length ); int size = 7; if(length < size) { rval = -1; terrno = (condor_errno_t) ENOSPC; } else { rval = sprintf(buffer, "UNKNOWN"); terrno = (condor_errno_t) errno; } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval != size) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->code_bytes_bool(buffer, rval)); ASSERT( result ); } free((char*)buffer); free((char*)host); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_fstatfs: { result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; #if defined(Solaris) struct statvfs statfs_buf; rval = fstatvfs(fd, &statfs_buf); #else struct statfs statfs_buf; rval = fstatfs(fd, &statfs_buf); #endif terrno = (condor_errno_t)errno; char line[1024]; if(rval == 0) { if(statfs_string(line, &statfs_buf) < 0) { rval = -1; terrno = (condor_errno_t)errno; } } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->code_bytes_bool(line, 1024) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_fchown: { result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->code(uid) ); ASSERT( result ); dprintf( D_SYSCALLS, " uid = %d\n", uid ); result = ( syscall_sock->code(gid) ); ASSERT( result ); dprintf( D_SYSCALLS, " gid = %d\n", gid ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = fchown(fd, uid, gid); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_fchmod: { result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->code(mode) ); ASSERT( result ); dprintf( D_SYSCALLS, " mode = %d\n", mode ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = fchmod(fd, (mode_t)mode); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if(rval < 0) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_ftruncate: { result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->code(length) ); ASSERT( result ); dprintf( D_SYSCALLS, " length = %d\n", length ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = ftruncate(fd, length); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if(rval < 0) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_link: { char *newpath = NULL; result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->code(newpath) ); ASSERT( result ); dprintf( D_SYSCALLS, " newpath = %s\n", newpath ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = link(path, newpath); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if(rval < 0) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free((char*)path); free((char*)newpath); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_symlink: { char *newpath = NULL; result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->code(newpath) ); ASSERT( result ); dprintf( D_SYSCALLS, " newpath = %s\n", newpath ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = symlink(path, newpath); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if(rval < 0) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free((char*)path); free((char*)newpath); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_readlink: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->code(length) ); ASSERT( result ); dprintf( D_SYSCALLS, " length = %d\n", length ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); char *lbuffer = (char*)malloc(length); errno = 0; rval = readlink(path, lbuffer, length); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->code_bytes_bool(lbuffer, rval)); ASSERT( result ); } free(lbuffer); free(path); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_lstat: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; struct stat stat_buf; rval = lstat(path, &stat_buf); terrno = (condor_errno_t)errno; char line[1024]; if(rval == 0) { if(stat_string(line, &stat_buf) < 0) { rval = -1; terrno = (condor_errno_t)errno; } } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->code_bytes_bool(line, 1024) ); ASSERT( result ); } free( (char*)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_statfs: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; #if defined(Solaris) struct statvfs statfs_buf; rval = statvfs(path, &statfs_buf); #else struct statfs statfs_buf; rval = statfs(path, &statfs_buf); #endif terrno = (condor_errno_t)errno; char line[1024]; if(rval == 0) { if(statfs_string(line, &statfs_buf) < 0) { rval = -1; terrno = (condor_errno_t)errno; } } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->code_bytes_bool(line, 1024) ); ASSERT( result ); } free( (char*)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_chown: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->code(uid) ); ASSERT( result ); dprintf( D_SYSCALLS, " uid = %d\n", uid ); result = ( syscall_sock->code(gid) ); ASSERT( result ); dprintf( D_SYSCALLS, " gid = %d\n", gid ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = chown(path, uid, gid); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char*)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_lchown: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->code(uid) ); ASSERT( result ); dprintf( D_SYSCALLS, " uid = %d\n", uid ); result = ( syscall_sock->code(gid) ); ASSERT( result ); dprintf( D_SYSCALLS, " gid = %d\n", gid ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = lchown(path, uid, gid); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char*)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_truncate: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->code(length) ); ASSERT( result ); dprintf( D_SYSCALLS, " length = %d\n", length ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; if ( write_access(path) ) { errno = 0; rval = truncate(path, length); } else { rval = -1; errno = EACCES; } terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if(rval < 0) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char*)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } #endif // ! WIN32 case CONDOR_fstat: { result = ( syscall_sock->code(fd) ); ASSERT( result ); dprintf( D_SYSCALLS, " fd = %d\n", fd ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; struct stat stat_buf; rval = fstat(fd, &stat_buf); terrno = (condor_errno_t)errno; char line[1024]; if(rval == 0) { if(stat_string(line, &stat_buf) < 0) { rval = -1; terrno = (condor_errno_t)errno; } } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->code_bytes_bool(line, 1024) ); ASSERT( result ); } result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_stat: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; struct stat stat_buf; rval = stat(path, &stat_buf); terrno = (condor_errno_t)errno; char line[1024]; if(rval == 0) { if(stat_string(line, &stat_buf) < 0) { rval = -1; terrno = (condor_errno_t)errno; } } dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if( rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } else { result = ( syscall_sock->code_bytes_bool(line, 1024) ); ASSERT( result ); } free( (char*)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_access: { int flags = -1; result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->code(flags) ); ASSERT( result ); dprintf( D_SYSCALLS, " flags = %d\n", flags ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = access(path, flags); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if(rval < 0 ) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char*)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_chmod: { result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->code(mode) ); ASSERT( result ); dprintf( D_SYSCALLS, " mode = %d\n", mode ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); errno = 0; rval = chmod(path, mode); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if(rval < 0) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char*)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } case CONDOR_utime: { time_t actime = -1, modtime = -1; result = ( syscall_sock->code(path) ); ASSERT( result ); dprintf( D_SYSCALLS, " path = %s\n", path ); result = ( syscall_sock->code(actime) ); ASSERT( result ); dprintf( D_SYSCALLS, " actime = %ld\n", actime ); result = ( syscall_sock->code(modtime) ); ASSERT( result ); dprintf( D_SYSCALLS, " modtime = %ld\n", modtime ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); struct utimbuf ut; ut.actime = actime; ut.modtime = modtime; errno = 0; rval = utime(path, &ut); terrno = (condor_errno_t)errno; dprintf( D_SYSCALLS, "\trval = %d, errno = %d\n", rval, terrno ); syscall_sock->encode(); result = ( syscall_sock->code(rval) ); ASSERT( result ); if(rval < 0) { result = ( syscall_sock->code( terrno ) ); ASSERT( result ); } free( (char*)path ); result = ( syscall_sock->end_of_message() ); ASSERT( result ); return 0; } default: { dprintf(D_ALWAYS, "ERROR: unknown syscall %d received\n", condor_sysnum ); return 0; } } /* End of switch on system call number */ return -1; } /* End of do_REMOTE_syscall() procedure */ Commit Message: CWE ID: CWE-134 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 dev_load(struct net *net, const char *name) { struct net_device *dev; rcu_read_lock(); dev = dev_get_by_name_rcu(net, name); rcu_read_unlock(); if (!dev && capable(CAP_NET_ADMIN)) request_module("%s", name); } Commit Message: net: don't allow CAP_NET_ADMIN to load non-netdev kernel modules Since a8f80e8ff94ecba629542d9b4b5f5a8ee3eb565c any process with CAP_NET_ADMIN may load any module from /lib/modules/. This doesn't mean that CAP_NET_ADMIN is a superset of CAP_SYS_MODULE as modules are limited to /lib/modules/**. However, CAP_NET_ADMIN capability shouldn't allow anybody load any module not related to networking. This patch restricts an ability of autoloading modules to netdev modules with explicit aliases. This fixes CVE-2011-1019. Arnd Bergmann suggested to leave untouched the old pre-v2.6.32 behavior of loading netdev modules by name (without any prefix) for processes with CAP_SYS_MODULE to maintain the compatibility with network scripts that use autoloading netdev modules by aliases like "eth0", "wlan0". Currently there are only three users of the feature in the upstream kernel: ipip, ip_gre and sit. root@albatros:~# capsh --drop=$(seq -s, 0 11),$(seq -s, 13 34) -- root@albatros:~# grep Cap /proc/$$/status CapInh: 0000000000000000 CapPrm: fffffff800001000 CapEff: fffffff800001000 CapBnd: fffffff800001000 root@albatros:~# modprobe xfs FATAL: Error inserting xfs (/lib/modules/2.6.38-rc6-00001-g2bf4ca3/kernel/fs/xfs/xfs.ko): Operation not permitted root@albatros:~# lsmod | grep xfs root@albatros:~# ifconfig xfs xfs: error fetching interface information: Device not found root@albatros:~# lsmod | grep xfs root@albatros:~# lsmod | grep sit root@albatros:~# ifconfig sit sit: error fetching interface information: Device not found root@albatros:~# lsmod | grep sit root@albatros:~# ifconfig sit0 sit0 Link encap:IPv6-in-IPv4 NOARP MTU:1480 Metric:1 root@albatros:~# lsmod | grep sit sit 10457 0 tunnel4 2957 1 sit For CAP_SYS_MODULE module loading is still relaxed: root@albatros:~# grep Cap /proc/$$/status CapInh: 0000000000000000 CapPrm: ffffffffffffffff CapEff: ffffffffffffffff CapBnd: ffffffffffffffff root@albatros:~# ifconfig xfs xfs: error fetching interface information: Device not found root@albatros:~# lsmod | grep xfs xfs 745319 0 Reference: https://lkml.org/lkml/2011/2/24/203 Signed-off-by: Vasiliy Kulikov <[email protected]> Signed-off-by: Michael Tokarev <[email protected]> Acked-by: David S. Miller <[email protected]> Acked-by: Kees Cook <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void RenderFrameImpl::DidAddContentSecurityPolicies( const blink::WebVector<blink::WebContentSecurityPolicy>& policies) { std::vector<ContentSecurityPolicy> content_policies; for (const auto& policy : policies) content_policies.push_back(BuildContentSecurityPolicy(policy)); Send(new FrameHostMsg_DidAddContentSecurityPolicies(routing_id_, content_policies)); } 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 void devinet_sysctl_unregister(struct in_device *idev) { } Commit Message: ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <[email protected]> Signed-off-by: David S. Miller <[email protected]> Tested-by: Cyrill Gorcunov <[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: OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() { CHECK(mHandle != NULL); memset(mHandle, 0, sizeof(tagvideoEncControls)); CHECK(mEncParams != NULL); memset(mEncParams, 0, sizeof(tagvideoEncOptions)); if (!PVGetDefaultEncOption(mEncParams, 0)) { ALOGE("Failed to get default encoding parameters"); return OMX_ErrorUndefined; } mEncParams->encMode = mEncodeMode; mEncParams->encWidth[0] = mWidth; mEncParams->encHeight[0] = mHeight; mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format mEncParams->rcType = VBR_1; mEncParams->vbvDelay = 5.0f; mEncParams->profile_level = CORE_PROFILE_LEVEL2; mEncParams->packetSize = 32; mEncParams->rvlcEnable = PV_OFF; mEncParams->numLayers = 1; mEncParams->timeIncRes = 1000; mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate; mEncParams->bitRate[0] = mBitrate; mEncParams->iQuant[0] = 15; mEncParams->pQuant[0] = 12; mEncParams->quantType[0] = 0; mEncParams->noFrameSkipped = PV_OFF; if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) { free(mInputFrameData); mInputFrameData = (uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1); CHECK(mInputFrameData != NULL); } if (mWidth % 16 != 0 || mHeight % 16 != 0) { ALOGE("Video frame size %dx%d must be a multiple of 16", mWidth, mHeight); return OMX_ErrorBadParameter; } if (mIDRFrameRefreshIntervalInSec < 0) { mEncParams->intraPeriod = -1; } else if (mIDRFrameRefreshIntervalInSec == 0) { mEncParams->intraPeriod = 1; // All I frames } else { mEncParams->intraPeriod = (mIDRFrameRefreshIntervalInSec * mFramerate) >> 16; } mEncParams->numIntraMB = 0; mEncParams->sceneDetect = PV_ON; mEncParams->searchRange = 16; mEncParams->mv8x8Enable = PV_OFF; mEncParams->gobHeaderInterval = 0; mEncParams->useACPred = PV_ON; mEncParams->intraDCVlcTh = 0; return OMX_ErrorNone; } Commit Message: DO NOT MERGE - libstagefright: check requested memory size before allocation for SoftMPEG4Encoder and SoftVPXEncoder. Bug: 25812794 Change-Id: I96dc74734380d462583f6efa33d09946f9532809 (cherry picked from commit 87f8cbb223ee516803dbb99699320c2484cbf3ba) (cherry picked from commit 0462975291796e414891e04bcec9da993914e458) CWE ID: CWE-119 Target: 1 Example 2: Code: int ssl3_send_client_key_exchange(SSL *s) { unsigned char *p; int n; unsigned long alg_k; #ifndef OPENSSL_NO_RSA unsigned char *q; EVP_PKEY *pkey=NULL; #endif #ifndef OPENSSL_NO_KRB5 KSSL_ERR kssl_err; #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH EC_KEY *clnt_ecdh = NULL; const EC_POINT *srvr_ecpoint = NULL; EVP_PKEY *srvr_pub_pkey = NULL; unsigned char *encodedPoint = NULL; int encoded_pt_len = 0; BN_CTX * bn_ctx = NULL; #endif if (s->state == SSL3_ST_CW_KEY_EXCH_A) { p = ssl_handshake_start(s); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; /* Fool emacs indentation */ if (0) {} #ifndef OPENSSL_NO_RSA else if (alg_k & SSL_kRSA) { RSA *rsa; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; if (s->session->sess_cert == NULL) { /* We should always have a server certificate with SSL_kRSA. */ SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } if (s->session->sess_cert->peer_rsa_tmp != NULL) rsa=s->session->sess_cert->peer_rsa_tmp; else { pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } rsa=pkey->pkey.rsa; EVP_PKEY_free(pkey); } tmp_buf[0]=s->client_version>>8; tmp_buf[1]=s->client_version&0xff; if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) goto err; s->session->master_key_length=sizeof tmp_buf; q=p; /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) p+=2; n=RSA_public_encrypt(sizeof tmp_buf, tmp_buf,p,rsa,RSA_PKCS1_PADDING); #ifdef PKCS1_CHECK if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++; if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70; #endif if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT); goto err; } /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) { s2n(n,q); n+=2; } s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, tmp_buf,sizeof tmp_buf); OPENSSL_cleanse(tmp_buf,sizeof tmp_buf); } #endif #ifndef OPENSSL_NO_KRB5 else if (alg_k & SSL_kKRB5) { krb5_error_code krb5rc; KSSL_CTX *kssl_ctx = s->kssl_ctx; /* krb5_data krb5_ap_req; */ krb5_data *enc_ticket; krb5_data authenticator, *authp = NULL; EVP_CIPHER_CTX ciph_ctx; const EVP_CIPHER *enc = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_IV_LENGTH]; int padl, outl = sizeof(epms); EVP_CIPHER_CTX_init(&ciph_ctx); #ifdef KSSL_DEBUG fprintf(stderr,"ssl3_send_client_key_exchange(%lx & %lx)\n", alg_k, SSL_kKRB5); #endif /* KSSL_DEBUG */ authp = NULL; #ifdef KRB5SENDAUTH if (KRB5SENDAUTH) authp = &authenticator; #endif /* KRB5SENDAUTH */ krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, &kssl_err); enc = kssl_map_enc(kssl_ctx->enctype); if (enc == NULL) goto err; #ifdef KSSL_DEBUG { fprintf(stderr,"kssl_cget_tkt rtn %d\n", krb5rc); if (krb5rc && kssl_err.text) fprintf(stderr,"kssl_cget_tkt kssl_err=%s\n", kssl_err.text); } #endif /* KSSL_DEBUG */ if (krb5rc) { ssl3_send_alert(s,SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } /*- * 20010406 VRS - Earlier versions used KRB5 AP_REQ * in place of RFC 2712 KerberosWrapper, as in: * * Send ticket (copy to *p, set n = length) * n = krb5_ap_req.length; * memcpy(p, krb5_ap_req.data, krb5_ap_req.length); * if (krb5_ap_req.data) * kssl_krb5_free_data_contents(NULL,&krb5_ap_req); * * Now using real RFC 2712 KerberosWrapper * (Thanks to Simon Wilkinson <[email protected]>) * Note: 2712 "opaque" types are here replaced * with a 2-byte length followed by the value. * Example: * KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms * Where "xx xx" = length bytes. Shown here with * optional authenticator omitted. */ /* KerberosWrapper.Ticket */ s2n(enc_ticket->length,p); memcpy(p, enc_ticket->data, enc_ticket->length); p+= enc_ticket->length; n = enc_ticket->length + 2; /* KerberosWrapper.Authenticator */ if (authp && authp->length) { s2n(authp->length,p); memcpy(p, authp->data, authp->length); p+= authp->length; n+= authp->length + 2; free(authp->data); authp->data = NULL; authp->length = 0; } else { s2n(0,p);/* null authenticator length */ n+=2; } tmp_buf[0]=s->client_version>>8; tmp_buf[1]=s->client_version&0xff; if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) goto err; /*- * 20010420 VRS. Tried it this way; failed. * EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL); * EVP_CIPHER_CTX_set_key_length(&ciph_ctx, * kssl_ctx->length); * EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv); */ memset(iv, 0, sizeof iv); /* per RFC 1510 */ EVP_EncryptInit_ex(&ciph_ctx,enc, NULL, kssl_ctx->key,iv); EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf, sizeof tmp_buf); EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl); outl += padl; if (outl > (int)sizeof epms) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } EVP_CIPHER_CTX_cleanup(&ciph_ctx); /* KerberosWrapper.EncryptedPreMasterSecret */ s2n(outl,p); memcpy(p, epms, outl); p+=outl; n+=outl + 2; s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(epms, outl); } #endif #ifndef OPENSSL_NO_DH else if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) { DH *dh_srvr,*dh_clnt; SESS_CERT *scert = s->session->sess_cert; if (scert == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto err; } if (scert->peer_dh_tmp != NULL) dh_srvr=scert->peer_dh_tmp; else { /* we get them from the cert */ int idx = scert->peer_cert_type; EVP_PKEY *spkey = NULL; dh_srvr = NULL; if (idx >= 0) spkey = X509_get_pubkey( scert->peer_pkeys[idx].x509); if (spkey) { dh_srvr = EVP_PKEY_get1_DH(spkey); EVP_PKEY_free(spkey); } if (dh_srvr == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) { /* Use client certificate key */ EVP_PKEY *clkey = s->cert->key->privatekey; dh_clnt = NULL; if (clkey) dh_clnt = EVP_PKEY_get1_DH(clkey); if (dh_clnt == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } else { /* generate a new random key */ if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } if (!DH_generate_key(dh_clnt)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); DH_free(dh_clnt); goto err; } } /* use the 'p' output buffer for the DH key, but * make sure to clear it out afterwards */ n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt); if (scert->peer_dh_tmp == NULL) DH_free(dh_srvr); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); DH_free(dh_clnt); goto err; } /* generate master key from the result */ s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,p,n); /* clean up */ memset(p,0,n); if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) n = 0; else { /* send off the data */ n=BN_num_bytes(dh_clnt->pub_key); s2n(n,p); BN_bn2bin(dh_clnt->pub_key,p); n+=2; } DH_free(dh_clnt); /* perhaps clean things up a bit EAY EAY EAY EAY*/ } #endif #ifndef OPENSSL_NO_ECDH else if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) { const EC_GROUP *srvr_group = NULL; EC_KEY *tkey; int ecdh_clnt_cert = 0; int field_size = 0; if (s->session->sess_cert == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto err; } /* Did we send out the client's * ECDH share for use in premaster * computation as part of client certificate? * If so, set ecdh_clnt_cert to 1. */ if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) { /*- * XXX: For now, we do not support client * authentication using ECDH certificates. * To add such support, one needs to add * code that checks for appropriate * conditions and sets ecdh_clnt_cert to 1. * For example, the cert have an ECC * key on the same curve as the server's * and the key should be authorized for * key agreement. * * One also needs to add code in ssl3_connect * to skip sending the certificate verify * message. * * if ((s->cert->key->privatekey != NULL) && * (s->cert->key->privatekey->type == * EVP_PKEY_EC) && ...) * ecdh_clnt_cert = 1; */ } if (s->session->sess_cert->peer_ecdh_tmp != NULL) { tkey = s->session->sess_cert->peer_ecdh_tmp; } else { /* Get the Server Public Key from Cert */ srvr_pub_pkey = X509_get_pubkey(s->session-> \ sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); if ((srvr_pub_pkey == NULL) || (srvr_pub_pkey->type != EVP_PKEY_EC) || (srvr_pub_pkey->pkey.ec == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } tkey = srvr_pub_pkey->pkey.ec; } srvr_group = EC_KEY_get0_group(tkey); srvr_ecpoint = EC_KEY_get0_public_key(tkey); if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((clnt_ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (ecdh_clnt_cert) { /* Reuse key info from our certificate * We only need our private key to perform * the ECDH computation. */ const BIGNUM *priv_key; tkey = s->cert->key->privatekey->pkey.ec; priv_key = EC_KEY_get0_private_key(tkey); if (priv_key == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } } else { /* Generate a new ECDH key pair */ if (!(EC_KEY_generate_key(clnt_ecdh))) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } } /* use the 'p' output buffer for the ECDH key, but * make sure to clear it out afterwards */ field_size = EC_GROUP_get_degree(srvr_group); if (field_size <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } /* generate master key from the result */ s->session->master_key_length = s->method->ssl3_enc \ -> generate_master_secret(s, s->session->master_key, p, n); memset(p, 0, n); /* clean up */ if (ecdh_clnt_cert) { /* Send empty client key exch message */ n = 0; } else { /* First check the size of encoding and * allocate memory accordingly. */ encoded_pt_len = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); encodedPoint = (unsigned char *) OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char)); bn_ctx = BN_CTX_new(); if ((encodedPoint == NULL) || (bn_ctx == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Encode the public key */ n = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encoded_pt_len, bn_ctx); *p = n; /* length of encoded point */ /* Encoded point will be copied here */ p += 1; /* copy the point */ memcpy((unsigned char *)p, encodedPoint, n); /* increment n to account for length field */ n += 1; } /* Free allocated memory */ BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); } #endif /* !OPENSSL_NO_ECDH */ else if (alg_k & SSL_kGOST) { /* GOST key exchange message creation */ EVP_PKEY_CTX *pkey_ctx; X509 *peer_cert; size_t msglen; unsigned int md_len; int keytype; unsigned char premaster_secret[32],shared_ukm[32], tmp[256]; EVP_MD_CTX *ukm_hash; EVP_PKEY *pub_key; /* Get server sertificate PKEY and create ctx from it */ peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509; if (!peer_cert) peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509; if (!peer_cert) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER); goto err; } pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL); /* If we have send a certificate, and certificate key * parameters match those of server certificate, use * certificate key for key exchange */ /* Otherwise, generate ephemeral key pair */ EVP_PKEY_encrypt_init(pkey_ctx); /* Generate session key */ RAND_bytes(premaster_secret,32); /* If we have client certificate, use its secret as peer key */ if (s->s3->tmp.cert_req && s->cert->key->privatekey) { if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) { /* If there was an error - just ignore it. Ephemeral key * would be used */ ERR_clear_error(); } } /* Compute shared IV and store it in algorithm-specific * context data */ ukm_hash = EVP_MD_CTX_create(); EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94)); EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE); EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE); EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len); EVP_MD_CTX_destroy(ukm_hash); if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV, 8,shared_ukm)<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_LIBRARY_BUG); goto err; } /* Make GOST keytransport blob message */ /*Encapsulate it into sequence */ *(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED; msglen=255; if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_LIBRARY_BUG); goto err; } if (msglen >= 0x80) { *(p++)=0x81; *(p++)= msglen & 0xff; n=msglen+3; } else { *(p++)= msglen & 0xff; n=msglen+2; } memcpy(p, tmp, msglen); /* Check if pubkey from client certificate was used */ if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) { /* Set flag "skip certificate verify" */ s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY; } EVP_PKEY_CTX_free(pkey_ctx); s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,premaster_secret,32); EVP_PKEY_free(pub_key); } #ifndef OPENSSL_NO_SRP else if (alg_k & SSL_kSRP) { if (s->srp_ctx.A != NULL) { /* send off the data */ n=BN_num_bytes(s->srp_ctx.A); s2n(n,p); BN_bn2bin(s->srp_ctx.A,p); n+=2; } else { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } if (s->session->srp_username != NULL) OPENSSL_free(s->session->srp_username); s->session->srp_username = BUF_strdup(s->srp_ctx.login); if (s->session->srp_username == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if ((s->session->master_key_length = SRP_generate_client_master_secret(s,s->session->master_key))<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } } #endif #ifndef OPENSSL_NO_PSK else if (alg_k & SSL_kPSK) { /* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes * to return a \0-terminated identity. The last byte * is for us for simulating strnlen. */ char identity[PSK_MAX_IDENTITY_LEN + 2]; size_t identity_len; unsigned char *t = NULL; unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4]; unsigned int pre_ms_len = 0, psk_len = 0; int psk_err = 1; n = 0; if (s->psk_client_callback == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_PSK_NO_CLIENT_CB); goto err; } memset(identity, 0, sizeof(identity)); psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint, identity, sizeof(identity) - 1, psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_len > PSK_MAX_PSK_LEN) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } else if (psk_len == 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_PSK_IDENTITY_NOT_FOUND); goto psk_err; } identity[PSK_MAX_IDENTITY_LEN + 1] = '\0'; identity_len = strlen(identity); if (identity_len > PSK_MAX_IDENTITY_LEN) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } /* create PSK pre_master_secret */ pre_ms_len = 2+psk_len+2+psk_len; t = psk_or_pre_ms; memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len); s2n(psk_len, t); memset(t, 0, psk_len); t+=psk_len; s2n(psk_len, t); if (s->session->psk_identity_hint != NULL) OPENSSL_free(s->session->psk_identity_hint); s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); if (s->ctx->psk_identity_hint != NULL && s->session->psk_identity_hint == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } if (s->session->psk_identity != NULL) OPENSSL_free(s->session->psk_identity); s->session->psk_identity = BUF_strdup(identity); if (s->session->psk_identity == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, psk_or_pre_ms, pre_ms_len); s2n(identity_len, p); memcpy(p, identity, identity_len); n = 2 + identity_len; psk_err = 0; psk_err: OPENSSL_cleanse(identity, sizeof(identity)); OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_err != 0) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); goto err; } } #endif else { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n); s->state=SSL3_ST_CW_KEY_EXCH_B; } /* SSL3_ST_CW_KEY_EXCH_B */ return ssl_do_write(s); err: #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); #endif return(-1); } Commit Message: Only allow ephemeral RSA keys in export ciphersuites. OpenSSL clients would tolerate temporary RSA keys in non-export ciphersuites. It also had an option SSL_OP_EPHEMERAL_RSA which enabled this server side. Remove both options as they are a protocol violation. Thanks to Karthikeyan Bhargavan for reporting this issue. (CVE-2015-0204) Reviewed-by: Matt Caswell <[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: int hsr_dev_finalize(struct net_device *hsr_dev, struct net_device *slave[2], unsigned char multicast_spec, u8 protocol_version) { struct hsr_priv *hsr; struct hsr_port *port; int res; hsr = netdev_priv(hsr_dev); INIT_LIST_HEAD(&hsr->ports); INIT_LIST_HEAD(&hsr->node_db); INIT_LIST_HEAD(&hsr->self_node_db); ether_addr_copy(hsr_dev->dev_addr, slave[0]->dev_addr); /* Make sure we recognize frames from ourselves in hsr_rcv() */ res = hsr_create_self_node(&hsr->self_node_db, hsr_dev->dev_addr, slave[1]->dev_addr); if (res < 0) return res; spin_lock_init(&hsr->seqnr_lock); /* Overflow soon to find bugs easier: */ hsr->sequence_nr = HSR_SEQNR_START; hsr->sup_sequence_nr = HSR_SUP_SEQNR_START; timer_setup(&hsr->announce_timer, hsr_announce, 0); timer_setup(&hsr->prune_timer, hsr_prune_nodes, 0); ether_addr_copy(hsr->sup_multicast_addr, def_multicast_addr); hsr->sup_multicast_addr[ETH_ALEN - 1] = multicast_spec; hsr->protVersion = protocol_version; /* FIXME: should I modify the value of these? * * - hsr_dev->flags - i.e. * IFF_MASTER/SLAVE? * - hsr_dev->priv_flags - i.e. * IFF_EBRIDGE? * IFF_TX_SKB_SHARING? * IFF_HSR_MASTER/SLAVE? */ /* Make sure the 1st call to netif_carrier_on() gets through */ netif_carrier_off(hsr_dev); res = hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER); if (res) return res; res = register_netdevice(hsr_dev); if (res) goto fail; res = hsr_add_port(hsr, slave[0], HSR_PT_SLAVE_A); if (res) goto fail; res = hsr_add_port(hsr, slave[1], HSR_PT_SLAVE_B); if (res) goto fail; mod_timer(&hsr->prune_timer, jiffies + msecs_to_jiffies(PRUNE_PERIOD)); return 0; fail: hsr_for_each_port(hsr, port) hsr_del_port(port); return res; } Commit Message: net: hsr: fix memory leak in hsr_dev_finalize() If hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER) failed to add port, it directly returns res and forgets to free the node that allocated in hsr_create_self_node(), and forgets to delete the node->mac_list linked in hsr->self_node_db. BUG: memory leak unreferenced object 0xffff8881cfa0c780 (size 64): comm "syz-executor.0", pid 2077, jiffies 4294717969 (age 2415.377s) hex dump (first 32 bytes): e0 c7 a0 cf 81 88 ff ff 00 02 00 00 00 00 ad de ................ 00 e6 49 cd 81 88 ff ff c0 9b 87 d0 81 88 ff ff ..I............. backtrace: [<00000000e2ff5070>] hsr_dev_finalize+0x736/0x960 [hsr] [<000000003ed2e597>] hsr_newlink+0x2b2/0x3e0 [hsr] [<000000003fa8c6b6>] __rtnl_newlink+0xf1f/0x1600 net/core/rtnetlink.c:3182 [<000000001247a7ad>] rtnl_newlink+0x66/0x90 net/core/rtnetlink.c:3240 [<00000000e7d1b61d>] rtnetlink_rcv_msg+0x54e/0xb90 net/core/rtnetlink.c:5130 [<000000005556bd3a>] netlink_rcv_skb+0x129/0x340 net/netlink/af_netlink.c:2477 [<00000000741d5ee6>] netlink_unicast_kernel net/netlink/af_netlink.c:1310 [inline] [<00000000741d5ee6>] netlink_unicast+0x49a/0x650 net/netlink/af_netlink.c:1336 [<000000009d56f9b7>] netlink_sendmsg+0x88b/0xdf0 net/netlink/af_netlink.c:1917 [<0000000046b35c59>] sock_sendmsg_nosec net/socket.c:621 [inline] [<0000000046b35c59>] sock_sendmsg+0xc3/0x100 net/socket.c:631 [<00000000d208adc9>] __sys_sendto+0x33e/0x560 net/socket.c:1786 [<00000000b582837a>] __do_sys_sendto net/socket.c:1798 [inline] [<00000000b582837a>] __se_sys_sendto net/socket.c:1794 [inline] [<00000000b582837a>] __x64_sys_sendto+0xdd/0x1b0 net/socket.c:1794 [<00000000c866801d>] do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 [<00000000fea382d9>] entry_SYSCALL_64_after_hwframe+0x49/0xbe [<00000000e01dacb3>] 0xffffffffffffffff Fixes: c5a759117210 ("net/hsr: Use list_head (and rcu) instead of array for slave devices.") Reported-by: Hulk Robot <[email protected]> Signed-off-by: Mao Wenan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-772 Output:
1