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: update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu) { struct ring_buffer *buf; if (tr->stop_count) return; WARN_ON_ONCE(!irqs_disabled()); if (!tr->allocated_snapshot) { /* Only the nop tracer should hit this when disabling */ WARN_ON_ONCE(tr->current_trace != &nop_trace); return; } arch_spin_lock(&tr->max_lock); buf = tr->trace_buffer.buffer; tr->trace_buffer.buffer = tr->max_buffer.buffer; tr->max_buffer.buffer = buf; __update_max_tr(tr, tsk, cpu); arch_spin_unlock(&tr->max_lock); } Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace Pull tracing fixes from Steven Rostedt: "This contains a few fixes and a clean up. - a bad merge caused an "endif" to go in the wrong place in scripts/Makefile.build - softirq tracing fix for tracing that corrupts lockdep and causes a false splat - histogram documentation typo fixes - fix a bad memory reference when passing in no filter to the filter code - simplify code by using the swap macro instead of open coding the swap" * tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace: tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount tracing: Fix some errors in histogram documentation tracing: Use swap macro in update_max_tr softirq: Reorder trace_softirqs_on to prevent lockdep splat tracing: Check for no filter when processing event filters CWE ID: CWE-787 Target: 1 Example 2: Code: static void __exit usbnet_exit(void) { } Commit Message: usbnet: cleanup after bind() in probe() In case bind() works, but a later error forces bailing in probe() in error cases work and a timer may be scheduled. They must be killed. This fixes an error case related to the double free reported in http://www.spinics.net/lists/netdev/msg367669.html and needs to go on top of Linus' fix to cdc-ncm. Signed-off-by: Oliver Neukum <[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: static int ___sys_recvmsg(struct socket *sock, struct msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, int nosec) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov = iovstack; unsigned long cmsg_ptr; int err, total_len, len; /* kernel mode address */ struct sockaddr_storage addr; /* user mode address pointers */ struct sockaddr __user *uaddr; int __user *uaddr_len; if (MSG_CMSG_COMPAT & flags) { if (get_compat_msghdr(msg_sys, msg_compat)) return -EFAULT; } else { err = copy_msghdr_from_user(msg_sys, msg); if (err) return err; } if (msg_sys->msg_iovlen > UIO_FASTIOV) { err = -EMSGSIZE; if (msg_sys->msg_iovlen > UIO_MAXIOV) goto out; err = -ENOMEM; iov = kmalloc(msg_sys->msg_iovlen * sizeof(struct iovec), GFP_KERNEL); if (!iov) goto out; } /* * Save the user-mode address (verify_iovec will change the * kernel msghdr to use the kernel address space) */ uaddr = (__force void __user *)msg_sys->msg_name; uaddr_len = COMPAT_NAMELEN(msg); if (MSG_CMSG_COMPAT & flags) { err = verify_compat_iovec(msg_sys, iov, &addr, VERIFY_WRITE); } else err = verify_iovec(msg_sys, iov, &addr, VERIFY_WRITE); if (err < 0) goto out_freeiov; total_len = err; cmsg_ptr = (unsigned long)msg_sys->msg_control; msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT); if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys, total_len, flags); if (err < 0) goto out_freeiov; len = err; if (uaddr != NULL) { err = move_addr_to_user(&addr, msg_sys->msg_namelen, uaddr, uaddr_len); if (err < 0) goto out_freeiov; } err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT), COMPAT_FLAGS(msg)); if (err) goto out_freeiov; if (MSG_CMSG_COMPAT & flags) err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg_compat->msg_controllen); else err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg->msg_controllen); if (err) goto out_freeiov; err = len; out_freeiov: if (iov != iovstack) kfree(iov); out: return err; } 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:
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 dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf, int len, int peek) { int al, i, j, ret; unsigned int n; SSL3_RECORD *rr; void (*cb) (const SSL *ssl, int type2, int val) = NULL; if (!SSL3_BUFFER_is_initialised(&s->rlayer.rbuf)) { /* Not initialized yet */ if (!ssl3_setup_buffers(s)) return (-1); } if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } /* * check whether there's a handshake message (client hello?) waiting */ if ((ret = have_handshake_fragment(s, type, buf, len))) return ret; /* * Now s->rlayer.d->handshake_fragment_len == 0 if * type == SSL3_RT_HANDSHAKE. */ #ifndef OPENSSL_NO_SCTP /* * Continue handshake if it had to be interrupted to read app data with * SCTP. */ if ((!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) || (BIO_dgram_is_sctp(SSL_get_rbio(s)) && ossl_statem_in_sctp_read_sock(s) && s->s3->in_read_app_data != 2)) #else if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) #endif { /* type == SSL3_RT_APPLICATION_DATA */ i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } } start: s->rwstate = SSL_NOTHING; /*- * s->s3->rrec.type - is the type of record * s->s3->rrec.data, - data * s->s3->rrec.off, - offset into 'data' for next read * s->s3->rrec.length, - number of bytes. */ rr = s->rlayer.rrec; /* * We are not handshaking and have no data yet, so process data buffered * during the last handshake in advance, if any. */ if (SSL_is_init_finished(s) && SSL3_RECORD_get_length(rr) == 0) { pitem *item; item = pqueue_pop(s->rlayer.d->buffered_app_data.q); if (item) { #ifndef OPENSSL_NO_SCTP /* Restore bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s))) { DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif dtls1_copy_record(s, item); OPENSSL_free(item->data); pitem_free(item); } } /* Check for timeout */ if (dtls1_handle_timeout(s) > 0) goto start; /* get new packet if necessary */ if ((SSL3_RECORD_get_length(rr) == 0) || (s->rlayer.rstate == SSL_ST_READ_BODY)) { ret = dtls1_get_record(s); if (ret <= 0) { ret = dtls1_read_failed(s, ret); /* anything other than a timeout is an error */ if (ret <= 0) return (ret); else goto start; } } /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, SSL3_RECORD_get_seq_num(rr)) < 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } SSL3_RECORD_set_length(rr, 0); goto start; } Commit Message: CWE ID: CWE-400 Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoCopyTexImage2D( GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) { CheckErrorCallbackState(); api()->glCopyTexImage2DFn(target, level, internalformat, x, y, width, height, border); if (CheckErrorCallbackState()) { return error::kNoError; } UpdateTextureSizeFromTarget(target); ExitCommandProcessingEarly(); 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: void FragmentPaintPropertyTreeBuilder::UpdateSvgLocalToBorderBoxTransform() { DCHECK(properties_); if (!object_.IsSVGRoot()) return; if (NeedsPaintPropertyUpdate()) { AffineTransform transform_to_border_box = SVGRootPainter(ToLayoutSVGRoot(object_)) .TransformToPixelSnappedBorderBox(context_.current.paint_offset); if (!transform_to_border_box.IsIdentity() && NeedsSVGLocalToBorderBoxTransform(object_)) { OnUpdate(properties_->UpdateSvgLocalToBorderBoxTransform( context_.current.transform, TransformPaintPropertyNode::State{transform_to_border_box})); } else { OnClear(properties_->ClearSvgLocalToBorderBoxTransform()); } } if (properties_->SvgLocalToBorderBoxTransform()) { context_.current.transform = properties_->SvgLocalToBorderBoxTransform(); context_.current.should_flatten_inherited_transform = false; context_.current.rendering_context_id = 0; } context_.current.paint_offset = LayoutPoint(); } 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 cx24116_send_diseqc_msg(struct dvb_frontend *fe, struct dvb_diseqc_master_cmd *d) { struct cx24116_state *state = fe->demodulator_priv; int i, ret; /* Dump DiSEqC message */ if (debug) { printk(KERN_INFO "cx24116: %s(", __func__); for (i = 0 ; i < d->msg_len ;) { printk(KERN_INFO "0x%02x", d->msg[i]); if (++i < d->msg_len) printk(KERN_INFO ", "); } printk(") toneburst=%d\n", toneburst); } /* Validate length */ if (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS)) return -EINVAL; /* DiSEqC message */ for (i = 0; i < d->msg_len; i++) state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i]; /* DiSEqC message length */ state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len; /* Command length */ state->dsec_cmd.len = CX24116_DISEQC_MSGOFS + state->dsec_cmd.args[CX24116_DISEQC_MSGLEN]; /* DiSEqC toneburst */ if (toneburst == CX24116_DISEQC_MESGCACHE) /* Message is cached */ return 0; else if (toneburst == CX24116_DISEQC_TONEOFF) /* Message is sent without burst */ state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0; else if (toneburst == CX24116_DISEQC_TONECACHE) { /* * Message is sent with derived else cached burst * * WRITE PORT GROUP COMMAND 38 * * 0/A/A: E0 10 38 F0..F3 * 1/B/B: E0 10 38 F4..F7 * 2/C/A: E0 10 38 F8..FB * 3/D/B: E0 10 38 FC..FF * * databyte[3]= 8421:8421 * ABCD:WXYZ * CLR :SET * * WX= PORT SELECT 0..3 (X=TONEBURST) * Y = VOLTAGE (0=13V, 1=18V) * Z = BAND (0=LOW, 1=HIGH(22K)) */ if (d->msg_len >= 4 && d->msg[2] == 0x38) state->dsec_cmd.args[CX24116_DISEQC_BURST] = ((d->msg[3] & 4) >> 2); if (debug) dprintk("%s burst=%d\n", __func__, state->dsec_cmd.args[CX24116_DISEQC_BURST]); } /* Wait for LNB ready */ ret = cx24116_wait_for_lnb(fe); if (ret != 0) return ret; /* Wait for voltage/min repeat delay */ msleep(100); /* Command */ ret = cx24116_cmd_execute(fe, &state->dsec_cmd); if (ret != 0) return ret; /* * Wait for send * * Eutelsat spec: * >15ms delay + (XXX determine if FW does this, see set_tone) * 13.5ms per byte + * >15ms delay + * 12.5ms burst + * >15ms delay (XXX determine if FW does this, see set_tone) */ msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) + ((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60)); return 0; } Commit Message: [media] cx24116: fix a buffer overflow when checking userspace params The maximum size for a DiSEqC command is 6, according to the userspace API. However, the code allows to write up much more values: drivers/media/dvb-frontends/cx24116.c:983 cx24116_send_diseqc_msg() error: buffer overflow 'd->msg' 6 <= 23 Cc: [email protected] Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void AwContents::InitAutofillIfNecessary(bool enabled) { if (!enabled) return; content::WebContents* web_contents = web_contents_.get(); if (ContentAutofillDriverFactory::FromWebContents(web_contents)) return; AwAutofillClient::CreateForWebContents(web_contents); ContentAutofillDriverFactory::CreateForWebContentsAndDelegate( web_contents, AwAutofillClient::FromWebContents(web_contents), base::android::GetDefaultLocale(), AutofillManager::DISABLE_AUTOFILL_DOWNLOAD_MANAGER); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399 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 ServiceWorkerDevToolsAgentHost::WorkerDestroyed() { DCHECK_NE(WORKER_TERMINATED, state_); state_ = WORKER_TERMINATED; agent_ptr_.reset(); for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetCrashed(); for (DevToolsSession* session : sessions()) session->SetRenderer(nullptr, nullptr); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: const user_manager::UserList UserSelectionScreen::PrepareUserListForSending( const user_manager::UserList& users, const AccountId& owner, bool is_signin_to_add) { user_manager::UserList users_to_send; bool has_owner = owner.is_valid(); size_t max_non_owner_users = has_owner ? kMaxUsers - 1 : kMaxUsers; size_t non_owner_count = 0; for (user_manager::UserList::const_iterator it = users.begin(); it != users.end(); ++it) { bool is_owner = ((*it)->GetAccountId() == owner); bool is_public_account = ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT); if ((is_public_account && !is_signin_to_add) || is_owner || (!is_public_account && non_owner_count < max_non_owner_users)) { if (!is_owner) ++non_owner_count; if (is_owner && users_to_send.size() > kMaxUsers) { users_to_send.insert(users_to_send.begin() + (kMaxUsers - 1), *it); while (users_to_send.size() > kMaxUsers) users_to_send.erase(users_to_send.begin() + kMaxUsers); } else if (users_to_send.size() < kMaxUsers) { users_to_send.push_back(*it); } } } return users_to_send; } 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: Target: 1 Example 2: Code: void SpeechRecognitionManagerImpl::DispatchEvent(int session_id, FSMEvent event) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!SessionExists(session_id)) return; Session* session = GetSession(session_id); FSMState session_state = GetSessionState(session_id); DCHECK_LE(session_state, SESSION_STATE_MAX_VALUE); DCHECK_LE(event, EVENT_MAX_VALUE); DCHECK(!is_dispatching_event_); is_dispatching_event_ = true; ExecuteTransitionAndGetNextState(session, session_state, event); is_dispatching_event_ = false; } 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 set_load_weight(struct task_struct *p) { int prio = p->static_prio - MAX_RT_PRIO; struct load_weight *load = &p->se.load; /* * SCHED_IDLE tasks get minimal weight: */ if (p->policy == SCHED_IDLE) { load->weight = scale_load(WEIGHT_IDLEPRIO); load->inv_weight = WMULT_IDLEPRIO; return; } load->weight = scale_load(prio_to_weight[prio]); load->inv_weight = prio_to_wmult[prio]; } 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: bool ParamTraits<SkBitmap>::Read(const base::Pickle* m, base::PickleIterator* iter, SkBitmap* r) { const char* fixed_data; int fixed_data_size = 0; if (!iter->ReadData(&fixed_data, &fixed_data_size) || (fixed_data_size <= 0)) { return false; } if (fixed_data_size != sizeof(SkBitmap_Data)) return false; // Message is malformed. const char* variable_data; int variable_data_size = 0; if (!iter->ReadData(&variable_data, &variable_data_size) || (variable_data_size < 0)) { return false; } const SkBitmap_Data* bmp_data = reinterpret_cast<const SkBitmap_Data*>(fixed_data); return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size); } Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices. Using memcpy() to serialize a POD struct is highly discouraged. Just use the standard IPC param traits macros for doing it. Bug: 779428 Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334 Reviewed-on: https://chromium-review.googlesource.com/899649 Reviewed-by: Tom Sepez <[email protected]> Commit-Queue: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#534562} CWE ID: CWE-125 Target: 1 Example 2: Code: static void dump_mem(const char *lvl, const char *str, unsigned long bottom, unsigned long top) { unsigned long first; mm_segment_t fs; int i; /* * We need to switch to kernel mode so that we can use __get_user * to safely read from kernel space. Note that we now dump the * code first, just in case the backtrace kills us. */ fs = get_fs(); set_fs(KERNEL_DS); printk("%s%s(0x%08lx to 0x%08lx)\n", lvl, str, bottom, top); for (first = bottom & ~31; first < top; first += 32) { unsigned long p; char str[sizeof(" 12345678") * 8 + 1]; memset(str, ' ', sizeof(str)); str[sizeof(str) - 1] = '\0'; for (p = first, i = 0; i < 8 && p < top; i++, p += 4) { if (p >= bottom && p < top) { unsigned long val; if (__get_user(val, (unsigned long *)p) == 0) sprintf(str + i * 9, " %08lx", val); else sprintf(str + i * 9, " ????????"); } } printk("%s%04lx:%s\n", lvl, first & 0xffff, str); } set_fs(fs); } Commit Message: ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to prevent it from being used as a covert channel between two tasks. There are more and more applications coming to Windows RT, Wine could support them, but mostly they expect to have the thread environment block (TEB) in TPIDRURW. This patch preserves that register per thread instead of clearing it. Unlike the TPIDRURO, which is already switched, the TPIDRURW can be updated from userspace so needs careful treatment in the case that we modify TPIDRURW and call fork(). To avoid this we must always read TPIDRURW in copy_thread. Signed-off-by: André Hentschel <[email protected]> Signed-off-by: Will Deacon <[email protected]> Signed-off-by: Jonathan Austin <[email protected]> Signed-off-by: Russell King <[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 DatabaseImpl::IDBThreadHelper::CreateTransaction( int64_t transaction_id, const std::vector<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode) { DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; connection_->database()->CreateTransaction(transaction_id, connection_.get(), object_store_ids, mode); } Commit Message: [IndexedDB] Fixed transaction use-after-free vuln Bug: 725032 Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa Reviewed-on: https://chromium-review.googlesource.com/518483 Reviewed-by: Joshua Bell <[email protected]> Commit-Queue: Daniel Murphy <[email protected]> Cr-Commit-Position: refs/heads/master@{#475952} CWE ID: CWE-416 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: UserCloudPolicyManagerChromeOS::UserCloudPolicyManagerChromeOS( scoped_ptr<CloudPolicyStore> store, scoped_ptr<CloudExternalDataManager> external_data_manager, const base::FilePath& component_policy_cache_path, bool wait_for_policy_fetch, base::TimeDelta initial_policy_fetch_timeout, const scoped_refptr<base::SequencedTaskRunner>& task_runner, const scoped_refptr<base::SequencedTaskRunner>& file_task_runner, const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) : CloudPolicyManager( PolicyNamespaceKey(dm_protocol::kChromeUserPolicyType, std::string()), store.get(), task_runner, file_task_runner, io_task_runner), store_(store.Pass()), external_data_manager_(external_data_manager.Pass()), component_policy_cache_path_(component_policy_cache_path), wait_for_policy_fetch_(wait_for_policy_fetch), policy_fetch_timeout_(false, false) { time_init_started_ = base::Time::Now(); if (wait_for_policy_fetch_) { policy_fetch_timeout_.Start( FROM_HERE, initial_policy_fetch_timeout, base::Bind(&UserCloudPolicyManagerChromeOS::OnBlockingFetchTimeout, base::Unretained(this))); } } Commit Message: Make the policy fetch for first time login blocking The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users. BUG=334584 Review URL: https://codereview.chromium.org/330843002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: void WebRtcAudioRenderer::OnRenderError() { NOTIMPLEMENTED(); LOG(ERROR) << "OnRenderError()"; } Commit Message: Avoids crash in WebRTC audio clients for 96kHz render rate on Mac OSX. TBR=xians BUG=166523 TEST=Misc set of WebRTC audio clients on Mac. Review URL: https://codereview.chromium.org/11773017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@175323 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: MagickExport MagickBooleanType GrayscaleImage(Image *image, const PixelIntensityMethod method,ExceptionInfo *exception) { #define GrayscaleImageTag "Grayscale/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { if (SyncImage(image,exception) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse) { image->intensity=method; image->type=GrayscaleType; return(SetImageColorspace(image,GRAYColorspace,exception)); } #endif /* Grayscale image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType blue, green, red, intensity; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } red=(MagickRealType) GetPixelRed(image,q); green=(MagickRealType) GetPixelGreen(image,q); blue=(MagickRealType) GetPixelBlue(image,q); intensity=0.0; switch (method) { case AveragePixelIntensityMethod: { intensity=(red+green+blue)/3.0; break; } case BrightnessPixelIntensityMethod: { intensity=MagickMax(MagickMax(red,green),blue); break; } case LightnessPixelIntensityMethod: { intensity=(MagickMin(MagickMin(red,green),blue)+ MagickMax(MagickMax(red,green),blue))/2.0; break; } case MSPixelIntensityMethod: { intensity=(MagickRealType) (((double) red*red+green*green+ blue*blue)/3.0); break; } case Rec601LumaPixelIntensityMethod: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec601LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec709LumaPixelIntensityMethod: default: { if (image->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case Rec709LuminancePixelIntensityMethod: { if (image->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case RMSPixelIntensityMethod: { intensity=(MagickRealType) (sqrt((double) red*red+green*green+ blue*blue)/sqrt(3.0)); break; } } SetPixelGray(image,ClampToQuantum(intensity),q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GrayscaleImage) #endif proceed=SetImageProgress(image,GrayscaleImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); image->intensity=method; image->type=GrayscaleType; return(SetImageColorspace(image,GRAYColorspace,exception)); } Commit Message: Evaluate lazy pixel cache morphology to prevent buffer overflow (bug report from Ibrahim M. El-Sayed) CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu) { const struct usb_cdc_union_desc *union_desc; struct usb_host_interface *alt; union_desc = ims_pcu_get_cdc_union_desc(intf); if (!union_desc) return -EINVAL; pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev, union_desc->bMasterInterface0); alt = pcu->ctrl_intf->cur_altsetting; pcu->ep_ctrl = &alt->endpoint[0].desc; pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl); pcu->data_intf = usb_ifnum_to_if(pcu->udev, union_desc->bSlaveInterface0); alt = pcu->data_intf->cur_altsetting; if (alt->desc.bNumEndpoints != 2) { dev_err(pcu->dev, "Incorrect number of endpoints on data interface (%d)\n", alt->desc.bNumEndpoints); return -EINVAL; } pcu->ep_out = &alt->endpoint[0].desc; if (!usb_endpoint_is_bulk_out(pcu->ep_out)) { dev_err(pcu->dev, "First endpoint on data interface is not BULK OUT\n"); return -EINVAL; } pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out); if (pcu->max_out_size < 8) { dev_err(pcu->dev, "Max OUT packet size is too small (%zd)\n", pcu->max_out_size); return -EINVAL; } pcu->ep_in = &alt->endpoint[1].desc; if (!usb_endpoint_is_bulk_in(pcu->ep_in)) { dev_err(pcu->dev, "Second endpoint on data interface is not BULK IN\n"); return -EINVAL; } pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in); if (pcu->max_in_size < 8) { dev_err(pcu->dev, "Max IN packet size is too small (%zd)\n", pcu->max_in_size); return -EINVAL; } return 0; } Commit Message: Input: ims-pcu - sanity check against missing interfaces A malicious device missing interface can make the driver oops. Add sanity checking. Signed-off-by: Oliver Neukum <[email protected]> CC: [email protected] Signed-off-by: Dmitry Torokhov <[email protected]> CWE ID: Target: 1 Example 2: Code: void __ext4_warning(struct super_block *sb, const char *function, unsigned int line, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n", sb->s_id, function, line, &vaf); va_end(args); } Commit Message: ext4: fix undefined behavior in ext4_fill_flex_info() Commit 503358ae01b70ce6909d19dd01287093f6b6271c ("ext4: avoid divide by zero when trying to mount a corrupted file system") fixes CVE-2009-4307 by performing a sanity check on s_log_groups_per_flex, since it can be set to a bogus value by an attacker. sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex; groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex < 2) { ... } This patch fixes two potential issues in the previous commit. 1) The sanity check might only work on architectures like PowerPC. On x86, 5 bits are used for the shifting amount. That means, given a large s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36 is essentially 1 << 4 = 16, rather than 0. This will bypass the check, leaving s_log_groups_per_flex and groups_per_flex inconsistent. 2) The sanity check relies on undefined behavior, i.e., oversized shift. A standard-confirming C compiler could rewrite the check in unexpected ways. Consider the following equivalent form, assuming groups_per_flex is unsigned for simplicity. groups_per_flex = 1 << sbi->s_log_groups_per_flex; if (groups_per_flex == 0 || groups_per_flex == 1) { We compile the code snippet using Clang 3.0 and GCC 4.6. Clang will completely optimize away the check groups_per_flex == 0, leaving the patched code as vulnerable as the original. GCC keeps the check, but there is no guarantee that future versions will do the same. Signed-off-by: Xi Wang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> Cc: [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: void EnterpriseEnrollmentScreen::HandleAuthError( const GoogleServiceAuthError& error) { scoped_ptr<GaiaAuthFetcher> scoped_killer(auth_fetcher_.release()); if (!is_showing_) return; switch (error.state()) { case GoogleServiceAuthError::CONNECTION_FAILED: UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentNetworkFailed, policy::kMetricEnrollmentSize); actor_->ShowNetworkEnrollmentError(); return; case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: case GoogleServiceAuthError::CAPTCHA_REQUIRED: case GoogleServiceAuthError::TWO_FACTOR: case GoogleServiceAuthError::SERVICE_UNAVAILABLE: UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentLoginFailed, policy::kMetricEnrollmentSize); actor_->ShowAuthError(error); return; case GoogleServiceAuthError::USER_NOT_SIGNED_UP: case GoogleServiceAuthError::ACCOUNT_DELETED: case GoogleServiceAuthError::ACCOUNT_DISABLED: UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentNotSupported, policy::kMetricEnrollmentSize); actor_->ShowAccountError(); return; case GoogleServiceAuthError::NONE: case GoogleServiceAuthError::HOSTED_NOT_ALLOWED: NOTREACHED() << error.state(); case GoogleServiceAuthError::REQUEST_CANCELED: LOG(ERROR) << "Unexpected GAIA auth error: " << error.state(); UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentNetworkFailed, policy::kMetricEnrollmentSize); actor_->ShowFatalAuthError(); return; } NOTREACHED() << error.state(); UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentOtherFailed, policy::kMetricEnrollmentSize); } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: BGD_DECLARE(gdImagePtr) gdImageCropThreshold(gdImagePtr im, const unsigned int color, const float threshold) { const int width = gdImageSX(im); const int height = gdImageSY(im); int x,y; int match; gdRect crop; crop.x = 0; crop.y = 0; crop.width = 0; crop.height = 0; /* Pierre: crop everything sounds bad */ if (threshold > 100.0) { return NULL; } /* TODO: Add gdImageGetRowPtr and works with ptr at the row level * for the true color and palette images * new formats will simply work with ptr */ match = 1; for (y = 0; match && y < height; y++) { for (x = 0; match && x < width; x++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } /* Pierre * Nothing to do > bye * Duplicate the image? */ if (y == height - 1) { return NULL; } crop.y = y -1; match = 1; for (y = height - 1; match && y >= 0; y--) { for (x = 0; match && x < width; x++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x, y), threshold)) > 0; } } if (y == 0) { crop.height = height - crop.y + 1; } else { crop.height = y - crop.y + 2; } match = 1; for (x = 0; match && x < width; x++) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } crop.x = x - 1; match = 1; for (x = width - 1; match && x >= 0; x--) { for (y = 0; match && y < crop.y + crop.height - 1; y++) { match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0; } } crop.width = x - crop.x + 2; return gdImageCrop(im, &crop); } Commit Message: fix php 72494, invalid color index not handled, can lead to crash CWE ID: CWE-20 Target: 1 Example 2: Code: void CL_GlobalServers_f( void ) { netadr_t to; int count, i, masterNum; char command[1024], *masteraddress; if ((count = Cmd_Argc()) < 3 || (masterNum = atoi(Cmd_Argv(1))) < 0 || masterNum > MAX_MASTER_SERVERS - 1) { Com_Printf("usage: globalservers <master# 0-%d> <protocol> [keywords]\n", MAX_MASTER_SERVERS - 1); return; } sprintf(command, "sv_master%d", masterNum + 1); masteraddress = Cvar_VariableString(command); if(!*masteraddress) { Com_Printf( "CL_GlobalServers_f: Error: No master server address given.\n"); return; } i = NET_StringToAdr(masteraddress, &to, NA_UNSPEC); if(!i) { Com_Printf( "CL_GlobalServers_f: Error: could not resolve address of master %s\n", masteraddress); return; } else if(i == 2) to.port = BigShort(PORT_MASTER); Com_Printf("Requesting servers from master %s...\n", masteraddress); cls.numglobalservers = -1; cls.pingUpdateSource = AS_GLOBAL; if (to.type == NA_IP6 || to.type == NA_MULTICAST6) { int v4enabled = Cvar_VariableIntegerValue("net_enabled") & NET_ENABLEV4; if(v4enabled) { Com_sprintf(command, sizeof(command), "getserversExt %s %s", com_gamename->string, Cmd_Argv(2)); } else { Com_sprintf(command, sizeof(command), "getserversExt %s %s ipv6", com_gamename->string, Cmd_Argv(2)); } } else if ( !Q_stricmp( com_gamename->string, LEGACY_MASTER_GAMENAME ) ) Com_sprintf(command, sizeof(command), "getservers %s", Cmd_Argv(2)); else Com_sprintf(command, sizeof(command), "getservers %s %s", com_gamename->string, Cmd_Argv(2)); for (i=3; i < count; i++) { Q_strcat(command, sizeof(command), " "); Q_strcat(command, sizeof(command), Cmd_Argv(i)); } NET_OutOfBandPrint( NS_SERVER, to, "%s", command ); } Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s. CWE ID: CWE-269 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: FrameView::FrameView(LocalFrame* frame) : m_frame(frame) , m_canHaveScrollbars(true) , m_slowRepaintObjectCount(0) , m_hasPendingLayout(false) , m_layoutSubtreeRoot(0) , m_inSynchronousPostLayout(false) , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired) , m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired) , m_isTransparent(false) , m_baseBackgroundColor(Color::white) , m_mediaType("screen") , m_overflowStatusDirty(true) , m_viewportRenderer(0) , m_wasScrolledByUser(false) , m_inProgrammaticScroll(false) , m_safeToPropagateScrollToParent(true) , m_isTrackingPaintInvalidations(false) , m_scrollCorner(nullptr) , m_hasSoftwareFilters(false) , m_visibleContentScaleFactor(1) , m_inputEventsScaleFactorForEmulation(1) , m_layoutSizeFixedToFrameSize(true) , m_didScrollTimer(this, &FrameView::didScrollTimerFired) { ASSERT(m_frame); init(); if (!m_frame->isMainFrame()) return; ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed); ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed); } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 [email protected] Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416 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 *nlmsg_reserve(struct nl_msg *n, size_t len, int pad) { void *buf = n->nm_nlh; size_t nlmsg_len = n->nm_nlh->nlmsg_len; size_t tlen; tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len; if ((tlen + nlmsg_len) > n->nm_size) n->nm_nlh->nlmsg_len += tlen; if (tlen > len) memset(buf + len, 0, tlen - len); NL_DBG(2, "msg %p: Reserved %zu (%zu) bytes, pad=%d, nlmsg_len=%d\n", n, tlen, len, pad, n->nm_nlh->nlmsg_len); return buf; } Commit Message: CWE ID: CWE-190 Target: 1 Example 2: Code: void mlock_vma_page(struct page *page) { /* Serialize with page migration */ BUG_ON(!PageLocked(page)); VM_BUG_ON_PAGE(PageTail(page), page); VM_BUG_ON_PAGE(PageCompound(page) && PageDoubleMap(page), page); if (!TestSetPageMlocked(page)) { mod_zone_page_state(page_zone(page), NR_MLOCK, hpage_nr_pages(page)); count_vm_event(UNEVICTABLE_PGMLOCKED); if (!isolate_lru_page(page)) putback_lru_page(page); } } Commit Message: mlock: fix mlock count can not decrease in race condition Kefeng reported that when running the follow test, the mlock count in meminfo will increase permanently: [1] testcase linux:~ # cat test_mlockal grep Mlocked /proc/meminfo for j in `seq 0 10` do for i in `seq 4 15` do ./p_mlockall >> log & done sleep 0.2 done # wait some time to let mlock counter decrease and 5s may not enough sleep 5 grep Mlocked /proc/meminfo linux:~ # cat p_mlockall.c #include <sys/mman.h> #include <stdlib.h> #include <stdio.h> #define SPACE_LEN 4096 int main(int argc, char ** argv) { int ret; void *adr = malloc(SPACE_LEN); if (!adr) return -1; ret = mlockall(MCL_CURRENT | MCL_FUTURE); printf("mlcokall ret = %d\n", ret); ret = munlockall(); printf("munlcokall ret = %d\n", ret); free(adr); return 0; } In __munlock_pagevec() we should decrement NR_MLOCK for each page where we clear the PageMlocked flag. Commit 1ebb7cc6a583 ("mm: munlock: batch NR_MLOCK zone state updates") has introduced a bug where we don't decrement NR_MLOCK for pages where we clear the flag, but fail to isolate them from the lru list (e.g. when the pages are on some other cpu's percpu pagevec). Since PageMlocked stays cleared, the NR_MLOCK accounting gets permanently disrupted by this. Fix it by counting the number of page whose PageMlock flag is cleared. Fixes: 1ebb7cc6a583 (" mm: munlock: batch NR_MLOCK zone state updates") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Yisheng Xie <[email protected]> Reported-by: Kefeng Wang <[email protected]> Tested-by: Kefeng Wang <[email protected]> Cc: Vlastimil Babka <[email protected]> Cc: Joern Engel <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Michel Lespinasse <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Rik van Riel <[email protected]> Cc: Johannes Weiner <[email protected]> Cc: Michal Hocko <[email protected]> Cc: Xishi Qiu <[email protected]> Cc: zhongjiang <[email protected]> Cc: Hanjun Guo <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[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 SECStatus SelectClientCert(void *arg, PRFileDesc *sock, struct CERTDistNamesStr *caNames, struct CERTCertificateStr **pRetCert, struct SECKEYPrivateKeyStr **pRetKey) { struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg; struct Curl_easy *data = connssl->data; const char *nickname = connssl->client_nickname; if(connssl->obj_clicert) { /* use the cert/key provided by PEM reader */ static const char pem_slotname[] = "PEM Token #1"; SECItem cert_der = { 0, NULL, 0 }; void *proto_win = SSL_RevealPinArg(sock); struct CERTCertificateStr *cert; struct SECKEYPrivateKeyStr *key; PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname); if(NULL == slot) { failf(data, "NSS: PK11 slot not found: %s", pem_slotname); return SECFailure; } if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE, &cert_der) != SECSuccess) { failf(data, "NSS: CKA_VALUE not found in PK11 generic object"); PK11_FreeSlot(slot); return SECFailure; } cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win); SECITEM_FreeItem(&cert_der, PR_FALSE); if(NULL == cert) { failf(data, "NSS: client certificate from file not found"); PK11_FreeSlot(slot); return SECFailure; } key = PK11_FindPrivateKeyFromCert(slot, cert, NULL); PK11_FreeSlot(slot); if(NULL == key) { failf(data, "NSS: private key from file not found"); CERT_DestroyCertificate(cert); return SECFailure; } infof(data, "NSS: client certificate from file\n"); display_cert_info(data, cert); *pRetCert = cert; *pRetKey = key; return SECSuccess; } /* use the default NSS hook */ if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames, pRetCert, pRetKey) || NULL == *pRetCert) { if(NULL == nickname) failf(data, "NSS: client certificate not found (nickname not " "specified)"); else failf(data, "NSS: client certificate not found: %s", nickname); return SECFailure; } /* get certificate nickname if any */ nickname = (*pRetCert)->nickname; if(NULL == nickname) nickname = "[unknown]"; if(NULL == *pRetKey) { failf(data, "NSS: private key not found for certificate: %s", nickname); return SECFailure; } infof(data, "NSS: using client certificate: %s\n", nickname); display_cert_info(data, *pRetCert); return SECSuccess; } Commit Message: nss: refuse previously loaded certificate from file ... when we are not asked to use a certificate from file CWE ID: CWE-287 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 filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; BoxBlurContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int plane; int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub); int w[4] = { inlink->w, cw, cw, inlink->w }; int h[4] = { in->height, ch, ch, in->height }; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); for (plane = 0; in->data[plane] && plane < 4; plane++) hblur(out->data[plane], out->linesize[plane], in ->data[plane], in ->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); for (plane = 0; in->data[plane] && plane < 4; plane++) vblur(out->data[plane], out->linesize[plane], out->data[plane], out->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); av_frame_free(&in); return ff_filter_frame(outlink, out); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int conf__parse_string(char **token, const char *name, char **value, char *saveptr) { *token = strtok_r(NULL, "", &saveptr); if(*token){ if(*value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate %s value in configuration.", name); return MOSQ_ERR_INVAL; } /* Deal with multiple spaces at the beginning of the string. */ while((*token)[0] == ' ' || (*token)[0] == '\t'){ (*token)++; } if(mosquitto_validate_utf8(*token, strlen(*token))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Malformed UTF-8 in configuration."); return MOSQ_ERR_INVAL; } *value = mosquitto__strdup(*token); if(!*value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } Commit Message: Fix acl_file being ignore for default listener if with per_listener_settings Close #1073. Thanks to Jef Driesen. Bug: https://github.com/eclipse/mosquitto/issues/1073 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: PHP_FUNCTION(openssl_x509_checkpurpose) { zval ** zcert, * zcainfo = NULL; X509_STORE * cainfo = NULL; X509 * cert = NULL; long certresource = -1; STACK_OF(X509) * untrustedchain = NULL; long purpose; char * untrusted = NULL; int untrusted_len = 0, ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zl|a!s", &zcert, &purpose, &zcainfo, &untrusted, &untrusted_len) == FAILURE) { return; } RETVAL_LONG(-1); if (untrusted) { untrustedchain = load_all_certs_from_file(untrusted); if (untrustedchain == NULL) { goto clean_exit; } } cainfo = setup_verify(zcainfo TSRMLS_CC); if (cainfo == NULL) { goto clean_exit; } cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC); if (cert == NULL) { goto clean_exit; } ret = check_cert(cainfo, cert, untrustedchain, purpose); if (ret != 0 && ret != 1) { RETVAL_LONG(ret); } else { RETVAL_BOOL(ret); } clean_exit: if (certresource == 1 && cert) { X509_free(cert); } if (cainfo) { X509_STORE_free(cainfo); } if (untrustedchain) { sk_X509_pop_free(untrustedchain, X509_free); } } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: setPath(JsonbIterator **it, Datum *path_elems, bool *path_nulls, int path_len, JsonbParseState **st, int level, Jsonb *newval, bool create) { JsonbValue v; JsonbValue *res = NULL; int r; if (path_nulls[level]) elog(ERROR, "path element at the position %d is NULL", level + 1); switch (r) { case WJB_BEGIN_ARRAY: (void) pushJsonbValue(st, r, NULL); setPathArray(it, path_elems, path_nulls, path_len, st, level, newval, v.val.array.nElems, create); r = JsonbIteratorNext(it, &v, false); Assert(r == WJB_END_ARRAY); res = pushJsonbValue(st, r, NULL); break; case WJB_BEGIN_OBJECT: (void) pushJsonbValue(st, r, NULL); setPathObject(it, path_elems, path_nulls, path_len, st, level, newval, v.val.object.nPairs, create); r = JsonbIteratorNext(it, &v, true); Assert(r == WJB_END_OBJECT); res = pushJsonbValue(st, r, NULL); break; case WJB_ELEM: case WJB_VALUE: res = pushJsonbValue(st, r, &v); break; default: elog(ERROR, "impossible state"); } return res; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static int encode_setattr(struct xdr_stream *xdr, const struct nfs_setattrargs *arg, const struct nfs_server *server) { int status; __be32 *p; RESERVE_SPACE(4+NFS4_STATEID_SIZE); WRITE32(OP_SETATTR); WRITEMEM(arg->stateid.data, NFS4_STATEID_SIZE); if ((status = encode_attrs(xdr, arg->iap, server))) return status; return 0; } 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: create_mainbar () { GUI *g = &uzbl.gui; g->mainbar = gtk_hbox_new (FALSE, 0); g->mainbar_label = gtk_label_new (""); gtk_label_set_selectable((GtkLabel *)g->mainbar_label, TRUE); gtk_label_set_ellipsize(GTK_LABEL(g->mainbar_label), PANGO_ELLIPSIZE_END); gtk_misc_set_alignment (GTK_MISC(g->mainbar_label), 0, 0); gtk_misc_set_padding (GTK_MISC(g->mainbar_label), 2, 2); gtk_box_pack_start (GTK_BOX (g->mainbar), g->mainbar_label, TRUE, TRUE, 0); g_object_connect((GObject*)g->mainbar, "signal::key-press-event", (GCallback)key_press_cb, NULL, "signal::key-release-event", (GCallback)key_release_cb, NULL, NULL); return g->mainbar; } Commit Message: disable Uzbl javascript object because of security problem. 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 zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from, int offset, size_t count) { int len = iov_length(from, count) - offset; int copy = skb_headlen(skb); int size, offset1 = 0; int i = 0; /* Skip over from offset */ while (count && (offset >= from->iov_len)) { offset -= from->iov_len; ++from; --count; } /* copy up to skb headlen */ while (count && (copy > 0)) { size = min_t(unsigned int, copy, from->iov_len - offset); if (copy_from_user(skb->data + offset1, from->iov_base + offset, size)) return -EFAULT; if (copy > size) { ++from; --count; offset = 0; } else offset += size; copy -= size; offset1 += size; } if (len == offset1) return 0; while (count--) { struct page *page[MAX_SKB_FRAGS]; int num_pages; unsigned long base; unsigned long truesize; len = from->iov_len - offset; if (!len) { offset = 0; ++from; continue; } base = (unsigned long)from->iov_base + offset; size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT; num_pages = get_user_pages_fast(base, size, 0, &page[i]); if ((num_pages != size) || (num_pages > MAX_SKB_FRAGS - skb_shinfo(skb)->nr_frags)) { for (i = 0; i < num_pages; i++) put_page(page[i]); return -EFAULT; } truesize = size * PAGE_SIZE; skb->data_len += len; skb->len += len; skb->truesize += truesize; atomic_add(truesize, &skb->sk->sk_wmem_alloc); while (len) { int off = base & ~PAGE_MASK; int size = min_t(int, len, PAGE_SIZE - off); __skb_fill_page_desc(skb, i, page[i], off, size); skb_shinfo(skb)->nr_frags++; /* increase sk_wmem_alloc */ base += size; len -= size; i++; } offset = 0; ++from; } return 0; } Commit Message: macvtap: zerocopy: validate vectors before building skb There're several reasons that the vectors need to be validated: - Return error when caller provides vectors whose num is greater than UIO_MAXIOV. - Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS. - Return error when userspace provides vectors whose total length may exceed - MAX_SKB_FRAGS * PAGE_SIZE. Signed-off-by: Jason Wang <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: int cap_task_setnice(struct task_struct *p, int nice) { return cap_safe_nice(p); } Commit Message: fcaps: clear the same personality flags as suid when fcaps are used If a process increases permissions using fcaps all of the dangerous personality flags which are cleared for suid apps should also be cleared. Thus programs given priviledge with fcaps will continue to have address space randomization enabled even if the parent tried to disable it to make it easier to attack. Signed-off-by: Eric Paris <[email protected]> Reviewed-by: Serge Hallyn <[email protected]> Signed-off-by: James Morris <[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 int tipc_nl_compat_link_set(struct tipc_nl_compat_cmd_doit *cmd, struct sk_buff *skb, struct tipc_nl_compat_msg *msg) { struct tipc_link_config *lc; struct tipc_bearer *bearer; struct tipc_media *media; lc = (struct tipc_link_config *)TLV_DATA(msg->req); media = tipc_media_find(lc->name); if (media) { cmd->doit = &tipc_nl_media_set; return tipc_nl_compat_media_set(skb, msg); } bearer = tipc_bearer_find(msg->net, lc->name); if (bearer) { cmd->doit = &tipc_nl_bearer_set; return tipc_nl_compat_bearer_set(skb, msg); } return __tipc_nl_compat_link_set(skb, msg); } Commit Message: tipc: fix an infoleak in tipc_nl_compat_link_dump link_info.str is a char array of size 60. Memory after the NULL byte is not initialized. Sending the whole object out can cause a leak. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: David S. Miller <[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: void AppCacheUpdateJob::HandleMasterEntryFetchCompleted(URLFetcher* fetcher, int net_error) { DCHECK(internal_state_ == NO_UPDATE || internal_state_ == DOWNLOADING); UpdateURLLoaderRequest* request = fetcher->request(); const GURL& url = request->GetURL(); master_entry_fetches_.erase(url); ++master_entries_completed_; int response_code = net_error == net::OK ? request->GetResponseCode() : -1; auto found = pending_master_entries_.find(url); DCHECK(found != pending_master_entries_.end()); PendingHosts& hosts = found->second; if (response_code / 100 == 2) { AppCache* cache = inprogress_cache_.get() ? inprogress_cache_.get() : group_->newest_complete_cache(); DCHECK(fetcher->response_writer()); AppCacheEntry master_entry(AppCacheEntry::MASTER, fetcher->response_writer()->response_id(), fetcher->response_writer()->amount_written()); if (cache->AddOrModifyEntry(url, master_entry)) added_master_entries_.push_back(url); else duplicate_response_ids_.push_back(master_entry.response_id()); if (!inprogress_cache_.get()) { DCHECK(cache == group_->newest_complete_cache()); for (AppCacheHost* host : hosts) host->AssociateCompleteCache(cache); } } else { HostNotifier host_notifier; for (AppCacheHost* host : hosts) { host_notifier.AddHost(host); if (inprogress_cache_.get()) host->AssociateNoCache(GURL()); host->RemoveObserver(this); } hosts.clear(); failed_master_entries_.insert(url); const char kFormatString[] = "Manifest fetch failed (%d) %s"; std::string message = FormatUrlErrorMessage( kFormatString, request->GetURL(), fetcher->result(), response_code); host_notifier.SendErrorNotifications(blink::mojom::AppCacheErrorDetails( message, blink::mojom::AppCacheErrorReason::APPCACHE_MANIFEST_ERROR, request->GetURL(), response_code, false /*is_cross_origin*/)); if (inprogress_cache_.get()) { pending_master_entries_.erase(found); --master_entries_completed_; if (update_type_ == CACHE_ATTEMPT && pending_master_entries_.empty()) { HandleCacheFailure( blink::mojom::AppCacheErrorDetails( message, blink::mojom::AppCacheErrorReason::APPCACHE_MANIFEST_ERROR, request->GetURL(), response_code, false /*is_cross_origin*/), fetcher->result(), GURL()); return; } } } DCHECK(internal_state_ != CACHE_FAILURE); FetchMasterEntries(); MaybeCompleteUpdate(); } 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: 1 Example 2: Code: void vmalloc_sync_all(void) { sync_global_pgds(VMALLOC_START & PGDIR_MASK, VMALLOC_END); } 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: 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 ServiceWorkerContextCore::IsValidRegisterRequest( const GURL& script_url, const GURL& scope_url, std::string* out_error) const { if (!scope_url.is_valid() || !script_url.is_valid()) { *out_error = ServiceWorkerConsts::kBadMessageInvalidURL; return false; } if (ServiceWorkerUtils::ContainsDisallowedCharacter(scope_url, script_url, out_error)) { return false; } std::vector<GURL> urls = {scope_url, script_url}; if (!ServiceWorkerUtils::AllOriginsMatchAndCanAccessServiceWorkers(urls)) { *out_error = ServiceWorkerConsts::kBadMessageImproperOrigins; return false; } return true; } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int get_rock_ridge_filename(struct iso_directory_record *de, char *retname, struct inode *inode) { struct rock_state rs; struct rock_ridge *rr; int sig; int retnamlen = 0; int truncate = 0; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; *retname = 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_NM) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('N', 'M'): if (truncate) break; if (rr->len < 5) break; /* * If the flags are 2 or 4, this indicates '.' or '..'. * We don't want to do anything with this, because it * screws up the code that calls us. We don't really * care anyways, since we can just use the non-RR * name. */ if (rr->u.NM.flags & 6) break; if (rr->u.NM.flags & ~1) { printk("Unsupported NM flag settings (%d)\n", rr->u.NM.flags); break; } if ((strlen(retname) + rr->len - 5) >= 254) { truncate = 1; break; } strncat(retname, rr->u.NM.name, rr->len - 5); retnamlen += rr->len - 5; break; case SIG('R', 'E'): kfree(rs.buffer); return -1; default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) return retnamlen; /* If 0, this file did not have a NM field */ out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } Commit Message: get_rock_ridge_filename(): handle malformed NM entries Payloads of NM entries are not supposed to contain NUL. When we run into such, only the part prior to the first NUL goes into the concatenation (i.e. the directory entry name being encoded by a bunch of NM entries). We do stop when the amount collected so far + the claimed amount in the current NM entry exceed 254. So far, so good, but what we return as the total length is the sum of *claimed* sizes, not the actual amount collected. And that can grow pretty large - not unlimited, since you'd need to put CE entries in between to be able to get more than the maximum that could be contained in one isofs directory entry / continuation chunk and we are stop once we'd encountered 32 CEs, but you can get about 8Kb easily. And that's what will be passed to readdir callback as the name length. 8Kb __copy_to_user() from a buffer allocated by __get_free_page() Cc: [email protected] # 0.98pl6+ (yes, really) Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: void blk_mq_release(struct request_queue *q) { struct blk_mq_hw_ctx *hctx; unsigned int i; /* hctx kobj stays in hctx */ queue_for_each_hw_ctx(q, hctx, i) { if (!hctx) continue; kfree(hctx->ctxs); kfree(hctx); } kfree(q->queue_hw_ctx); /* ctx kobj stays in queue_ctx */ free_percpu(q->queue_ctx); } 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 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: diff_filter_context(int context, int upper_bound, int lower_bound, xmlNode * xml_node, xmlNode * parent) { xmlNode *us = NULL; xmlNode *child = NULL; xmlAttrPtr pIter = NULL; xmlNode *new_parent = parent; const char *name = crm_element_name(xml_node); CRM_CHECK(xml_node != NULL && name != NULL, return); us = create_xml_node(parent, name); for (pIter = crm_first_attr(xml_node); pIter != NULL; pIter = pIter->next) { const char *p_name = (const char *)pIter->name; const char *p_value = crm_attr_value(pIter); lower_bound = context; crm_xml_add(us, p_name, p_value); } if (lower_bound >= 0 || upper_bound >= 0) { crm_xml_add(us, XML_ATTR_ID, ID(xml_node)); new_parent = us; } else { upper_bound = in_upper_context(0, context, xml_node); if (upper_bound >= 0) { crm_xml_add(us, XML_ATTR_ID, ID(xml_node)); new_parent = us; } else { free_xml(us); us = NULL; } } for (child = __xml_first_child(us); child != NULL; child = __xml_next(child)) { diff_filter_context(context, upper_bound - 1, lower_bound - 1, child, new_parent); } } Commit Message: Fix: acl: Do not delay evaluation of added nodes in some situations It is not appropriate when the node has no children as it is not a placeholder 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: MagickExport void CatchException(ExceptionInfo *exception) { register const ExceptionInfo *p; assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (exception->exceptions == (void *) NULL) return; LockSemaphoreInfo(exception->semaphore); ResetLinkedListIterator((LinkedListInfo *) exception->exceptions); p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *) exception->exceptions); while (p != (const ExceptionInfo *) NULL) { if ((p->severity >= WarningException) && (p->severity < ErrorException)) MagickWarning(p->severity,p->reason,p->description); if ((p->severity >= ErrorException) && (p->severity < FatalErrorException)) MagickError(p->severity,p->reason,p->description); if (p->severity >= FatalErrorException) MagickFatalError(p->severity,p->reason,p->description); p=(const ExceptionInfo *) GetNextValueInLinkedList((LinkedListInfo *) exception->exceptions); } UnlockSemaphoreInfo(exception->semaphore); ClearMagickException(exception); } Commit Message: Suspend exception processing if there are too many exceptions CWE ID: CWE-119 Target: 1 Example 2: Code: SProcXvPutImage(ClientPtr client) { REQUEST(xvPutImageReq); REQUEST_AT_LEAST_SIZE(xvPutImageReq); swaps(&stuff->length); swapl(&stuff->port); swapl(&stuff->drawable); swapl(&stuff->gc); swapl(&stuff->id); swaps(&stuff->src_x); swaps(&stuff->src_y); swaps(&stuff->src_w); swaps(&stuff->src_h); swaps(&stuff->drw_x); swaps(&stuff->drw_y); swaps(&stuff->drw_w); swaps(&stuff->drw_h); swaps(&stuff->width); swaps(&stuff->height); return XvProcVector[xv_PutImage] (client); } 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: get_option_arg( char* option, char** *pargv, char** argend ) { if ( option[2] == 0 ) { char** argv = *pargv; if ( ++argv >= argend ) usage(); option = argv[0]; *pargv = argv; } else option += 2; return option; } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OMX_ERRORTYPE SoftMP3::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex > 1) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSamplingRate; return OMX_ErrorNone; } case OMX_IndexParamAudioMp3: { OMX_AUDIO_PARAM_MP3TYPE *mp3Params = (OMX_AUDIO_PARAM_MP3TYPE *)params; if (mp3Params->nPortIndex > 1) { return OMX_ErrorUndefined; } mp3Params->nChannels = mNumChannels; mp3Params->nBitRate = 0 /* unknown */; mp3Params->nSampleRate = mSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(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 XDisplayExists() { return (GetXDisplay() != NULL); } Commit Message: Make shared memory segments writable only by their rightful owners. BUG=143859 TEST=Chrome's UI still works on Linux and Chrome OS Review URL: https://chromiumcodereview.appspot.com/10854242 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98 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: bool DesktopWindowTreeHostX11::CaptureSystemKeyEventsImpl( base::Optional<base::flat_set<ui::DomCode>> dom_codes) { DCHECK(!keyboard_hook_); keyboard_hook_ = ui::KeyboardHook::CreateModifierKeyboardHook( std::move(dom_codes), GetAcceleratedWidget(), base::BindRepeating(&DesktopWindowTreeHostX11::DispatchKeyEvent, base::Unretained(this))); return keyboard_hook_ != nullptr; } Commit Message: Fix PIP window being blank after minimize/show DesktopWindowTreeHostX11::SetVisible only made the call into OnNativeWidgetVisibilityChanged when transitioning from shown to minimized and not vice versa. This is because this change https://chromium-review.googlesource.com/c/chromium/src/+/1437263 considered IsVisible to be true when minimized, which made IsVisible always true in this case. This caused layers to be hidden but never shown again. This is a reland of: https://chromium-review.googlesource.com/c/chromium/src/+/1580103 Bug: 949199 Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617 Reviewed-by: Scott Violet <[email protected]> Commit-Queue: enne <[email protected]> Cr-Commit-Position: refs/heads/master@{#654280} CWE ID: CWE-284 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 cdrom_ioctl_drive_status(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n"); if (!(cdi->ops->capability & CDC_DRIVE_STATUS)) return -ENOSYS; if (!CDROM_CAN(CDC_SELECT_DISC) || (arg == CDSL_CURRENT || arg == CDSL_NONE)) return cdi->ops->drive_status(cdi, CDSL_CURRENT); if (((int)arg >= cdi->capacity)) return -EINVAL; return cdrom_slot_status(cdi, arg); } Commit Message: cdrom: Fix info leak/OOB read in cdrom_ioctl_drive_status Like d88b6d04: "cdrom: information leak in cdrom_ioctl_media_changed()" There is another cast from unsigned long to int which causes a bounds check to fail with specially crafted input. The value is then used as an index in the slot array in cdrom_slot_status(). Signed-off-by: Scott Bauer <[email protected]> Signed-off-by: Scott Bauer <[email protected]> Cc: [email protected] Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: static cycle_t read_tsc(void) { cycle_t ret = (cycle_t)rdtsc_ordered(); u64 last = pvclock_gtod_data.clock.cycle_last; if (likely(ret >= last)) return ret; /* * GCC likes to generate cmov here, but this branch is extremely * predictable (it's just a funciton of time and the likely is * very likely) and there's a data dependence, so force GCC * to generate a branch instead. I don't barrier() because * we don't actually need a barrier, and if this function * ever gets inlined it will generate worse code. */ asm volatile (""); return last; } Commit Message: KVM: x86: Reload pit counters for all channels when restoring state Currently if userspace restores the pit counters with a count of 0 on channels 1 or 2 and the guest attempts to read the count on those channels, then KVM will perform a mod of 0 and crash. This will ensure that 0 values are converted to 65536 as per the spec. This is CVE-2015-7513. Signed-off-by: Andy Honig <[email protected]> Signed-off-by: Paolo Bonzini <[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: struct redirect_rule *http_parse_redirect_rule(const char *file, int linenum, struct proxy *curproxy, const char **args, char **errmsg, int use_fmt) { struct redirect_rule *rule; int cur_arg; int type = REDIRECT_TYPE_NONE; int code = 302; const char *destination = NULL; const char *cookie = NULL; int cookie_set = 0; unsigned int flags = REDIRECT_FLAG_NONE; struct acl_cond *cond = NULL; cur_arg = 0; while (*(args[cur_arg])) { if (strcmp(args[cur_arg], "location") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; type = REDIRECT_TYPE_LOCATION; cur_arg++; destination = args[cur_arg]; } else if (strcmp(args[cur_arg], "prefix") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; type = REDIRECT_TYPE_PREFIX; cur_arg++; destination = args[cur_arg]; } else if (strcmp(args[cur_arg], "scheme") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; type = REDIRECT_TYPE_SCHEME; cur_arg++; destination = args[cur_arg]; } else if (strcmp(args[cur_arg], "set-cookie") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; cur_arg++; cookie = args[cur_arg]; cookie_set = 1; } else if (strcmp(args[cur_arg], "clear-cookie") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; cur_arg++; cookie = args[cur_arg]; cookie_set = 0; } else if (strcmp(args[cur_arg], "code") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; cur_arg++; code = atol(args[cur_arg]); if (code < 301 || code > 308 || (code > 303 && code < 307)) { memprintf(errmsg, "'%s': unsupported HTTP code '%s' (must be one of 301, 302, 303, 307 or 308)", args[cur_arg - 1], args[cur_arg]); return NULL; } } else if (!strcmp(args[cur_arg],"drop-query")) { flags |= REDIRECT_FLAG_DROP_QS; } else if (!strcmp(args[cur_arg],"append-slash")) { flags |= REDIRECT_FLAG_APPEND_SLASH; } else if (strcmp(args[cur_arg], "if") == 0 || strcmp(args[cur_arg], "unless") == 0) { cond = build_acl_cond(file, linenum, curproxy, (const char **)args + cur_arg, errmsg); if (!cond) { memprintf(errmsg, "error in condition: %s", *errmsg); return NULL; } break; } else { memprintf(errmsg, "expects 'code', 'prefix', 'location', 'scheme', 'set-cookie', 'clear-cookie', 'drop-query' or 'append-slash' (was '%s')", args[cur_arg]); return NULL; } cur_arg++; } if (type == REDIRECT_TYPE_NONE) { memprintf(errmsg, "redirection type expected ('prefix', 'location', or 'scheme')"); return NULL; } rule = (struct redirect_rule *)calloc(1, sizeof(*rule)); rule->cond = cond; LIST_INIT(&rule->rdr_fmt); if (!use_fmt) { /* old-style static redirect rule */ rule->rdr_str = strdup(destination); rule->rdr_len = strlen(destination); } else { /* log-format based redirect rule */ /* Parse destination. Note that in the REDIRECT_TYPE_PREFIX case, * if prefix == "/", we don't want to add anything, otherwise it * makes it hard for the user to configure a self-redirection. */ proxy->conf.args.ctx = ARGC_RDR; if (!(type == REDIRECT_TYPE_PREFIX && destination[0] == '/' && destination[1] == '\0')) { parse_logformat_string(destination, curproxy, &rule->rdr_fmt, LOG_OPT_HTTP, (curproxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, file, linenum); free(curproxy->conf.lfs_file); curproxy->conf.lfs_file = strdup(curproxy->conf.args.file); curproxy->conf.lfs_line = curproxy->conf.args.line; } } if (cookie) { /* depending on cookie_set, either we want to set the cookie, or to clear it. * a clear consists in appending "; path=/; Max-Age=0;" at the end. */ rule->cookie_len = strlen(cookie); if (cookie_set) { rule->cookie_str = malloc(rule->cookie_len + 10); memcpy(rule->cookie_str, cookie, rule->cookie_len); memcpy(rule->cookie_str + rule->cookie_len, "; path=/;", 10); rule->cookie_len += 9; } else { rule->cookie_str = malloc(rule->cookie_len + 21); memcpy(rule->cookie_str, cookie, rule->cookie_len); memcpy(rule->cookie_str + rule->cookie_len, "; path=/; Max-Age=0;", 21); rule->cookie_len += 20; } } rule->type = type; rule->code = code; rule->flags = flags; LIST_INIT(&rule->list); return rule; missing_arg: memprintf(errmsg, "missing argument for '%s'", args[cur_arg]); return NULL; } Commit Message: 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 Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) { const char *option; Image *image; int jp2_status; MagickBooleanType status; opj_codec_t *jp2_codec; opj_codestream_index_t *codestream_index = (opj_codestream_index_t *) NULL; opj_dparameters_t parameters; opj_image_t *jp2_image; opj_stream_t *jp2_stream; register ssize_t i; ssize_t y; unsigned char sans[4]; /* 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); } /* Initialize JP2 codec. */ if (ReadBlob(image,4,sans) != 4) { image=DestroyImageList(image); return((Image *) NULL); } (void) SeekBlob(image,SEEK_SET,0); if (LocaleCompare(image_info->magick,"JPT") == 0) jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); else if (IsJ2K(sans,4) != MagickFalse) jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); else jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); opj_set_default_decoder_parameters(&parameters); option=GetImageOption(image_info,"jp2:reduce-factor"); if (option != (const char *) NULL) parameters.cp_reduce=StringToInteger(option); option=GetImageOption(image_info,"jp2:quality-layers"); if (option == (const char *) NULL) option=GetImageOption(image_info,"jp2:layer-number"); if (option != (const char *) NULL) parameters.cp_layer=StringToInteger(option); if (opj_setup_decoder(jp2_codec,&parameters) == 0) { opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToManageJP2Stream"); } jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); opj_stream_set_read_function(jp2_stream,JP2ReadHandler); opj_stream_set_write_function(jp2_stream,JP2WriteHandler); opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); opj_stream_set_user_data(jp2_stream,image,NULL); opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } jp2_status=1; if ((image->columns != 0) && (image->rows != 0)) { /* Extract an area from the image. */ jp2_status=opj_set_decode_area(jp2_codec,jp2_image, (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y, (OPJ_INT32) image->extract_info.x+(ssize_t) image->columns, (OPJ_INT32) image->extract_info.y+(ssize_t) image->rows); if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } } if ((image_info->number_scenes != 0) && (image_info->scene != 0)) jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, (unsigned int) image_info->scene-1); else if (image->ping == MagickFalse) { jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); if (jp2_status != 0) jp2_status=opj_end_decompress(jp2_codec,jp2_stream); } if (jp2_status == 0) { opj_stream_destroy(jp2_stream); opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(DelegateError,"UnableToDecodeImageFile"); } opj_stream_destroy(jp2_stream); for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) || (jp2_image->comps[0].dx != jp2_image->comps[i].dx) || (jp2_image->comps[0].dy != jp2_image->comps[i].dy) || (jp2_image->comps[0].prec != jp2_image->comps[i].prec) || (jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd)) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported") } } /* Convert JP2 image. */ image->columns=(size_t) jp2_image->comps[0].w; image->rows=(size_t) jp2_image->comps[0].h; image->depth=jp2_image->comps[0].prec; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } image->compression=JPEG2000Compression; if (jp2_image->color_space == 2) { SetImageColorspace(image,GRAYColorspace); if (jp2_image->numcomps > 1) image->matte=MagickTrue; } else if (jp2_image->color_space == 3) SetImageColorspace(image,Rec601YCbCrColorspace); if (jp2_image->numcomps > 3) image->matte=MagickTrue; if (jp2_image->icc_profile_buf != (unsigned char *) NULL) { StringInfo *profile; profile=BlobToStringInfo(jp2_image->icc_profile_buf, jp2_image->icc_profile_len); if (profile != (StringInfo *) NULL) SetImageProfile(image,"icc",profile); } if (image->ping != MagickFalse) { opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); return(GetFirstImageInList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) jp2_image->numcomps; i++) { double pixel, scale; scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); switch (i) { case 0: { q->red=ClampToQuantum(pixel); q->green=q->red; q->blue=q->red; q->opacity=OpaqueOpacity; break; } case 1: { if (jp2_image->numcomps == 2) { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } q->green=ClampToQuantum(pixel); break; } case 2: { q->blue=ClampToQuantum(pixel); break; } case 3: { q->opacity=ClampToQuantum(QuantumRange-pixel); break; } } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* Free resources. */ opj_destroy_codec(jp2_codec); opj_image_destroy(jp2_image); opj_destroy_cstr_index(&codestream_index); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: ... CWE ID: CWE-20 Target: 1 Example 2: Code: static int lzh_decompress(struct kwajd_stream *lzh) { register unsigned int bit_buffer; register int bits_left, i; register unsigned short sym; unsigned char *i_ptr, *i_end, lit_run = 0; int j, pos = 0, len, offset, err; unsigned int types[6]; /* reset global state */ INIT_BITS; RESTORE_BITS; memset(&lzh->window[0], LZSS_WINDOW_FILL, (size_t) LZSS_WINDOW_SIZE); /* read 6 encoding types (for byte alignment) but only 5 are needed */ for (i = 0; i < 6; i++) READ_BITS_SAFE(types[i], 4); /* read huffman table symbol lengths and build huffman trees */ BUILD_TREE(MATCHLEN1, types[0]); BUILD_TREE(MATCHLEN2, types[1]); BUILD_TREE(LITLEN, types[2]); BUILD_TREE(OFFSET, types[3]); BUILD_TREE(LITERAL, types[4]); while (!lzh->input_end) { if (lit_run) READ_HUFFSYM_SAFE(MATCHLEN2, len); else READ_HUFFSYM_SAFE(MATCHLEN1, len); if (len > 0) { len += 2; lit_run = 0; /* not the end of a literal run */ READ_HUFFSYM_SAFE(OFFSET, j); offset = j << 6; READ_BITS_SAFE(j, 6); offset |= j; /* copy match as output and into the ring buffer */ while (len-- > 0) { lzh->window[pos] = lzh->window[(pos+4096-offset) & 4095]; WRITE_BYTE; pos++; pos &= 4095; } } else { READ_HUFFSYM_SAFE(LITLEN, len); len++; lit_run = (len == 32) ? 0 : 1; /* end of a literal run? */ while (len-- > 0) { READ_HUFFSYM_SAFE(LITERAL, j); /* copy as output and into the ring buffer */ lzh->window[pos] = j; WRITE_BYTE; pos++; pos &= 4095; } } } return MSPACK_ERR_OK; } Commit Message: kwaj_read_headers(): fix handling of non-terminated strings CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void *jas_malloc(size_t size) { void *result; JAS_DBGLOG(101, ("jas_malloc called with %zu\n", size)); result = malloc(size); JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result)); return result; } Commit Message: Fixed an integer overflow problem. CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void LogoService::SetClockForTests(std::unique_ptr<base::Clock> clock) { clock_for_test_ = std::move(clock); } 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 Target: 1 Example 2: Code: xfs_inode_validate_extsize( struct xfs_mount *mp, uint32_t extsize, uint16_t mode, uint16_t flags) { bool rt_flag; bool hint_flag; bool inherit_flag; uint32_t extsize_bytes; uint32_t blocksize_bytes; rt_flag = (flags & XFS_DIFLAG_REALTIME); hint_flag = (flags & XFS_DIFLAG_EXTSIZE); inherit_flag = (flags & XFS_DIFLAG_EXTSZINHERIT); extsize_bytes = XFS_FSB_TO_B(mp, extsize); if (rt_flag) blocksize_bytes = mp->m_sb.sb_rextsize << mp->m_sb.sb_blocklog; else blocksize_bytes = mp->m_sb.sb_blocksize; if ((hint_flag || inherit_flag) && !(S_ISDIR(mode) || S_ISREG(mode))) return __this_address; if (hint_flag && !S_ISREG(mode)) return __this_address; if (inherit_flag && !S_ISDIR(mode)) return __this_address; if ((hint_flag || inherit_flag) && extsize == 0) return __this_address; if (!(hint_flag || inherit_flag) && extsize != 0) return __this_address; if (extsize_bytes % blocksize_bytes) return __this_address; if (extsize > MAXEXTLEN) return __this_address; if (!rt_flag && extsize > mp->m_sb.sb_agblocks / 2) return __this_address; return NULL; } Commit Message: xfs: More robust inode extent count validation When the inode is in extent format, it can't have more extents that fit in the inode fork. We don't currenty check this, and so this corruption goes unnoticed by the inode verifiers. This can lead to crashes operating on invalid in-memory structures. Attempts to access such a inode will now error out in the verifier rather than allowing modification operations to proceed. Reported-by: Wen Xu <[email protected]> Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Darrick J. Wong <[email protected]> [darrick: fix a typedef, add some braces and breaks to shut up compiler warnings] Signed-off-by: Darrick J. Wong <[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: _exsltDateAdd (exsltDateValPtr dt, exsltDateValPtr dur) { exsltDateValPtr ret; long carry, tempdays, temp; exsltDateValDatePtr r, d; exsltDateValDurationPtr u; if ((dt == NULL) || (dur == NULL)) return NULL; ret = exsltDateCreateDate(dt->type); if (ret == NULL) return NULL; r = &(ret->value.date); d = &(dt->value.date); u = &(dur->value.dur); /* normalization */ if (d->mon == 0) d->mon = 1; /* normalize for time zone offset */ u->sec -= (d->tzo * 60); /* changed from + to - (bug 153000) */ d->tzo = 0; /* normalization */ if (d->day == 0) d->day = 1; /* month */ carry = d->mon + u->mon; r->mon = (unsigned int)MODULO_RANGE(carry, 1, 13); carry = (long)FQUOTIENT_RANGE(carry, 1, 13); /* year (may be modified later) */ r->year = d->year + carry; if (r->year == 0) { if (d->year > 0) r->year--; else r->year++; } /* time zone */ r->tzo = d->tzo; r->tz_flag = d->tz_flag; /* seconds */ r->sec = d->sec + u->sec; carry = (long)FQUOTIENT((long)r->sec, 60); if (r->sec != 0.0) { r->sec = MODULO(r->sec, 60.0); } /* minute */ carry += d->min; r->min = (unsigned int)MODULO(carry, 60); carry = (long)FQUOTIENT(carry, 60); /* hours */ carry += d->hour; r->hour = (unsigned int)MODULO(carry, 24); carry = (long)FQUOTIENT(carry, 24); /* * days * Note we use tempdays because the temporary values may need more * than 5 bits */ if ((VALID_YEAR(r->year)) && (VALID_MONTH(r->mon)) && (d->day > MAX_DAYINMONTH(r->year, r->mon))) tempdays = MAX_DAYINMONTH(r->year, r->mon); else if (d->day < 1) tempdays = 1; else tempdays = d->day; tempdays += u->day + carry; while (1) { if (tempdays < 1) { long tmon = (long)MODULO_RANGE((int)r->mon-1, 1, 13); long tyr = r->year + (long)FQUOTIENT_RANGE((int)r->mon-1, 1, 13); if (tyr == 0) tyr--; /* * Coverity detected an overrun in daysInMonth * of size 12 at position 12 with index variable "((r)->mon - 1)" */ if (tmon < 0) tmon = 0; if (tmon > 12) tmon = 12; tempdays += MAX_DAYINMONTH(tyr, tmon); carry = -1; } else if (tempdays > (long)MAX_DAYINMONTH(r->year, r->mon)) { tempdays = tempdays - MAX_DAYINMONTH(r->year, r->mon); carry = 1; } else break; temp = r->mon + carry; r->mon = (unsigned int)MODULO_RANGE(temp, 1, 13); r->year = r->year + (long)FQUOTIENT_RANGE(temp, 1, 13); if (r->year == 0) { if (temp < 1) r->year--; else r->year++; } } r->day = tempdays; /* * adjust the date/time type to the date values */ if (ret->type != XS_DATETIME) { if ((r->hour) || (r->min) || (r->sec)) ret->type = XS_DATETIME; else if (ret->type != XS_DATE) { if (r->day != 1) ret->type = XS_DATE; else if ((ret->type != XS_GYEARMONTH) && (r->mon != 1)) ret->type = XS_GYEARMONTH; } } return ret; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Chapters::Display::ShallowCopy(Display& rhs) const { rhs.m_string = m_string; rhs.m_language = m_language; rhs.m_country = m_country; } 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: void TabCloseableStateWatcher::TabStripWatcher::TabDetachedAt( TabContentsWrapper* tab_contents, int index) { main_watcher_->OnTabStripChanged(browser_, false); } 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: void ExtensionTtsController::Stop() { if (current_utterance_ && !current_utterance_->extension_id().empty()) { current_utterance_->profile()->GetExtensionEventRouter()-> DispatchEventToExtension( current_utterance_->extension_id(), events::kOnStop, "[]", current_utterance_->profile(), GURL()); } else { GetPlatformImpl()->clear_error(); GetPlatformImpl()->StopSpeaking(); } if (current_utterance_) current_utterance_->set_error(kSpeechInterruptedError); FinishCurrentUtterance(); ClearUtteranceQueue(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
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 UnprivilegedProcessDelegate::LaunchProcess( IPC::Listener* delegate, ScopedHandle* process_exit_event_out) { DCHECK(main_task_runner_->BelongsToCurrentThread()); std::string channel_name = GenerateIpcChannelName(this); ScopedHandle client; scoped_ptr<IPC::ChannelProxy> server; if (!CreateConnectedIpcChannel(channel_name, delegate, &client, &server)) return false; std::string pipe_handle = base::StringPrintf( "%d", reinterpret_cast<ULONG_PTR>(client.Get())); CommandLine command_line(binary_path_); command_line.AppendSwitchASCII(kDaemonPipeSwitchName, pipe_handle); command_line.CopySwitchesFrom(*CommandLine::ForCurrentProcess(), kCopiedSwitchNames, arraysize(kCopiedSwitchNames)); ScopedHandle worker_thread; worker_process_.Close(); if (!LaunchProcessWithToken(command_line.GetProgram(), command_line.GetCommandLineString(), NULL, true, 0, &worker_process_, &worker_thread)) { return false; } ScopedHandle process_exit_event; if (!DuplicateHandle(GetCurrentProcess(), worker_process_, GetCurrentProcess(), process_exit_event.Receive(), SYNCHRONIZE, FALSE, 0)) { LOG_GETLASTERROR(ERROR) << "Failed to duplicate a handle"; KillProcess(CONTROL_C_EXIT); return false; } channel_ = server.Pass(); *process_exit_event_out = process_exit_event.Pass(); return true; } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt) { int size = 0, ret; const uint8_t *data; uint32_t flags; int64_t val; data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size); if (!data) return 0; if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) { av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter " "changes, but PARAM_CHANGE side data was sent to it.\n"); ret = AVERROR(EINVAL); goto fail2; } if (size < 4) goto fail; flags = bytestream_get_le32(&data); size -= 4; if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) { if (size < 4) goto fail; val = bytestream_get_le32(&data); if (val <= 0 || val > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "Invalid channel count"); ret = AVERROR_INVALIDDATA; goto fail2; } avctx->channels = val; size -= 4; } if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) { if (size < 8) goto fail; avctx->channel_layout = bytestream_get_le64(&data); size -= 8; } if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) { if (size < 4) goto fail; val = bytestream_get_le32(&data); if (val <= 0 || val > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "Invalid sample rate"); ret = AVERROR_INVALIDDATA; goto fail2; } avctx->sample_rate = val; size -= 4; } if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) { if (size < 8) goto fail; avctx->width = bytestream_get_le32(&data); avctx->height = bytestream_get_le32(&data); size -= 8; ret = ff_set_dimensions(avctx, avctx->width, avctx->height); if (ret < 0) goto fail2; } return 0; fail: av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n"); ret = AVERROR_INVALIDDATA; fail2: if (ret < 0) { av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n"); if (avctx->err_recognition & AV_EF_EXPLODE) return ret; } 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: mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; uint8_t type; switch (type = cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { size_t sz = file_pstring_length_size(m); char *ptr1 = p->s, *ptr2 = ptr1 + sz; size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) { /* * The size of the pascal string length (sz) * is 1, 2, or 4. We need at least 1 byte for NUL * termination, but we've already truncated the * string by p->s, so we need to deduct sz. */ len = sizeof(p->s) - sz; } while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); if (type == FILE_BELONG) cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); if (type == FILE_BEQUAD) cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); if (type == FILE_LELONG) cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); if (type == FILE_LEQUAD) cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); if (type == FILE_MELONG) cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0; } } Commit Message: PR/398: Correctly truncate pascal strings (fixes out of bounds read of 1, 2, or 4 bytes). 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 output_quantization_factor(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { if (out_depth == 16 && in_depth != 16 && pm->calculations_use_input_precision) return 257; else return 1; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: flx_colorspace_convert (FlxColorSpaceConverter * flxpal, guchar * src, guchar * dest) { guint size, col; g_return_if_fail (flxpal != NULL); g_return_if_fail (src != dest); size = flxpal->width * flxpal->height; while (size--) { col = (*src++ * 3); #if G_BYTE_ORDER == G_BIG_ENDIAN *dest++ = 0; *dest++ = flxpal->palvec[col]; *dest++ = flxpal->palvec[col + 1]; *dest++ = flxpal->palvec[col + 2]; #else *dest++ = flxpal->palvec[col + 2]; *dest++ = flxpal->palvec[col + 1]; *dest++ = flxpal->palvec[col]; *dest++ = 0; #endif } } Commit Message: CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int OBJ_sn2nid(const char *s) { ASN1_OBJECT o; const ASN1_OBJECT *oo= &o; ADDED_OBJ ad,*adp; const unsigned int *op; o.sn=s; if (added != NULL) { ad.type=ADDED_SNAME; ad.obj= &o; adp=lh_ADDED_OBJ_retrieve(added,&ad); if (adp != NULL) return (adp->obj->nid); } op=OBJ_bsearch_sn(&oo, sn_objs, NUM_SN); if (op == NULL) return(NID_undef); return(nid_objs[*op].nid); } Commit Message: 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: int xt_check_entry_offsets(const void *base, unsigned int target_offset, unsigned int next_offset) { const struct xt_entry_target *t; const char *e = base; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct xt_standard_target) != next_offset) return -EINVAL; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void ReleaseProcessIfNeeded() { content::UtilityThread::Get()->ReleaseProcessIfNeeded(); } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 [email protected], [email protected], [email protected], [email protected] Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} 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 SimplifyMarkupCommand::doApply() { Node* rootNode = m_firstNode->parentNode(); Vector<RefPtr<Node> > nodesToRemove; for (Node* node = m_firstNode.get(); node && node != m_nodeAfterLast; node = NodeTraversal::next(*node)) { if (node->firstChild() || (node->isTextNode() && node->nextSibling())) continue; Node* startingNode = node->parentNode(); if (!startingNode) continue; RenderStyle* startingStyle = startingNode->renderStyle(); if (!startingStyle) continue; Node* currentNode = startingNode; Node* topNodeWithStartingStyle = 0; while (currentNode != rootNode) { if (currentNode->parentNode() != rootNode && isRemovableBlock(currentNode)) nodesToRemove.append(currentNode); currentNode = currentNode->parentNode(); if (!currentNode) break; if (!currentNode->renderer() || !currentNode->renderer()->isRenderInline() || toRenderInline(currentNode->renderer())->alwaysCreateLineBoxes()) continue; if (currentNode->firstChild() != currentNode->lastChild()) { topNodeWithStartingStyle = 0; break; } unsigned context; if (currentNode->renderStyle()->visualInvalidationDiff(*startingStyle, context) == StyleDifferenceEqual && !context) topNodeWithStartingStyle = currentNode; } if (topNodeWithStartingStyle) { for (Node* node = startingNode; node != topNodeWithStartingStyle; node = node->parentNode()) nodesToRemove.append(node); } } for (size_t i = 0; i < nodesToRemove.size(); ++i) { int numPrunedAncestors = pruneSubsequentAncestorsToRemove(nodesToRemove, i); if (numPrunedAncestors < 0) continue; removeNodePreservingChildren(nodesToRemove[i], AssumeContentIsAlwaysEditable); i += numPrunedAncestors; } } 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: OMX::buffer_id OMXNodeInstance::makeBufferID(OMX_BUFFERHEADERTYPE *bufferHeader) { return (OMX::buffer_id)bufferHeader; } Commit Message: IOMX: Enable buffer ptr to buffer id translation for arm32 Bug: 20634516 Change-Id: Iac9eac3cb251eccd9bbad5df7421a07edc21da0c (cherry picked from commit 2d6b6601743c3c6960c6511a2cb774ef902759f4) CWE ID: CWE-119 Target: 1 Example 2: Code: SoapError(struct upnphttp * h, int errCode, const char * errDesc) { static const char resp[] = "<s:Envelope " "xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" " "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" "<s:Body>" "<s:Fault>" "<faultcode>s:Client</faultcode>" "<faultstring>UPnPError</faultstring>" "<detail>" "<UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\">" "<errorCode>%d</errorCode>" "<errorDescription>%s</errorDescription>" "</UPnPError>" "</detail>" "</s:Fault>" "</s:Body>" "</s:Envelope>"; char body[2048]; int bodylen; syslog(LOG_INFO, "Returning UPnPError %d: %s", errCode, errDesc); bodylen = snprintf(body, sizeof(body), resp, errCode, errDesc); BuildResp2_upnphttp(h, 500, "Internal Server Error", body, bodylen); SendRespAndClose_upnphttp(h); } Commit Message: GetOutboundPinholeTimeout: check args 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: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h, uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount) { const cdf_section_header_t *shp; cdf_section_header_t sh; const uint8_t *p, *q, *e; int16_t s16; int32_t s32; uint32_t u32; int64_t s64; uint64_t u64; cdf_timestamp_t tp; size_t i, o, o4, nelements, j; cdf_property_info_t *inp; if (offs > UINT32_MAX / 4) { errno = EFTYPE; goto out; } shp = CAST(const cdf_section_header_t *, (const void *) ((const char *)sst->sst_tab + offs)); if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1) goto out; sh.sh_len = CDF_TOLE4(shp->sh_len); #define CDF_SHLEN_LIMIT (UINT32_MAX / 8) if (sh.sh_len > CDF_SHLEN_LIMIT) { errno = EFTYPE; goto out; } sh.sh_properties = CDF_TOLE4(shp->sh_properties); #define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp))) if (sh.sh_properties > CDF_PROP_LIMIT) goto out; DPRINTF(("section len: %u properties %u\n", sh.sh_len, sh.sh_properties)); if (*maxcount) { if (*maxcount > CDF_PROP_LIMIT) goto out; *maxcount += sh.sh_properties; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); } else { *maxcount = sh.sh_properties; inp = CAST(cdf_property_info_t *, malloc(*maxcount * sizeof(*inp))); } if (inp == NULL) goto out; *info = inp; inp += *count; *count += sh.sh_properties; p = CAST(const uint8_t *, (const void *) ((const char *)(const void *)sst->sst_tab + offs + sizeof(sh))); e = CAST(const uint8_t *, (const void *) (((const char *)(const void *)shp) + sh.sh_len)); if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1) goto out; for (i = 0; i < sh.sh_properties; i++) { size_t ofs = CDF_GETUINT32(p, (i << 1) + 1); q = (const uint8_t *)(const void *) ((const char *)(const void *)p + ofs - 2 * sizeof(uint32_t)); if (q > e) { DPRINTF(("Ran of the end %p > %p\n", q, e)); goto out; } inp[i].pi_id = CDF_GETUINT32(p, i << 1); inp[i].pi_type = CDF_GETUINT32(q, 0); DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n", i, inp[i].pi_id, inp[i].pi_type, q - p, offs)); if (inp[i].pi_type & CDF_VECTOR) { nelements = CDF_GETUINT32(q, 1); if (nelements == 0) { DPRINTF(("CDF_VECTOR with nelements == 0\n")); goto out; } o = 2; } else { nelements = 1; o = 1; } o4 = o * sizeof(uint32_t); if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED)) goto unknown; switch (inp[i].pi_type & CDF_TYPEMASK) { case CDF_NULL: case CDF_EMPTY: break; case CDF_SIGNED16: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s16, &q[o4], sizeof(s16)); inp[i].pi_s16 = CDF_TOLE2(s16); break; case CDF_SIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s32, &q[o4], sizeof(s32)); inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32); break; case CDF_BOOL: case CDF_UNSIGNED32: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); inp[i].pi_u32 = CDF_TOLE4(u32); break; case CDF_SIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&s64, &q[o4], sizeof(s64)); inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64); break; case CDF_UNSIGNED64: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64); break; case CDF_FLOAT: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u32, &q[o4], sizeof(u32)); u32 = CDF_TOLE4(u32); memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f)); break; case CDF_DOUBLE: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&u64, &q[o4], sizeof(u64)); u64 = CDF_TOLE8((uint64_t)u64); memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d)); break; case CDF_LENGTH32_STRING: case CDF_LENGTH32_WSTRING: if (nelements > 1) { size_t nelem = inp - *info; if (*maxcount > CDF_PROP_LIMIT || nelements > CDF_PROP_LIMIT) goto out; *maxcount += nelements; inp = CAST(cdf_property_info_t *, realloc(*info, *maxcount * sizeof(*inp))); if (inp == NULL) goto out; *info = inp; inp = *info + nelem; } DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n", nelements)); for (j = 0; j < nelements && i < sh.sh_properties; j++, i++) { uint32_t l = CDF_GETUINT32(q, o); inp[i].pi_str.s_len = l; inp[i].pi_str.s_buf = (const char *) (const void *)(&q[o4 + sizeof(l)]); DPRINTF(("l = %d, r = %" SIZE_T_FORMAT "u, s = %s\n", l, CDF_ROUND(l, sizeof(l)), inp[i].pi_str.s_buf)); if (l & 1) l++; o += l >> 1; if (q + o >= e) goto out; o4 = o * sizeof(uint32_t); } i--; break; case CDF_FILETIME: if (inp[i].pi_type & CDF_VECTOR) goto unknown; (void)memcpy(&tp, &q[o4], sizeof(tp)); inp[i].pi_tp = CDF_TOLE8((uint64_t)tp); break; case CDF_CLIPBOARD: if (inp[i].pi_type & CDF_VECTOR) goto unknown; break; default: unknown: DPRINTF(("Don't know how to deal with %x\n", inp[i].pi_type)); break; } } return 0; out: free(*info); return -1; } Commit Message: Fix incorrect bounds check for sector count. (Francisco Alonso and Jan Kaluza at RedHat) 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: process_bitmap_updates(STREAM s) { uint16 num_updates; uint16 left, top, right, bottom, width, height; uint16 cx, cy, bpp, Bpp, compress, bufsize, size; uint8 *data, *bmpdata; int i; logger(Protocol, Debug, "%s()", __func__); in_uint16_le(s, num_updates); for (i = 0; i < num_updates; i++) { in_uint16_le(s, left); in_uint16_le(s, top); in_uint16_le(s, right); in_uint16_le(s, bottom); in_uint16_le(s, width); in_uint16_le(s, height); in_uint16_le(s, bpp); Bpp = (bpp + 7) / 8; in_uint16_le(s, compress); in_uint16_le(s, bufsize); cx = right - left + 1; cy = bottom - top + 1; logger(Graphics, Debug, "process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d", left, top, right, bottom, width, height, Bpp, compress); if (!compress) { int y; bmpdata = (uint8 *) xmalloc(width * height * Bpp); for (y = 0; y < height; y++) { in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp); } ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); xfree(bmpdata); continue; } if (compress & 0x400) { size = bufsize; } else { in_uint8s(s, 2); /* pad */ in_uint16_le(s, size); in_uint8s(s, 4); /* line_size, final_size */ } in_uint8p(s, data, size); bmpdata = (uint8 *) xmalloc(width * height * Bpp); if (bitmap_decompress(bmpdata, width, height, data, size, Bpp)) { ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); } else { logger(Graphics, Warning, "process_bitmap_updates(), failed to decompress bitmap"); } xfree(bmpdata); } } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119 Target: 1 Example 2: Code: cpl_closeall () { struct cpelement *cpe; for (cpe = coproc_list.head; cpe; cpe = cpe->next) coproc_close (cpe->coproc); } 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: raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer, raptor_option option, int value) { if(value < 0 || !raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER)) return 1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: if(value) turtle_writer->flags |= TURTLE_WRITER_AUTO_INDENT; else turtle_writer->flags &= ~TURTLE_WRITER_AUTO_INDENT; break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: turtle_writer->indent = value; break; case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: break; /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: return -1; break; } return 0; } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200 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 dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *raw_data) { struct super_block *s; struct ecryptfs_sb_info *sbi; struct ecryptfs_dentry_info *root_info; const char *err = "Getting sb failed"; struct inode *inode; struct path path; int rc; sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL); if (!sbi) { rc = -ENOMEM; goto out; } rc = ecryptfs_parse_options(sbi, raw_data); if (rc) { err = "Error parsing options"; goto out; } s = sget(fs_type, NULL, set_anon_super, NULL); if (IS_ERR(s)) { rc = PTR_ERR(s); goto out; } s->s_flags = flags; rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY); if (rc) goto out1; ecryptfs_set_superblock_private(s, sbi); s->s_bdi = &sbi->bdi; /* ->kill_sb() will take care of sbi after that point */ sbi = NULL; s->s_op = &ecryptfs_sops; s->s_d_op = &ecryptfs_dops; err = "Reading sb failed"; rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path); if (rc) { ecryptfs_printk(KERN_WARNING, "kern_path() failed\n"); goto out1; } if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) { rc = -EINVAL; printk(KERN_ERR "Mount on filesystem of type " "eCryptfs explicitly disallowed due to " "known incompatibilities\n"); goto out_free; } ecryptfs_set_superblock_lower(s, path.dentry->d_sb); s->s_maxbytes = path.dentry->d_sb->s_maxbytes; s->s_blocksize = path.dentry->d_sb->s_blocksize; s->s_magic = ECRYPTFS_SUPER_MAGIC; inode = ecryptfs_get_inode(path.dentry->d_inode, s); rc = PTR_ERR(inode); if (IS_ERR(inode)) goto out_free; s->s_root = d_alloc_root(inode); if (!s->s_root) { iput(inode); rc = -ENOMEM; goto out_free; } rc = -ENOMEM; root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL); if (!root_info) goto out_free; /* ->kill_sb() will take care of root_info */ ecryptfs_set_dentry_private(s->s_root, root_info); ecryptfs_set_dentry_lower(s->s_root, path.dentry); ecryptfs_set_dentry_lower_mnt(s->s_root, path.mnt); s->s_flags |= MS_ACTIVE; return dget(s->s_root); out_free: path_put(&path); out1: deactivate_locked_super(s); out: if (sbi) { ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat); kmem_cache_free(ecryptfs_sb_info_cache, sbi); } printk(KERN_ERR "%s; rc = [%d]\n", err, rc); return ERR_PTR(rc); } Commit Message: Ecryptfs: Add mount option to check uid of device being mounted = expect uid Close a TOCTOU race for mounts done via ecryptfs-mount-private. The mount source (device) can be raced when the ownership test is done in userspace. Provide Ecryptfs a means to force the uid check at mount time. Signed-off-by: John Johansen <[email protected]> Cc: <[email protected]> Signed-off-by: Tyler Hicks <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: virtual status_t getSecureStop(Vector<uint8_t> const &ssid, Vector<uint8_t> &secureStop) { Parcel data, reply; data.writeInterfaceToken(IDrm::getInterfaceDescriptor()); writeVector(data, ssid); status_t status = remote()->transact(GET_SECURE_STOP, data, &reply); if (status != OK) { return status; } readVector(reply, secureStop); return reply.readInt32(); } Commit Message: Fix info leak vulnerability of IDrm bug: 26323455 Change-Id: I25bb30d3666ab38d5150496375ed2f55ecb23ba8 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: WebNotificationData createWebNotificationData(ExecutionContext* executionContext, const String& title, const NotificationOptions& options, ExceptionState& exceptionState) { if (options.hasVibrate() && options.silent()) { exceptionState.throwTypeError("Silent notifications must not specify vibration patterns."); return WebNotificationData(); } WebNotificationData webData; webData.title = title; webData.direction = toDirectionEnumValue(options.dir()); webData.lang = options.lang(); webData.body = options.body(); webData.tag = options.tag(); KURL iconUrl; iconUrl = executionContext->completeURL(options.icon()); if (!iconUrl.isValid()) iconUrl = KURL(); } webData.icon = iconUrl; webData.vibrate = NavigatorVibration::sanitizeVibrationPattern(options.vibrate()); webData.timestamp = options.hasTimestamp() ? static_cast<double>(options.timestamp()) : WTF::currentTimeMS(); webData.silent = options.silent(); webData.requireInteraction = options.requireInteraction(); if (options.hasData()) { RefPtr<SerializedScriptValue> serializedScriptValue = SerializedScriptValueFactory::instance().create(options.data().isolate(), options.data(), nullptr, exceptionState); if (exceptionState.hadException()) return WebNotificationData(); Vector<char> serializedData; serializedScriptValue->toWireBytes(serializedData); webData.data = serializedData; } Vector<WebNotificationAction> actions; const size_t maxActions = Notification::maxActions(); for (const NotificationAction& action : options.actions()) { if (actions.size() >= maxActions) break; WebNotificationAction webAction; webAction.action = action.action(); webAction.title = action.title(); actions.append(webAction); } webData.actions = actions; return webData; } Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649} 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: DailyDataSavingUpdate( const char* pref_original, const char* pref_received, PrefService* pref_service) : pref_original_(pref_original), pref_received_(pref_received), original_update_(pref_service, pref_original_), received_update_(pref_service, pref_received_) { } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Target: 1 Example 2: Code: static void f_midi_disable(struct usb_function *f) { struct f_midi *midi = func_to_midi(f); struct usb_composite_dev *cdev = f->config->cdev; struct usb_request *req = NULL; DBG(cdev, "disable\n"); /* * just disable endpoints, forcing completion of pending i/o. * all our completion handlers free their requests in this case. */ usb_ep_disable(midi->in_ep); usb_ep_disable(midi->out_ep); /* release IN requests */ while (kfifo_get(&midi->in_req_fifo, &req)) free_ep_req(midi->in_ep, req); f_midi_drop_out_substreams(midi); } Commit Message: USB: gadget: f_midi: fixing a possible double-free in f_midi It looks like there is a possibility of a double-free vulnerability on an error path of the f_midi_set_alt function in the f_midi driver. If the path is feasible then free_ep_req gets called twice: req->complete = f_midi_complete; err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC); => ... usb_gadget_giveback_request => f_midi_complete (CALLBACK) (inside f_midi_complete, for various cases of status) free_ep_req(ep, req); // first kfree if (err) { ERROR(midi, "%s: couldn't enqueue request: %d\n", midi->out_ep->name, err); free_ep_req(midi->out_ep, req); // second kfree return err; } The double-free possibility was introduced with commit ad0d1a058eac ("usb: gadget: f_midi: fix leak on failed to enqueue out requests"). Found by MOXCAFE tool. Signed-off-by: Tuba Yavuz <[email protected]> Fixes: ad0d1a058eac ("usb: gadget: f_midi: fix leak on failed to enqueue out requests") Acked-by: Felipe Balbi <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-415 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: xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int cur, l; xmlChar stop; int state = ctxt->instate; int count = 0; SHRINK; if (RAW == '"') { NEXT; stop = '"'; } else if (RAW == '\'') { NEXT; stop = '\''; } else { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } ctxt->instate = XML_PARSER_SYSTEM_LITERAL; cur = CUR_CHAR(l); while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */ if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlFree(buf); xmlErrMemory(ctxt, NULL); ctxt->instate = (xmlParserInputState) state; return(NULL); } buf = tmp; } count++; if (count > 50) { GROW; count = 0; } COPY_BUF(l,buf,len,cur); NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { GROW; SHRINK; cur = CUR_CHAR(l); } } buf[len] = 0; ctxt->instate = (xmlParserInputState) state; if (!IS_CHAR(cur)) { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL); } else { NEXT; } return(buf); } 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 int userfaultfd_release(struct inode *inode, struct file *file) { struct userfaultfd_ctx *ctx = file->private_data; struct mm_struct *mm = ctx->mm; struct vm_area_struct *vma, *prev; /* len == 0 means wake all */ struct userfaultfd_wake_range range = { .len = 0, }; unsigned long new_flags; WRITE_ONCE(ctx->released, true); if (!mmget_not_zero(mm)) goto wakeup; /* * Flush page faults out of all CPUs. NOTE: all page faults * must be retried without returning VM_FAULT_SIGBUS if * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx * changes while handle_userfault released the mmap_sem. So * it's critical that released is set to true (above), before * taking the mmap_sem for writing. */ down_write(&mm->mmap_sem); prev = NULL; for (vma = mm->mmap; vma; vma = vma->vm_next) { cond_resched(); BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^ !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); if (vma->vm_userfaultfd_ctx.ctx != ctx) { prev = vma; continue; } new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP); prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end, new_flags, vma->anon_vma, vma->vm_file, vma->vm_pgoff, vma_policy(vma), NULL_VM_UFFD_CTX); if (prev) vma = prev; else prev = vma; vma->vm_flags = new_flags; vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; } up_write(&mm->mmap_sem); mmput(mm); wakeup: /* * After no new page faults can wait on this fault_*wqh, flush * the last page faults that may have been already waiting on * the fault_*wqh. */ spin_lock(&ctx->fault_pending_wqh.lock); __wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range); __wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range); spin_unlock(&ctx->fault_pending_wqh.lock); /* Flush pending events that may still wait on event_wqh */ wake_up_all(&ctx->event_wqh); wake_up_poll(&ctx->fd_wqh, EPOLLHUP); userfaultfd_ctx_put(ctx); return 0; } Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/[email protected] "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/[email protected] Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Jann Horn <[email protected]> Suggested-by: Oleg Nesterov <[email protected]> Acked-by: Peter Xu <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Reviewed-by: Jann Horn <[email protected]> Acked-by: Jason Gunthorpe <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct timespec end_time; if (timeout && poll_select_set_timeout(&end_time, timeout->tv_sec, timeout->tv_nsec)) return -EINVAL; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; err = sock_error(sock->sk); if (err) goto out_put; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; while (datagrams < vlen) { /* * No need to ask LSM for more than the first datagram. */ if (MSG_CMSG_COMPAT & flags) { err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = ___sys_recvmsg(sock, (struct user_msghdr __user *)entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */ if (flags & MSG_WAITFORONE) flags |= MSG_DONTWAIT; if (timeout) { ktime_get_ts(timeout); *timeout = timespec_sub(end_time, *timeout); if (timeout->tv_sec < 0) { timeout->tv_sec = timeout->tv_nsec = 0; break; } /* Timeout, return less than vlen datagrams */ if (timeout->tv_nsec == 0 && timeout->tv_sec == 0) break; } /* Out of band data, return right away */ if (msg_sys.msg_flags & MSG_OOB) break; } out_put: fput_light(sock->file, fput_needed); if (err == 0) return datagrams; if (datagrams != 0) { /* * We may return less entries than requested (vlen) if the * sock is non block and there aren't enough datagrams... */ if (err != -EAGAIN) { /* * ... or if recvmsg returns an error after we * received some datagrams, where we record the * error to return on the next call or if the * app asks about it using getsockopt(SO_ERROR). */ sock->sk->sk_err = -err; } return datagrams; } return err; } Commit Message: net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom Cc: [email protected] # v3.19 Signed-off-by: Al Viro <[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: static void reds_handle_ticket(void *opaque) { RedLinkInfo *link = (RedLinkInfo *)opaque; char password[SPICE_MAX_PASSWORD_LENGTH]; time_t ltime; time(&ltime); RSA_private_decrypt(link->tiTicketing.rsa_size, link->tiTicketing.encrypted_ticket.encrypted_data, (unsigned char *)password, link->tiTicketing.rsa, RSA_PKCS1_OAEP_PADDING); if (ticketing_enabled && !link->skip_auth) { int expired = taTicket.expiration_time < ltime; if (strlen(taTicket.password) == 0) { reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); spice_warning("Ticketing is enabled, but no password is set. " "please set a ticket first"); reds_link_free(link); return; } if (expired || strncmp(password, taTicket.password, SPICE_MAX_PASSWORD_LENGTH) != 0) { if (expired) { spice_warning("Ticket has expired"); } else { spice_warning("Invalid password"); } reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); reds_link_free(link); return; } } reds_handle_link(link); } 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 ScreenPositionController::ConvertHostPointToRelativeToRootWindow( aura::Window* root_window, const aura::Window::Windows& root_windows, gfx::Point* point, aura::Window** target_root) { DCHECK(!root_window->parent()); gfx::Point point_in_root(*point); root_window->GetHost()->ConvertPointFromHost(&point_in_root); *target_root = root_window; *point = point_in_root; #if defined(USE_X11) || defined(USE_OZONE) if (!root_window->GetHost()->GetBounds().Contains(*point)) { gfx::Point location_in_native(point_in_root); root_window->GetHost()->ConvertPointToNativeScreen(&location_in_native); for (size_t i = 0; i < root_windows.size(); ++i) { aura::WindowTreeHost* host = root_windows[i]->GetHost(); const gfx::Rect native_bounds = host->GetBounds(); if (native_bounds.Contains(location_in_native)) { *target_root = root_windows[i]; *point = location_in_native; host->ConvertPointFromNativeScreen(point); break; } } } #else NOTIMPLEMENTED(); #endif } Commit Message: Use the host coordinate when comparing to host window bounds. I somehow overlooked this and the test was not strict enough to catch this. BUG=521919 TEST=Updated ScreenPositionControllerTest.ConvertHostPointToScreenHiDPI so that it fails without the patch. Review URL: https://codereview.chromium.org/1293373002 Cr-Commit-Position: refs/heads/master@{#344186} CWE ID: CWE-399 Target: 1 Example 2: Code: int part_get_info_by_name(struct blk_desc *dev_desc, const char *name, disk_partition_t *info) { return part_get_info_by_name_type(dev_desc, name, info, PART_TYPE_ALL); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes 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: parse_fond( char* fond_data, short* have_sfnt, ResID* sfnt_id, Str255 lwfn_file_name, short face_index ) { AsscEntry* assoc; AsscEntry* base_assoc; FamRec* fond; *sfnt_id = 0; *have_sfnt = 0; lwfn_file_name[0] = 0; fond = (FamRec*)fond_data; assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 ); base_assoc = assoc; /* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */ if ( 47 < face_index ) return; /* Let's do a little range checking before we get too excited here */ if ( face_index < count_faces_sfnt( fond_data ) ) { assoc += face_index; /* add on the face_index! */ /* if the face at this index is not scalable, fall back to the first one (old behavior) */ if ( EndianS16_BtoN( assoc->fontSize ) == 0 ) { *have_sfnt = 1; *sfnt_id = EndianS16_BtoN( assoc->fontID ); } else if ( base_assoc->fontSize == 0 ) { *have_sfnt = 1; *sfnt_id = EndianS16_BtoN( base_assoc->fontID ); } } if ( EndianS32_BtoN( fond->ffStylOff ) ) { unsigned char* p = (unsigned char*)fond_data; StyleTable* style; unsigned short string_count; char ps_name[256]; unsigned char* names[64]; int i; p += EndianS32_BtoN( fond->ffStylOff ); style = (StyleTable*)p; p += sizeof ( StyleTable ); string_count = EndianS16_BtoN( *(short*)(p) ); p += sizeof ( short ); for ( i = 0; i < string_count && i < 64; i++ ) { names[i] = p; p += names[i][0]; } { size_t ps_name_len = (size_t)names[0][0]; if ( ps_name_len != 0 ) { ft_memcpy(ps_name, names[0] + 1, ps_name_len); ps_name[ps_name_len] = 0; ps_name[ps_name_len] = 0; } if ( style->indexes[face_index] > 1 && style->indexes[face_index] <= FT_MIN( string_count, 64 ) ) { unsigned char* suffixes = names[style->indexes[face_index] - 1]; for ( i = 1; i <= suffixes[0]; i++ ) { unsigned char* s; size_t j = suffixes[i] - 1; if ( j < string_count && ( s = names[j] ) != NULL ) { size_t s_len = (size_t)s[0]; if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) ) { ft_memcpy( ps_name + ps_name_len, s + 1, s_len ); ps_name_len += s_len; ps_name[ps_name_len] = 0; } } } } } create_lwfn_name( ps_name, lwfn_file_name ); } } 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: static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobSignedLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,(double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (EOFBlob(image) != MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } Commit Message: Slightly different fix for #714 CWE ID: CWE-834 Target: 1 Example 2: Code: static void ipip6_tunnel_uninit(struct net_device *dev) { struct net *net = dev_net(dev); struct sit_net *sitn = net_generic(net, sit_net_id); if (dev == sitn->fb_tunnel_dev) { rcu_assign_pointer(sitn->tunnels_wc[0], NULL); } else { ipip6_tunnel_unlink(sitn, netdev_priv(dev)); ipip6_tunnel_del_prl(netdev_priv(dev), NULL); } dev_put(dev); } 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: 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 get_time_list(char *arg, u32 *times, u32 *nb_times) { char *str; Float var; Double sec; u32 h, m, s, ms, f, fps; if (!arg || (arg[0]=='-') || !isdigit(arg[0])) return 0; /*SMPTE time code*/ if (strchr(arg, ':') && strchr(arg, ';') && strchr(arg, '/')) { if (sscanf(arg, "%02ud:%02ud:%02ud;%02ud/%02ud", &h, &m, &s, &f, &fps)==5) { sec = 0; if (fps) sec = ((Double)f) / fps; sec += 3600*h + 60*m + s; times[*nb_times] = (u32) (1000*sec); (*nb_times) ++; return 1; } } while (arg) { str = strchr(arg, '-'); if (str) str[0] = 0; /*HH:MM:SS:MS time code*/ if (strchr(arg, ':') && (sscanf(arg, "%u:%u:%u:%u", &h, &m, &s, &ms)==4)) { sec = ms; sec /= 1000; sec += 3600*h + 60*m + s; times[*nb_times] = (u32) (1000*sec); (*nb_times) ++; } else if (sscanf(arg, "%f", &var)==1) { sec = atof(arg); times[*nb_times] = (u32) (1000*sec); (*nb_times) ++; } if (!str) break; str[0] = '-'; arg = str+1; } return 1; } Commit Message: add some boundary checks on gf_text_get_utf8_line (#1188) 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: ScrollHitTestDisplayItem::ScrollHitTestDisplayItem( const DisplayItemClient& client, Type type, scoped_refptr<const TransformPaintPropertyNode> scroll_offset_node) : DisplayItem(client, type, sizeof(*this)), scroll_offset_node_(std::move(scroll_offset_node)) { DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled()); DCHECK(IsScrollHitTestType(type)); DCHECK(scroll_offset_node_->ScrollNode()); } 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: 1 Example 2: Code: void CharacterIterator::advance(int count) { if (count <= 0) { ASSERT(count == 0); return; } m_atBreak = false; int remaining = m_textIterator.length() - m_runOffset; if (count < remaining) { m_runOffset += count; m_offset += count; return; } count -= remaining; m_offset += remaining; for (m_textIterator.advance(); !atEnd(); m_textIterator.advance()) { int runLength = m_textIterator.length(); if (runLength == 0) m_atBreak = true; else { if (count < runLength) { m_runOffset = count; m_offset += count; return; } count -= runLength; m_offset += runLength; } } m_atBreak = true; m_runOffset = 0; } Commit Message: Upgrade a TextIterator ASSERT to a RELEASE_ASSERT as a defensive measure. BUG=156930,177197 [email protected] Review URL: https://codereview.chromium.org/15057010 git-svn-id: svn://svn.chromium.org/blink/trunk@150123 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int r_bin_dwarf_expand_debug_abbrev(RBinDwarfDebugAbbrev *da) { RBinDwarfAbbrevDecl *tmp; if (!da || da->capacity == 0 || da->capacity != da->length) { return -EINVAL; } tmp = (RBinDwarfAbbrevDecl*)realloc (da->decls, da->capacity * 2 * sizeof (RBinDwarfAbbrevDecl)); if (!tmp) { return -ENOMEM; } memset ((ut8*)tmp + da->capacity, 0, da->capacity); da->decls = tmp; da->capacity *= 2; return 0; } Commit Message: Fix #8813 - segfault in dwarf parser 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: ExtensionTtsController* ExtensionTtsController::GetInstance() { return Singleton<ExtensionTtsController>::get(); } 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 ShellSurface::Resize(int component) { TRACE_EVENT1("exo", "ShellSurface::Resize", "component", component); if (widget_ && !widget_->movement_disabled()) AttemptToStartDrag(component); } Commit Message: exo: Reduce side-effects of dynamic activation code. This code exists for clients that need to managed their own system modal dialogs. Since the addition of the remote surface API we can limit the impact of this to surfaces created for system modal container. BUG=29528396 Review-Url: https://codereview.chromium.org/2084023003 Cr-Commit-Position: refs/heads/master@{#401115} 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: node_get_pref_ipv6_dirport(const node_t *node, tor_addr_port_t *ap_out) { node_assert_ok(node); tor_assert(ap_out); /* Check ri first, because rewrite_node_address_for_bridge() updates * node->ri with the configured bridge address. * Prefer rs over md for consistency with the fascist_firewall_* functions. * Check if the address or port are valid, and try another alternative * if they are not. */ /* Assume IPv4 and IPv6 dirports are the same */ if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr, node->ri->dir_port, 0)) { tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr); ap_out->port = node->ri->dir_port; } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr, node->rs->dir_port, 0)) { tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr); ap_out->port = node->rs->dir_port; } else { tor_addr_make_null(&ap_out->addr, AF_INET6); ap_out->port = 0; } } Commit Message: Consider the exit family when applying guard restrictions. When the new path selection logic went into place, I accidentally dropped the code that considered the _family_ of the exit node when deciding if the guard was usable, and we didn't catch that during code review. This patch makes the guard_restriction_t code consider the exit family as well, and adds some (hopefully redundant) checks for the case where we lack a node_t for a guard but we have a bridge_info_t for it. Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006 and CVE-2017-0377. 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: LazyBackgroundPageNativeHandler::LazyBackgroundPageNativeHandler( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "IncrementKeepaliveCount", base::Bind(&LazyBackgroundPageNativeHandler::IncrementKeepaliveCount, base::Unretained(this))); RouteFunction( "DecrementKeepaliveCount", base::Bind(&LazyBackgroundPageNativeHandler::DecrementKeepaliveCount, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284 Target: 1 Example 2: Code: static void ahci_reg_init(AHCIState *s) { int i; s->control_regs.cap = (s->ports - 1) | (AHCI_NUM_COMMAND_SLOTS << 8) | (AHCI_SUPPORTED_SPEED_GEN1 << AHCI_SUPPORTED_SPEED) | HOST_CAP_NCQ | HOST_CAP_AHCI; s->control_regs.impl = (1 << s->ports) - 1; s->control_regs.version = AHCI_VERSION_1_0; for (i = 0; i < s->ports; i++) { s->dev[i].port_state = STATE_RUN; } } 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: static boolean FillInputBuffer(j_decompress_ptr cinfo) { SourceManager *source; source=(SourceManager *) cinfo->src; source->manager.bytes_in_buffer=(size_t) ReadBlob(source->image, MagickMinBufferExtent,source->buffer); if (source->manager.bytes_in_buffer == 0) { if (source->start_of_blob != FALSE) ERREXIT(cinfo,JERR_INPUT_EMPTY); WARNMS(cinfo,JWRN_JPEG_EOF); source->buffer[0]=(JOCTET) 0xff; source->buffer[1]=(JOCTET) JPEG_EOI; source->manager.bytes_in_buffer=2; } source->manager.next_input_byte=source->buffer; source->start_of_blob=FALSE; return(TRUE); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1641 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: xsltChoose(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, xmlNodePtr inst, xsltStylePreCompPtr comp ATTRIBUTE_UNUSED) { xmlNodePtr cur; if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL)) return; /* * TODO: Content model checks should be done only at compilation * time. */ cur = inst->children; if (cur == NULL) { xsltTransformError(ctxt, NULL, inst, "xsl:choose: The instruction has no content.\n"); return; } #ifdef XSLT_REFACTORED /* * We don't check the content model during transformation. */ #else if ((! IS_XSLT_ELEM(cur)) || (! IS_XSLT_NAME(cur, "when"))) { xsltTransformError(ctxt, NULL, inst, "xsl:choose: xsl:when expected first\n"); return; } #endif { int testRes = 0, res = 0; xmlXPathContextPtr xpctxt = ctxt->xpathCtxt; xmlDocPtr oldXPContextDoc = xpctxt->doc; int oldXPProximityPosition = xpctxt->proximityPosition; int oldXPContextSize = xpctxt->contextSize; xmlNsPtr *oldXPNamespaces = xpctxt->namespaces; int oldXPNsNr = xpctxt->nsNr; #ifdef XSLT_REFACTORED xsltStyleItemWhenPtr wcomp = NULL; #else xsltStylePreCompPtr wcomp = NULL; #endif /* * Process xsl:when --------------------------------------------------- */ while (IS_XSLT_ELEM(cur) && IS_XSLT_NAME(cur, "when")) { wcomp = cur->psvi; if ((wcomp == NULL) || (wcomp->test == NULL) || (wcomp->comp == NULL)) { xsltTransformError(ctxt, NULL, cur, "Internal error in xsltChoose(): " "The XSLT 'when' instruction was not compiled.\n"); goto error; } #ifdef WITH_DEBUGGER if (xslDebugStatus != XSLT_DEBUG_NONE) { /* * TODO: Isn't comp->templ always NULL for xsl:choose? */ xslHandleDebugger(cur, contextNode, NULL, ctxt); } #endif #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext, "xsltChoose: test %s\n", wcomp->test)); #endif xpctxt->node = contextNode; xpctxt->doc = oldXPContextDoc; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->contextSize = oldXPContextSize; #ifdef XSLT_REFACTORED if (wcomp->inScopeNs != NULL) { xpctxt->namespaces = wcomp->inScopeNs->list; xpctxt->nsNr = wcomp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = wcomp->nsList; xpctxt->nsNr = wcomp->nsNr; #endif #ifdef XSLT_FAST_IF res = xmlXPathCompiledEvalToBoolean(wcomp->comp, xpctxt); if (res == -1) { ctxt->state = XSLT_STATE_STOPPED; goto error; } testRes = (res == 1) ? 1 : 0; #else /* XSLT_FAST_IF */ res = xmlXPathCompiledEval(wcomp->comp, xpctxt); if (res != NULL) { if (res->type != XPATH_BOOLEAN) res = xmlXPathConvertBoolean(res); if (res->type == XPATH_BOOLEAN) testRes = res->boolval; else { #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext, "xsltChoose: test didn't evaluate to a boolean\n")); #endif goto error; } xmlXPathFreeObject(res); res = NULL; } else { ctxt->state = XSLT_STATE_STOPPED; goto error; } #endif /* else of XSLT_FAST_IF */ #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext, "xsltChoose: test evaluate to %d\n", testRes)); #endif if (testRes) goto test_is_true; cur = cur->next; } /* * Process xsl:otherwise ---------------------------------------------- */ if (IS_XSLT_ELEM(cur) && IS_XSLT_NAME(cur, "otherwise")) { #ifdef WITH_DEBUGGER if (xslDebugStatus != XSLT_DEBUG_NONE) xslHandleDebugger(cur, contextNode, NULL, ctxt); #endif #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext, "evaluating xsl:otherwise\n")); #endif goto test_is_true; } xpctxt->node = contextNode; xpctxt->doc = oldXPContextDoc; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->contextSize = oldXPContextSize; xpctxt->namespaces = oldXPNamespaces; xpctxt->nsNr = oldXPNsNr; goto exit; test_is_true: xpctxt->node = contextNode; xpctxt->doc = oldXPContextDoc; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->contextSize = oldXPContextSize; xpctxt->namespaces = oldXPNamespaces; xpctxt->nsNr = oldXPNsNr; goto process_sequence; } process_sequence: /* * Instantiate the sequence constructor. */ xsltApplySequenceConstructor(ctxt, ctxt->node, cur->children, NULL); exit: error: return; } 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 rds_send_remove_from_sock(struct list_head *messages, int status) { unsigned long flags; struct rds_sock *rs = NULL; struct rds_message *rm; while (!list_empty(messages)) { int was_on_sock = 0; rm = list_entry(messages->next, struct rds_message, m_conn_item); list_del_init(&rm->m_conn_item); /* * If we see this flag cleared then we're *sure* that someone * else beat us to removing it from the sock. If we race * with their flag update we'll get the lock and then really * see that the flag has been cleared. * * The message spinlock makes sure nobody clears rm->m_rs * while we're messing with it. It does not prevent the * message from being removed from the socket, though. */ spin_lock_irqsave(&rm->m_rs_lock, flags); if (!test_bit(RDS_MSG_ON_SOCK, &rm->m_flags)) goto unlock_and_drop; if (rs != rm->m_rs) { if (rs) { rds_wake_sk_sleep(rs); sock_put(rds_rs_to_sk(rs)); } rs = rm->m_rs; if (rs) sock_hold(rds_rs_to_sk(rs)); } if (!rs) goto unlock_and_drop; spin_lock(&rs->rs_lock); if (test_and_clear_bit(RDS_MSG_ON_SOCK, &rm->m_flags)) { struct rm_rdma_op *ro = &rm->rdma; struct rds_notifier *notifier; list_del_init(&rm->m_sock_item); rds_send_sndbuf_remove(rs, rm); if (ro->op_active && ro->op_notifier && (ro->op_notify || (ro->op_recverr && status))) { notifier = ro->op_notifier; list_add_tail(&notifier->n_list, &rs->rs_notify_queue); if (!notifier->n_status) notifier->n_status = status; rm->rdma.op_notifier = NULL; } was_on_sock = 1; rm->m_rs = NULL; } spin_unlock(&rs->rs_lock); unlock_and_drop: spin_unlock_irqrestore(&rm->m_rs_lock, flags); rds_message_put(rm); if (was_on_sock) rds_message_put(rm); } if (rs) { rds_wake_sk_sleep(rs); sock_put(rds_rs_to_sk(rs)); } } Commit Message: RDS: fix race condition when sending a message on unbound socket Sasha's found a NULL pointer dereference in the RDS connection code when sending a message to an apparently unbound socket. The problem is caused by the code checking if the socket is bound in rds_sendmsg(), which checks the rs_bound_addr field without taking a lock on the socket. This opens a race where rs_bound_addr is temporarily set but where the transport is not in rds_bind(), leading to a NULL pointer dereference when trying to dereference 'trans' in __rds_conn_create(). Vegard wrote a reproducer for this issue, so kindly ask him to share if you're interested. I cannot reproduce the NULL pointer dereference using Vegard's reproducer with this patch, whereas I could without. Complete earlier incomplete fix to CVE-2015-6937: 74e98eb08588 ("RDS: verify the underlying transport exists before creating a connection") Cc: David S. Miller <[email protected]> Cc: [email protected] Reviewed-by: Vegard Nossum <[email protected]> Reviewed-by: Sasha Levin <[email protected]> Acked-by: Santosh Shilimkar <[email protected]> Signed-off-by: Quentin Casasnovas <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: parsefh(netdissect_options *ndo, register const uint32_t *dp, int v3) { u_int len; if (v3) { ND_TCHECK(dp[0]); len = EXTRACT_32BITS(dp) / 4; dp++; } else len = NFSX_V2FH / 4; if (ND_TTEST2(*dp, len * sizeof(*dp))) { nfs_printfh(ndo, dp, len); return (dp + len); } trunc: return (NULL); } 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:
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 OutOfProcessInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { pp::Var document_url_var = pp::URLUtil_Dev::Get()->GetDocumentURL(this); std::string document_url = document_url_var.is_string() ? document_url_var.AsString() : std::string(); std::string extension_url = std::string(kChromeExtension); bool in_extension = !document_url.compare(0, extension_url.size(), extension_url); if (in_extension) { for (uint32_t i = 0; i < argc; ++i) { if (strcmp(argn[i], "full-frame") == 0) { full_ = true; break; } } } if (full_) SetPluginToHandleFindRequests(); pp::VarDictionary translated_strings; translated_strings.Set(kType, kJSSetTranslatedStringsType); translated_strings.Set(kJSGetPasswordString, GetLocalizedString(PP_RESOURCESTRING_PDFGETPASSWORD)); translated_strings.Set(kJSLoadingString, GetLocalizedString(PP_RESOURCESTRING_PDFLOADING)); translated_strings.Set(kJSLoadFailedString, GetLocalizedString(PP_RESOURCESTRING_PDFLOAD_FAILED)); PostMessage(translated_strings); text_input_.reset(new pp::TextInput_Dev(this)); const char* stream_url = nullptr; const char* original_url = nullptr; const char* headers = nullptr; bool is_material = false; for (uint32_t i = 0; i < argc; ++i) { if (strcmp(argn[i], "src") == 0) original_url = argv[i]; else if (strcmp(argn[i], "stream-url") == 0) stream_url = argv[i]; else if (strcmp(argn[i], "headers") == 0) headers = argv[i]; else if (strcmp(argn[i], "is-material") == 0) is_material = true; else if (strcmp(argn[i], "top-toolbar-height") == 0) base::StringToInt(argv[i], &top_toolbar_height_); } if (is_material) background_color_ = kBackgroundColorMaterial; else background_color_ = kBackgroundColor; if (!original_url) return false; if (!stream_url) stream_url = original_url; if (IsPrintPreviewUrl(original_url)) return true; LoadUrl(stream_url); url_ = original_url; return engine_->New(original_url, headers); } Commit Message: Prevent leaking PDF data cross-origin BUG=520422 Review URL: https://codereview.chromium.org/1311973002 Cr-Commit-Position: refs/heads/master@{#345267} CWE ID: CWE-20 Target: 1 Example 2: Code: void RenderWidgetHostImpl::OnMessageDispatchError(const IPC::Message& message) { RenderProcessHost* rph = GetProcess(); rph->OnBadMessageReceived(message); } Commit Message: Start rendering timer after first navigation Currently the new content rendering timer in the browser process, which clears an old page's contents 4 seconds after a navigation if the new page doesn't draw in that time, is not set on the first navigation for a top-level frame. This is problematic because content can exist before the first navigation, for instance if it was created by a javascript: URL. This CL removes the code that skips the timer activation on the first navigation. Bug: 844881 Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584 Reviewed-on: https://chromium-review.googlesource.com/1188589 Reviewed-by: Fady Samuel <[email protected]> Reviewed-by: ccameron <[email protected]> Commit-Queue: Ken Buchanan <[email protected]> Cr-Commit-Position: refs/heads/master@{#586913} 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 inet_sk_reselect_saddr(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); __be32 old_saddr = inet->inet_saddr; __be32 daddr = inet->inet_daddr; struct flowi4 fl4; struct rtable *rt; __be32 new_saddr; if (inet->opt && inet->opt->srr) daddr = inet->opt->faddr; /* Query new route. */ rt = ip_route_connect(&fl4, daddr, 0, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if, sk->sk_protocol, inet->inet_sport, inet->inet_dport, sk, false); if (IS_ERR(rt)) return PTR_ERR(rt); sk_setup_caps(sk, &rt->dst); new_saddr = rt->rt_src; if (new_saddr == old_saddr) return 0; if (sysctl_ip_dynaddr > 1) { printk(KERN_INFO "%s(): shifting inet->saddr from %pI4 to %pI4\n", __func__, &old_saddr, &new_saddr); } inet->inet_saddr = inet->inet_rcv_saddr = new_saddr; /* * XXX The only one ugly spot where we need to * XXX really change the sockets identity after * XXX it has entered the hashes. -DaveM * * Besides that, it does not check for connection * uniqueness. Wait for troubles. */ __sk_prot_rehash(sk); return 0; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static unsigned int ipv6_defrag(void *priv, struct sk_buff *skb, const struct nf_hook_state *state) { int err; #if IS_ENABLED(CONFIG_NF_CONNTRACK) /* Previously seen (loopback)? */ if (skb->nfct && !nf_ct_is_template((struct nf_conn *)skb->nfct)) return NF_ACCEPT; #endif err = nf_ct_frag6_gather(state->net, skb, nf_ct6_defrag_user(state->hook, skb)); /* queued */ if (err == -EINPROGRESS) return NF_STOLEN; return NF_ACCEPT; } Commit Message: netfilter: ipv6: nf_defrag: drop mangled skb on ream error Dmitry Vyukov reported GPF in network stack that Andrey traced down to negative nh offset in nf_ct_frag6_queue(). Problem is that all network headers before fragment header are pulled. Normal ipv6 reassembly will drop the skb when errors occur further down the line. netfilter doesn't do this, and instead passed the original fragment along. That was also fine back when netfilter ipv6 defrag worked with cloned fragments, as the original, pristine fragment was passed on. So we either have to undo the pull op, or discard such fragments. Since they're malformed after all (e.g. overlapping fragment) it seems preferrable to just drop them. Same for temporary errors -- it doesn't make sense to accept (and perhaps forward!) only some fragments of same datagram. Fixes: 029f7f3b8701cc7ac ("netfilter: ipv6: nf_defrag: avoid/free clone operations") Reported-by: Dmitry Vyukov <[email protected]> Debugged-by: Andrey Konovalov <[email protected]> Diagnosed-by: Eric Dumazet <Eric Dumazet <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-787 Target: 1 Example 2: Code: void CWebServer::Cmd_UpdateDevice(WebEmSession & session, const request& req, Json::Value &root) { if (session.rights < 1) { session.reply_status = reply::forbidden; return; //only user or higher allowed } std::string idx = request::findValue(&req, "idx"); if (!IsIdxForUser(&session, atoi(idx.c_str()))) { _log.Log(LOG_ERROR, "User: %s tried to update an Unauthorized device!", session.username.c_str()); session.reply_status = reply::forbidden; return; } std::string hid = request::findValue(&req, "hid"); std::string did = request::findValue(&req, "did"); std::string dunit = request::findValue(&req, "dunit"); std::string dtype = request::findValue(&req, "dtype"); std::string dsubtype = request::findValue(&req, "dsubtype"); std::string nvalue = request::findValue(&req, "nvalue"); std::string svalue = request::findValue(&req, "svalue"); if ((nvalue.empty() && svalue.empty())) { return; } int signallevel = 12; int batterylevel = 255; if (idx.empty()) { if ( (hid.empty()) || (did.empty()) || (dunit.empty()) || (dtype.empty()) || (dsubtype.empty()) ) return; } else { std::vector<std::vector<std::string> > result; result = m_sql.safe_query("SELECT HardwareID, DeviceID, Unit, Type, SubType FROM DeviceStatus WHERE (ID=='%q')", idx.c_str()); if (result.empty()) return; hid = result[0][0]; did = result[0][1]; dunit = result[0][2]; dtype = result[0][3]; dsubtype = result[0][4]; } int HardwareID = atoi(hid.c_str()); std::string DeviceID = did; int unit = atoi(dunit.c_str()); int devType = atoi(dtype.c_str()); int subType = atoi(dsubtype.c_str()); uint64_t ulIdx = std::strtoull(idx.c_str(), nullptr, 10); int invalue = atoi(nvalue.c_str()); std::string sSignalLevel = request::findValue(&req, "rssi"); if (sSignalLevel != "") { signallevel = atoi(sSignalLevel.c_str()); } std::string sBatteryLevel = request::findValue(&req, "battery"); if (sBatteryLevel != "") { batterylevel = atoi(sBatteryLevel.c_str()); } if (m_mainworker.UpdateDevice(HardwareID, DeviceID, unit, devType, subType, invalue, svalue, signallevel, batterylevel)) { root["status"] = "OK"; root["title"] = "Update Device"; } } Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!) CWE ID: CWE-89 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_ret(struct x86_emulate_ctxt *ctxt) { ctxt->dst.type = OP_REG; ctxt->dst.addr.reg = &ctxt->_eip; ctxt->dst.bytes = ctxt->op_bytes; return em_pop(ctxt); } Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches Before changing rip (during jmp, call, ret, etc.) the target should be asserted to be canonical one, as real CPUs do. During sysret, both target rsp and rip should be canonical. If any of these values is noncanonical, a #GP exception should occur. The exception to this rule are syscall and sysenter instructions in which the assigned rip is checked during the assignment to the relevant MSRs. This patch fixes the emulator to behave as real CPUs do for near branches. Far branches are handled by the next patch. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264 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 skel(const char *homedir, uid_t u, gid_t g) { char *fname; if (!arg_shell_none && (strcmp(cfg.shell,"/usr/bin/zsh") == 0 || strcmp(cfg.shell,"/bin/zsh") == 0)) { if (asprintf(&fname, "%s/.zshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.zshrc", &s) == 0) { copy_file("/etc/skel/.zshrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.zshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else if (!arg_shell_none && strcmp(cfg.shell,"/bin/csh") == 0) { if (asprintf(&fname, "%s/.cshrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.cshrc", &s) == 0) { copy_file("/etc/skel/.cshrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.cshrc"); } else { touch_file_as_user(fname, u, g, 0644); fs_logger2("touch", fname); } free(fname); } else { if (asprintf(&fname, "%s/.bashrc", homedir) == -1) errExit("asprintf"); struct stat s; if (stat(fname, &s) == 0) return; if (stat("/etc/skel/.bashrc", &s) == 0) { copy_file("/etc/skel/.bashrc", fname, u, g, 0644); fs_logger("clone /etc/skel/.bashrc"); } free(fname); } } Commit Message: security fix CWE ID: CWE-269 Target: 1 Example 2: Code: JPEGImageDecoder::~JPEGImageDecoder() { } Commit Message: Progressive JPEG outputScanlines() calls should handle failure outputScanlines() can fail and delete |this|, so any attempt to access members thereafter should be avoided. Copy the decoder pointer member, and use that copy to detect and handle the failure case. BUG=232763 [email protected] Review URL: https://codereview.chromium.org/14844003 git-svn-id: svn://svn.chromium.org/blink/trunk@150545 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline UChar foldQuoteMarkOrSoftHyphen(UChar c) { switch (c) { case hebrewPunctuationGershayim: case leftDoubleQuotationMark: case rightDoubleQuotationMark: return '"'; case hebrewPunctuationGeresh: case leftSingleQuotationMark: case rightSingleQuotationMark: return '\''; case softHyphen: return 0; default: return c; } } Commit Message: Upgrade a TextIterator ASSERT to a RELEASE_ASSERT as a defensive measure. BUG=156930,177197 [email protected] Review URL: https://codereview.chromium.org/15057010 git-svn-id: svn://svn.chromium.org/blink/trunk@150123 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[3],b[3],c1,c2,c3); r[6]=c1; r[7]=c2; } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <[email protected]> CWE ID: CWE-310 Target: 1 Example 2: Code: int bt_sock_stream_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int err = 0; size_t target, copied = 0; long timeo; if (flags & MSG_OOB) return -EOPNOTSUPP; msg->msg_namelen = 0; BT_DBG("sk %p size %zu", sk, size); lock_sock(sk); target = sock_rcvlowat(sk, flags & MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); do { struct sk_buff *skb; int chunk; skb = skb_dequeue(&sk->sk_receive_queue); if (!skb) { if (copied >= target) break; err = sock_error(sk); if (err) break; if (sk->sk_shutdown & RCV_SHUTDOWN) break; err = -EAGAIN; if (!timeo) break; timeo = bt_sock_data_wait(sk, timeo); if (signal_pending(current)) { err = sock_intr_errno(timeo); goto out; } continue; } chunk = min_t(unsigned int, skb->len, size); if (skb_copy_datagram_iovec(skb, 0, msg->msg_iov, chunk)) { skb_queue_head(&sk->sk_receive_queue, skb); if (!copied) copied = -EFAULT; break; } copied += chunk; size -= chunk; sock_recv_ts_and_drops(msg, sk, skb); if (!(flags & MSG_PEEK)) { int skb_len = skb_headlen(skb); if (chunk <= skb_len) { __skb_pull(skb, chunk); } else { struct sk_buff *frag; __skb_pull(skb, skb_len); chunk -= skb_len; skb_walk_frags(skb, frag) { if (chunk <= frag->len) { /* Pulling partial data */ skb->len -= chunk; skb->data_len -= chunk; __skb_pull(frag, chunk); break; } else if (frag->len) { /* Pulling all frag data */ chunk -= frag->len; skb->len -= frag->len; skb->data_len -= frag->len; __skb_pull(frag, frag->len); } } } if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); break; } kfree_skb(skb); } else { /* put message back and return */ skb_queue_head(&sk->sk_receive_queue, skb); break; } } while (size); out: release_sock(sk); return copied ? : err; } Commit Message: Bluetooth: fix possible info leak in bt_sock_recvmsg() In case the socket is already shutting down, bt_sock_recvmsg() returns with 0 without updating msg_namelen leading to net/socket.c leaking the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix this by moving the msg_namelen assignment in front of the shutdown test. 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: long kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm *kvm = filp->private_data; void __user *argp = (void __user *)arg; int r = -ENOTTY; /* * This union makes it completely explicit to gcc-3.x * that these two variables' stack usage should be * combined, not added together. */ union { struct kvm_pit_state ps; struct kvm_pit_state2 ps2; struct kvm_pit_config pit_config; } u; switch (ioctl) { case KVM_SET_TSS_ADDR: r = kvm_vm_ioctl_set_tss_addr(kvm, arg); if (r < 0) goto out; break; case KVM_SET_IDENTITY_MAP_ADDR: { u64 ident_addr; r = -EFAULT; if (copy_from_user(&ident_addr, argp, sizeof ident_addr)) goto out; r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr); if (r < 0) goto out; break; } case KVM_SET_NR_MMU_PAGES: r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg); if (r) goto out; break; case KVM_GET_NR_MMU_PAGES: r = kvm_vm_ioctl_get_nr_mmu_pages(kvm); break; case KVM_CREATE_IRQCHIP: { struct kvm_pic *vpic; mutex_lock(&kvm->lock); r = -EEXIST; if (kvm->arch.vpic) goto create_irqchip_unlock; r = -ENOMEM; vpic = kvm_create_pic(kvm); if (vpic) { r = kvm_ioapic_init(kvm); if (r) { mutex_lock(&kvm->slots_lock); kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &vpic->dev_master); kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &vpic->dev_slave); kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &vpic->dev_eclr); mutex_unlock(&kvm->slots_lock); kfree(vpic); goto create_irqchip_unlock; } } else goto create_irqchip_unlock; smp_wmb(); kvm->arch.vpic = vpic; smp_wmb(); r = kvm_setup_default_irq_routing(kvm); if (r) { mutex_lock(&kvm->slots_lock); mutex_lock(&kvm->irq_lock); kvm_ioapic_destroy(kvm); kvm_destroy_pic(kvm); mutex_unlock(&kvm->irq_lock); mutex_unlock(&kvm->slots_lock); } create_irqchip_unlock: mutex_unlock(&kvm->lock); break; } case KVM_CREATE_PIT: u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY; goto create_pit; case KVM_CREATE_PIT2: r = -EFAULT; if (copy_from_user(&u.pit_config, argp, sizeof(struct kvm_pit_config))) goto out; create_pit: mutex_lock(&kvm->slots_lock); r = -EEXIST; if (kvm->arch.vpit) goto create_pit_unlock; r = -ENOMEM; kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags); if (kvm->arch.vpit) r = 0; create_pit_unlock: mutex_unlock(&kvm->slots_lock); break; case KVM_IRQ_LINE_STATUS: case KVM_IRQ_LINE: { struct kvm_irq_level irq_event; r = -EFAULT; if (copy_from_user(&irq_event, argp, sizeof irq_event)) goto out; r = -ENXIO; if (irqchip_in_kernel(kvm)) { __s32 status; status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID, irq_event.irq, irq_event.level); if (ioctl == KVM_IRQ_LINE_STATUS) { r = -EFAULT; irq_event.status = status; if (copy_to_user(argp, &irq_event, sizeof irq_event)) goto out; } r = 0; } break; } case KVM_GET_IRQCHIP: { /* 0: PIC master, 1: PIC slave, 2: IOAPIC */ struct kvm_irqchip *chip; chip = memdup_user(argp, sizeof(*chip)); if (IS_ERR(chip)) { r = PTR_ERR(chip); goto out; } r = -ENXIO; if (!irqchip_in_kernel(kvm)) goto get_irqchip_out; r = kvm_vm_ioctl_get_irqchip(kvm, chip); if (r) goto get_irqchip_out; r = -EFAULT; if (copy_to_user(argp, chip, sizeof *chip)) goto get_irqchip_out; r = 0; get_irqchip_out: kfree(chip); if (r) goto out; break; } case KVM_SET_IRQCHIP: { /* 0: PIC master, 1: PIC slave, 2: IOAPIC */ struct kvm_irqchip *chip; chip = memdup_user(argp, sizeof(*chip)); if (IS_ERR(chip)) { r = PTR_ERR(chip); goto out; } r = -ENXIO; if (!irqchip_in_kernel(kvm)) goto set_irqchip_out; r = kvm_vm_ioctl_set_irqchip(kvm, chip); if (r) goto set_irqchip_out; r = 0; set_irqchip_out: kfree(chip); if (r) goto out; break; } case KVM_GET_PIT: { r = -EFAULT; if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state))) goto out; r = -ENXIO; if (!kvm->arch.vpit) goto out; r = kvm_vm_ioctl_get_pit(kvm, &u.ps); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state))) goto out; r = 0; break; } case KVM_SET_PIT: { r = -EFAULT; if (copy_from_user(&u.ps, argp, sizeof u.ps)) goto out; r = -ENXIO; if (!kvm->arch.vpit) goto out; r = kvm_vm_ioctl_set_pit(kvm, &u.ps); if (r) goto out; r = 0; break; } case KVM_GET_PIT2: { r = -ENXIO; if (!kvm->arch.vpit) goto out; r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &u.ps2, sizeof(u.ps2))) goto out; r = 0; break; } case KVM_SET_PIT2: { r = -EFAULT; if (copy_from_user(&u.ps2, argp, sizeof(u.ps2))) goto out; r = -ENXIO; if (!kvm->arch.vpit) goto out; r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2); if (r) goto out; r = 0; break; } case KVM_REINJECT_CONTROL: { struct kvm_reinject_control control; r = -EFAULT; if (copy_from_user(&control, argp, sizeof(control))) goto out; r = kvm_vm_ioctl_reinject(kvm, &control); if (r) goto out; r = 0; break; } case KVM_XEN_HVM_CONFIG: { r = -EFAULT; if (copy_from_user(&kvm->arch.xen_hvm_config, argp, sizeof(struct kvm_xen_hvm_config))) goto out; r = -EINVAL; if (kvm->arch.xen_hvm_config.flags) goto out; r = 0; break; } case KVM_SET_CLOCK: { struct kvm_clock_data user_ns; u64 now_ns; s64 delta; r = -EFAULT; if (copy_from_user(&user_ns, argp, sizeof(user_ns))) goto out; r = -EINVAL; if (user_ns.flags) goto out; r = 0; local_irq_disable(); now_ns = get_kernel_ns(); delta = user_ns.clock - now_ns; local_irq_enable(); kvm->arch.kvmclock_offset = delta; break; } case KVM_GET_CLOCK: { struct kvm_clock_data user_ns; u64 now_ns; local_irq_disable(); now_ns = get_kernel_ns(); user_ns.clock = kvm->arch.kvmclock_offset + now_ns; local_irq_enable(); user_ns.flags = 0; memset(&user_ns.pad, 0, sizeof(user_ns.pad)); r = -EFAULT; if (copy_to_user(argp, &user_ns, sizeof(user_ns))) goto out; r = 0; break; } default: ; } out: 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 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 user_describe(const struct key *key, struct seq_file *m) { seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %u", key->datalen); } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static void act_open_req_arp_failure(struct t3cdev *dev, struct sk_buff *skb) { printk(KERN_ERR MOD "ARP failure duing connect\n"); kfree_skb(skb); } Commit Message: iw_cxgb3: Fix incorrectly returning error on success The cxgb3_*_send() functions return NET_XMIT_ values, which are positive integers values. So don't treat positive return values as an error. Signed-off-by: Steve Wise <[email protected]> Signed-off-by: Hariprasad Shenai <[email protected]> Signed-off-by: Doug Ledford <[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: build_model (XML_Parser parser) { DTD * const dtd = parser->m_dtd; /* save one level of indirection */ XML_Content *ret; XML_Content *cpos; XML_Char * str; int allocsize = (dtd->scaffCount * sizeof(XML_Content) + (dtd->contentStringLen * sizeof(XML_Char))); ret = (XML_Content *)MALLOC(parser, allocsize); if (!ret) return NULL; str = (XML_Char *) (&ret[dtd->scaffCount]); cpos = &ret[1]; build_node(parser, 0, ret, &cpos, &str); return ret; } Commit Message: xmlparse.c: Fix extraction of namespace prefix from XML name (#186) CWE ID: CWE-611 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: QString IRCView::openTags(TextHtmlData* data, int from) { QString ret, tag; int i = from; for ( ; i < data->openHtmlTags.count(); ++i) { tag = data->openHtmlTags.at(i); if (data->reverse) { ret += fontColorOpenTag(Preferences::self()->color(Preferences::TextViewBackground).name()); } else { ret += fontColorOpenTag(data->lastFgColor); } } else if (tag == QLatin1String("span")) { if (data->reverse) { ret += spanColorOpenTag(data->defaultColor); } else { ret += spanColorOpenTag(data->lastBgColor); } } else { ret += QLatin1Char('<') + tag + QLatin1Char('>'); } } Commit Message: CWE ID: Target: 1 Example 2: Code: void shut_down(int code) { int i; int bytes_in = 0; int bytes_out = 0; in_shutdown = 1; proc_cleanup(); i = 0; while (backend_cached && backend_cached[i]) { proxy_downserver(backend_cached[i]); if (backend_cached[i]->last_result.s) { free(backend_cached[i]->last_result.s); } free(backend_cached[i]); i++; } if (backend_cached) free(backend_cached); if (mupdate_h) mupdate_disconnect(&mupdate_h); if (idling) idle_stop(index_mboxname(imapd_index)); if (imapd_index) index_close(&imapd_index); sync_log_done(); seen_done(); mboxkey_done(); mboxlist_close(); mboxlist_done(); quotadb_close(); quotadb_done(); denydb_close(); denydb_done(); annotatemore_close(); annotate_done(); idle_done(); if (config_getswitch(IMAPOPT_STATUSCACHE)) { statuscache_close(); statuscache_done(); } partlist_local_done(); if (imapd_in) { /* Flush the incoming buffer */ prot_NONBLOCK(imapd_in); prot_fill(imapd_in); bytes_in = prot_bytes_in(imapd_in); prot_free(imapd_in); } if (imapd_out) { /* Flush the outgoing buffer */ prot_flush(imapd_out); bytes_out = prot_bytes_out(imapd_out); prot_free(imapd_out); /* one less active connection */ snmp_increment(ACTIVE_CONNECTIONS, -1); } if (config_auditlog) syslog(LOG_NOTICE, "auditlog: traffic sessionid=<%s> bytes_in=<%d> bytes_out=<%d>", session_id(), bytes_in, bytes_out); if (protin) protgroup_free(protin); #ifdef HAVE_SSL tls_shutdown_serverengine(); #endif cyrus_done(); exit(code); } Commit Message: imapd: check for isadmin BEFORE parsing sync lines 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 MidiManagerUsb::DispatchSendMidiData(MidiManagerClient* client, uint32_t port_index, const std::vector<uint8>& data, double timestamp) { DCHECK_LT(port_index, output_streams_.size()); output_streams_[port_index]->Send(data); client->AccumulateMidiBytesSent(data.size()); } Commit Message: MidiManagerUsb should not trust indices provided by renderer. MidiManagerUsb::DispatchSendMidiData takes |port_index| parameter. As it is provided by a renderer possibly under the control of an attacker, we must validate the given index before using it. BUG=456516 Review URL: https://codereview.chromium.org/907793002 Cr-Commit-Position: refs/heads/master@{#315303} 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 bool on_accept(private_stroke_socket_t *this, stream_t *stream) { stroke_msg_t *msg; uint16_t len; FILE *out; /* read length */ if (!stream->read_all(stream, &len, sizeof(len))) { if (errno != EWOULDBLOCK) { DBG1(DBG_CFG, "reading length of stroke message failed: %s", strerror(errno)); } return FALSE; } /* read message (we need an additional byte to terminate the buffer) */ msg = malloc(len + 1); DBG1(DBG_CFG, "reading stroke message failed: %s", strerror(errno)); } Commit Message: CWE ID: CWE-787 Target: 1 Example 2: Code: void AppCacheUpdateJob::OnResponseInfoLoaded( AppCacheResponseInfo* response_info, int64 response_id) { const net::HttpResponseInfo* http_info = response_info ? response_info->http_response_info() : NULL; if (internal_state_ == FETCH_MANIFEST) { if (http_info) manifest_fetcher_->set_existing_response_headers( http_info->headers.get()); manifest_fetcher_->Start(); return; } LoadingResponses::iterator found = loading_responses_.find(response_id); DCHECK(found != loading_responses_.end()); const GURL& url = found->second; if (!http_info) { LoadFromNewestCacheFailed(url, NULL); // no response found } else { const std::string name = "vary"; std::string value; void* iter = NULL; if (!http_info->headers.get() || http_info->headers->RequiresValidation(http_info->request_time, http_info->response_time, base::Time::Now()) || http_info->headers->EnumerateHeader(&iter, name, &value)) { LoadFromNewestCacheFailed(url, response_info); } else { DCHECK(group_->newest_complete_cache()); AppCacheEntry* copy_me = group_->newest_complete_cache()->GetEntry(url); DCHECK(copy_me); DCHECK(copy_me->response_id() == response_id); AppCache::EntryMap::iterator it = url_file_list_.find(url); DCHECK(it != url_file_list_.end()); AppCacheEntry& entry = it->second; entry.set_response_id(response_id); entry.set_response_size(copy_me->response_size()); inprogress_cache_->AddOrModifyEntry(url, entry); NotifyAllProgress(url); ++url_fetches_completed_; } } loading_responses_.erase(found); MaybeCompleteUpdate(); } Commit Message: AppCache: fix a browser crashing bug that can happen during updates. BUG=558589 Review URL: https://codereview.chromium.org/1463463003 Cr-Commit-Position: refs/heads/master@{#360967} 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: WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec, WORD32 num_mb_skip, UWORD8 u1_is_idr_slice, UWORD16 u2_frame_num, pocstruct_t *ps_cur_poc, WORD32 prev_slice_err) { WORD32 i2_cur_mb_addr; UWORD32 u1_num_mbs, u1_num_mbsNby2; UWORD32 u1_mb_idx = ps_dec->u1_mb_idx; UWORD32 i2_mb_skip_run; UWORD32 u1_num_mbs_next, u1_end_of_row; const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; UWORD32 u1_slice_end; UWORD32 u1_tfr_n_mb; UWORD32 u1_decode_nmb; dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; deblk_mb_t *ps_cur_deblk_mb; dec_mb_info_t *ps_cur_mb_info; parse_pmbarams_t *ps_parse_mb_data; UWORD32 u1_inter_mb_type; UWORD32 u1_deblk_mb_type; UWORD16 u2_total_mbs_coded; UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag; parse_part_params_t *ps_part_info; WORD32 ret; if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return 0; } if(prev_slice_err == 1) { /* first slice - missing/header corruption */ ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num; if(!ps_dec->u1_first_slice_in_stream) { ih264d_end_of_pic(ps_dec, u1_is_idr_slice, ps_dec->ps_cur_slice->u2_frame_num); ps_dec->s_cur_pic_poc.u2_frame_num = ps_dec->ps_cur_slice->u2_frame_num; } { WORD32 i, j, poc = 0; ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0; ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; if(ps_dec->ps_cur_pic != NULL) poc = ps_dec->ps_cur_pic->i4_poc + 2; j = 0; for(i = 0; i < MAX_NUM_PIC_PARAMS; i++) if(ps_dec->ps_pps[i].u1_is_valid == TRUE) j = i; { ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc, ps_dec->ps_cur_slice->u2_frame_num, &ps_dec->ps_pps[j]); if(ret != OK) { return ret; } } ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0; ps_dec->u4_output_present = 0; { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); /* If error code is non-zero then there is no buffer available for display, hence avoid format conversion */ if(0 != ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; } else ps_dec->u4_output_present = 1; } if(ps_dec->u1_separate_parse == 1) { if(ps_dec->u4_dec_thread_created == 0) { ithread_create(ps_dec->pv_dec_thread_handle, NULL, (void *)ih264d_decode_picture_thread, (void *)ps_dec); ps_dec->u4_dec_thread_created = 1; } if((ps_dec->u4_num_cores == 3) && ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) && (ps_dec->u4_bs_deblk_thread_created == 0)) { ps_dec->u4_start_recon_deblk = 0; ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, (void *)ih264d_recon_deblk_thread, (void *)ps_dec); ps_dec->u4_bs_deblk_thread_created = 1; } } } } else { dec_slice_struct_t *ps_parse_cur_slice; ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; if(ps_dec->u1_slice_header_done && ps_parse_cur_slice == ps_dec->ps_parse_cur_slice) { u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb; if(u1_num_mbs) { ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1; } else { if(ps_dec->u1_separate_parse) { ps_cur_mb_info = ps_dec->ps_nmb_info - 1; } else { ps_cur_mb_info = ps_dec->ps_nmb_info + ps_dec->u4_num_mbs_prev_nmb - 1; } } ps_dec->u2_mby = ps_cur_mb_info->u2_mby; ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx; ps_dec->u1_mb_ngbr_availablity = ps_cur_mb_info->u1_mb_ngbr_availablity; ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data; ps_dec->u2_cur_mb_addr--; ps_dec->i4_submb_ofst -= SUB_BLK_SIZE; if(u1_num_mbs) { if (ps_dec->u1_pr_sl_type == P_SLICE || ps_dec->u1_pr_sl_type == B_SLICE) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); ps_dec->ps_part = ps_dec->ps_parse_part_params; } u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = 1; u1_tfr_n_mb = 1; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } ps_dec->u1_mb_idx = 0; ps_dec->u4_num_mbs_cur_nmb = 0; } if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; return 0; } ps_dec->u2_cur_slice_num++; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; ps_dec->ps_parse_cur_slice++; } else { ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; } } /******************************************************/ /* Initializations to new slice */ /******************************************************/ { WORD32 num_entries; WORD32 size; UWORD8 *pu1_buf; num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init); num_entries = 2 * ((2 * num_entries) + 1); size = num_entries * sizeof(void *); size += PAD_MAP_IDX_POC * sizeof(void *); pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; pu1_buf += size * ps_dec->u2_cur_slice_num; ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf; } ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; if(ps_dec->ps_cur_slice->u1_field_pic_flag) ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num; ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; if(ps_dec->u1_separate_parse) { ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; } else { ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; } /******************************************************/ /* Initializations specific to P slice */ /******************************************************/ u1_inter_mb_type = P_MB; u1_deblk_mb_type = D_INTER_MB; ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; ps_dec->ps_parse_cur_slice->slice_type = P_SLICE; ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb; ps_dec->ps_part = ps_dec->ps_parse_part_params; /******************************************************/ /* Parsing / decoding the slice */ /******************************************************/ ps_dec->u1_slice_header_done = 2; ps_dec->u1_qp = ps_slice->u1_slice_qp; ih264d_update_qp(ps_dec, 0); u1_mb_idx = ps_dec->u1_mb_idx; ps_parse_mb_data = ps_dec->ps_parse_mb_data; u1_num_mbs = u1_mb_idx; u1_slice_end = 0; u1_tfr_n_mb = 0; u1_decode_nmb = 0; u1_num_mbsNby2 = 0; i2_cur_mb_addr = ps_dec->u2_total_mbs_coded; i2_mb_skip_run = num_mb_skip; while(!u1_slice_end) { UWORD8 u1_mb_type; if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) break; ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; ps_cur_mb_info->u1_Mux = 0; ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; ps_cur_mb_info->u1_end_of_slice = 0; /* Storing Default partition info */ ps_parse_mb_data->u1_num_part = 1; ps_parse_mb_data->u1_isI_mb = 0; /**************************************************************/ /* Get the required information for decoding of MB */ /**************************************************************/ /* mb_x, mb_y, neighbor availablity, */ if (u1_mbaff) ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); else ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); /* Set the deblocking parameters for this MB */ if(ps_dec->u4_app_disable_deblk_frm == 0) { ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, ps_dec->u1_mb_ngbr_availablity, ps_dec->u1_cur_mb_fld_dec_flag); } /* Set appropriate flags in ps_cur_mb_info and ps_dec */ ps_dec->i1_prev_mb_qp_delta = 0; ps_dec->u1_sub_mb_num = 0; ps_cur_mb_info->u1_mb_type = MB_SKIP; ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16; ps_cur_mb_info->u1_cbp = 0; /* Storing Skip partition info */ ps_part_info = ps_dec->ps_part; ps_part_info->u1_is_direct = PART_DIRECT_16x16; ps_part_info->u1_sub_mb_num = 0; ps_dec->ps_part++; /* Update Nnzs */ ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC); ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type; ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type; i2_mb_skip_run--; ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; if (u1_mbaff) { ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); } /**************************************************************/ /* Get next Macroblock address */ /**************************************************************/ i2_cur_mb_addr++; u1_num_mbs++; ps_dec->u2_total_mbs_coded++; u1_num_mbsNby2++; ps_parse_mb_data++; /****************************************************************/ /* Check for End Of Row and other flags that determine when to */ /* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */ /* N-Mb */ /****************************************************************/ u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); u1_slice_end = !i2_mb_skip_run; u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row || u1_slice_end; u1_decode_nmb = u1_tfr_n_mb || u1_slice_end; ps_cur_mb_info->u1_end_of_slice = u1_slice_end; if(u1_decode_nmb) { ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); u1_num_mbsNby2 = 0; ps_parse_mb_data = ps_dec->ps_parse_mb_data; ps_dec->ps_part = ps_dec->ps_parse_part_params; if(ps_dec->u1_separate_parse) { ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); ps_dec->ps_nmb_info += u1_num_mbs; } else { ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); } if(u1_tfr_n_mb) u1_num_mbs = 0; u1_mb_idx = u1_num_mbs; ps_dec->u1_mb_idx = u1_num_mbs; } } ps_dec->u4_num_mbs_cur_nmb = 0; ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr - ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice; H264_DEC_DEBUG_PRINT("Mbs in slice: %d\n", ps_dec->ps_cur_slice->u4_mbs_in_slice); ps_dec->u2_cur_slice_num++; /* incremented here only if first slice is inserted */ if(ps_dec->u4_first_slice_in_pic != 0) ps_dec->ps_parse_cur_slice++; ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; if(ps_dec->u2_total_mbs_coded >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { ps_dec->u1_pic_decode_done = 1; } return 0; } Commit Message: Decoder Update mb count after mb map is set. Bug: 25928803 Change-Id: Iccc58a7dd1c5c6ea656dfca332cfb8dddba4de37 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: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) { jas_image_t *image; bmp_hdr_t hdr; bmp_info_t *info; uint_fast16_t cmptno; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; uint_fast16_t numcmpts; long n; if (optstr) { jas_eprintf("warning: ignoring BMP decoder options\n"); } jas_eprintf( "THE BMP FORMAT IS NOT FULLY SUPPORTED!\n" "THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n" "IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n" "TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n" ); /* Read the bitmap header. */ if (bmp_gethdr(in, &hdr)) { jas_eprintf("cannot get header\n"); return 0; } /* Read the bitmap information. */ if (!(info = bmp_getinfo(in))) { jas_eprintf("cannot get info\n"); return 0; } /* Ensure that we support this type of BMP file. */ if (!bmp_issupported(&hdr, info)) { jas_eprintf("error: unsupported BMP encoding\n"); bmp_info_destroy(info); return 0; } /* Skip over any useless data between the end of the palette and start of the bitmap data. */ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { jas_eprintf("error: possibly bad bitmap offset?\n"); return 0; } if (n > 0) { jas_eprintf("skipping unknown data in BMP file\n"); if (bmp_gobble(in, n)) { bmp_info_destroy(info); return 0; } } /* Get the number of components. */ numcmpts = bmp_numcmpts(info); for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = info->width; cmptparm->height = info->height; cmptparm->prec = 8; cmptparm->sgnd = false; } /* Create image object. */ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { bmp_info_destroy(info); return 0; } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read the bitmap data. */ if (bmp_getdata(in, info, image)) { bmp_info_destroy(info); jas_image_destroy(image); return 0; } bmp_info_destroy(info); return image; } Commit Message: Fixed a sanitizer failure in the BMP codec. Also, added a --debug-level command line option to the imginfo command for debugging purposes. CWE ID: CWE-476 Target: 1 Example 2: Code: BOOLEAN btif_hl_is_the_first_reliable_existed(UINT8 app_idx, UINT8 mcl_idx ) { btif_hl_mcl_cb_t *p_mcb =BTIF_HL_GET_MCL_CB_PTR(app_idx, mcl_idx); BOOLEAN is_existed =FALSE; UINT8 i ; for (i=0; i< BTA_HL_NUM_MDLS_PER_MCL; i++) { if (p_mcb->mdl[i].in_use && p_mcb->mdl[i].is_the_first_reliable) { is_existed = TRUE; break; } } BTIF_TRACE_DEBUG("bta_hl_is_the_first_reliable_existed is_existed=%d ",is_existed ); return is_existed; } 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: 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 main(int argc, char *argv[]) { FILE *fp_rd = stdin; FILE *fp_wr = stdout; FILE *fp_al = NULL; BOOL raw = TRUE; BOOL alpha = FALSE; int argi; for (argi = 1; argi < argc; argi++) { if (argv[argi][0] == '-') { switch (argv[argi][1]) { case 'n': raw = FALSE; break; case 'r': raw = TRUE; break; case 'a': alpha = TRUE; argi++; if ((fp_al = fopen (argv[argi], "wb")) == NULL) { fprintf (stderr, "PNM2PNG\n"); fprintf (stderr, "Error: can not create alpha-channel file %s\n", argv[argi]); exit (1); } break; case 'h': case '?': usage(); exit(0); break; default: fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: unknown option %s\n", argv[argi]); usage(); exit(1); break; } /* end switch */ } else if (fp_rd == stdin) { if ((fp_rd = fopen (argv[argi], "rb")) == NULL) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: file %s does not exist\n", argv[argi]); exit (1); } } else if (fp_wr == stdout) { if ((fp_wr = fopen (argv[argi], "wb")) == NULL) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: can not create file %s\n", argv[argi]); exit (1); } } else { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: too many parameters\n"); usage(); exit(1); } } /* end for */ #ifdef __TURBOC__ /* set stdin/stdout if required to binary */ if (fp_rd == stdin) { setmode (STDIN, O_BINARY); } if ((raw) && (fp_wr == stdout)) { setmode (STDOUT, O_BINARY); } #endif /* call the conversion program itself */ if (png2pnm (fp_rd, fp_wr, fp_al, raw, alpha) == FALSE) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: unsuccessful conversion of PNG-image\n"); exit(1); } /* close input file */ fclose (fp_rd); /* close output file */ fclose (fp_wr); /* close alpha file */ if (alpha) fclose (fp_al); return 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) 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 BaseAudioContext::WouldTaintOrigin(const KURL& url) const { if (url.ProtocolIsData()) { return false; } Document* document = GetDocument(); if (document && document->GetSecurityOrigin()) { return !document->GetSecurityOrigin()->CanRequest(url); } return true; } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Target: 1 Example 2: Code: mm_answer_rsa_response(int sock, Buffer *m) { Key *key = NULL; u_char *blob, *response; u_int blen, len; int success; debug3("%s entering", __func__); if (!authctxt->valid) fatal("%s: authctxt not valid", __func__); if (ssh1_challenge == NULL) fatal("%s: no ssh1_challenge", __func__); blob = buffer_get_string(m, &blen); if (!monitor_allowed_key(blob, blen)) fatal("%s: bad key, not previously allowed", __func__); if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY) fatal("%s: key type mismatch: %d", __func__, key_blobtype); if ((key = key_from_blob(blob, blen)) == NULL) fatal("%s: received bad key", __func__); response = buffer_get_string(m, &len); if (len != 16) fatal("%s: received bad response to challenge", __func__); success = auth_rsa_verify_response(key, ssh1_challenge, response); free(blob); key_free(key); free(response); auth_method = key_blobtype == MM_RSAUSERKEY ? "rsa" : "rhosts-rsa"; /* reset state */ BN_clear_free(ssh1_challenge); ssh1_challenge = NULL; monitor_reset_key_state(); buffer_clear(m); buffer_put_int(m, success); mm_request_send(sock, MONITOR_ANS_RSARESPONSE, m); return (success); } Commit Message: set sshpam_ctxt to NULL after free Avoids use-after-free in monitor when privsep child is compromised. Reported by Moritz Jodeit; ok dtucker@ 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 PaymentRequest::UpdateWith(mojom::PaymentDetailsPtr details) { std::string error; if (!ValidatePaymentDetails(ConvertPaymentDetails(details), &error)) { LOG(ERROR) << error; OnConnectionTerminated(); return; } if (details->shipping_address_errors && !PaymentsValidators::IsValidAddressErrorsFormat( details->shipping_address_errors, &error)) { DLOG(ERROR) << error; OnConnectionTerminated(); return; } if (!details->total) { LOG(ERROR) << "Missing total"; OnConnectionTerminated(); return; } spec_->UpdateWith(std::move(details)); } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} 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 NetworkHandler::ClearBrowserCookies( std::unique_ptr<ClearBrowserCookiesCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &ClearCookiesOnIO, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()), std::move(callback))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Target: 1 Example 2: Code: SPICE_GNUC_VISIBLE int spice_server_migrate_connect(SpiceServer *s, const char* dest, int port, int secure_port, const char* cert_subject) { SpiceMigrateInterface *sif; int try_seamless; spice_info(NULL); spice_assert(migration_interface); spice_assert(reds == s); if (reds->expect_migrate) { spice_info("consecutive calls without migration. Canceling previous call"); main_channel_migrate_src_complete(reds->main_channel, FALSE); } sif = SPICE_CONTAINEROF(migration_interface->base.sif, SpiceMigrateInterface, base); if (!reds_set_migration_dest_info(dest, port, secure_port, cert_subject)) { sif->migrate_connect_complete(migration_interface); return -1; } reds->expect_migrate = TRUE; /* * seamless migration support was added to the client after the support in * agent_connect_tokens, so there shouldn't be contradicition - if * the client is capable of seamless migration, it is capbable of agent_connected_tokens. * The demand for agent_connected_tokens support is in order to assure that if migration * occured when the agent was not connected, the tokens state after migration will still * be valid (see reds_reset_vdp for more details). */ try_seamless = reds->seamless_migration_enabled && red_channel_test_remote_cap(&reds->main_channel->base, SPICE_MAIN_CAP_AGENT_CONNECTED_TOKENS); /* main channel will take care of clients that are still during migration (at target)*/ if (main_channel_migrate_connect(reds->main_channel, reds->mig_spice, try_seamless)) { reds_mig_started(); } else { if (reds->num_clients == 0) { reds_mig_release(); spice_info("no client connected"); } sif->migrate_connect_complete(migration_interface); } return 0; } 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 irda_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct irda_sock *self; if (net != &init_net) return -EAFNOSUPPORT; /* Check for valid socket type */ switch (sock->type) { case SOCK_STREAM: /* For TTP connections with SAR disabled */ case SOCK_SEQPACKET: /* For TTP connections with SAR enabled */ case SOCK_DGRAM: /* For TTP Unitdata or LMP Ultra transfers */ break; default: return -ESOCKTNOSUPPORT; } /* Allocate networking socket */ sk = sk_alloc(net, PF_IRDA, GFP_KERNEL, &irda_proto, kern); if (sk == NULL) return -ENOMEM; self = irda_sk(sk); pr_debug("%s() : self is %p\n", __func__, self); init_waitqueue_head(&self->query_wait); switch (sock->type) { case SOCK_STREAM: sock->ops = &irda_stream_ops; self->max_sdu_size_rx = TTP_SAR_DISABLE; break; case SOCK_SEQPACKET: sock->ops = &irda_seqpacket_ops; self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; case SOCK_DGRAM: switch (protocol) { #ifdef CONFIG_IRDA_ULTRA case IRDAPROTO_ULTRA: sock->ops = &irda_ultra_ops; /* Initialise now, because we may send on unbound * sockets. Jean II */ self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER; self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER; break; #endif /* CONFIG_IRDA_ULTRA */ case IRDAPROTO_UNITDATA: sock->ops = &irda_dgram_ops; /* We let Unitdata conn. be like seqpack conn. */ self->max_sdu_size_rx = TTP_SAR_UNBOUND; break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } break; default: sk_free(sk); return -ESOCKTNOSUPPORT; } /* Initialise networking socket struct */ sock_init_data(sock, sk); /* Note : set sk->sk_refcnt to 1 */ sk->sk_family = PF_IRDA; sk->sk_protocol = protocol; /* Register as a client with IrLMP */ self->ckey = irlmp_register_client(0, NULL, NULL, NULL); self->mask.word = 0xffff; self->rx_flow = self->tx_flow = FLOW_START; self->nslots = DISCOVERY_DEFAULT_SLOTS; self->daddr = DEV_ADDR_ANY; /* Until we get connected */ self->saddr = 0x0; /* so IrLMP assign us any link */ return 0; } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <[email protected]> Reported-by: 郭永刚 <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static bool check_client_passwd(PgSocket *client, const char *passwd) { char md5[MD5_PASSWD_LEN + 1]; const char *correct; PgUser *user = client->auth_user; /* disallow empty passwords */ if (!*passwd || !*user->passwd) return false; switch (cf_auth_type) { case AUTH_PLAIN: return strcmp(user->passwd, passwd) == 0; case AUTH_CRYPT: correct = crypt(user->passwd, (char *)client->tmp_login_salt); return correct && strcmp(correct, passwd) == 0; case AUTH_MD5: if (strlen(passwd) != MD5_PASSWD_LEN) return false; if (!isMD5(user->passwd)) pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); return strcmp(md5, passwd) == 0; } return false; } Commit Message: Check if auth_user is set. Fixes a crash if password packet appears before startup packet (#42). CWE ID: CWE-476 Target: 1 Example 2: Code: static int64_t luma_abs_diff(const AVFrame *f1, const AVFrame *f2) { int x, y; const uint8_t *srcp1 = f1->data[0]; const uint8_t *srcp2 = f2->data[0]; const int src1_linesize = f1->linesize[0]; const int src2_linesize = f2->linesize[0]; const int width = f1->width; const int height = f1->height; int64_t acc = 0; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) acc += abs(srcp1[x] - srcp2[x]); srcp1 += src1_linesize; srcp2 += src2_linesize; } return acc; } 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: void PrintJobWorker::StopSoon() { thread_.StopSoon(); } Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884} CWE ID: CWE-20 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_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, "Support for %d components", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if (!s->cdx[i] || !s->cdy[i]) { av_log(s->avctx, AV_LOG_ERROR, "Invalid sample seperation\n"); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, "Unknown pix_fmt, profile: %d, colour_space: %d, " "components: %d, precision: %d, " "cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } return 0; } Commit Message: avcodec/jpeg2000dec: Check cdx/y values more carefully Some invalid values where not handled correctly in the later pixel format matching code. Fixes out of array accesses Fixes Ticket2848 Found-by: Piotr Bandurski <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn) { BUG_ON(!(vma->vm_flags & VM_MIXEDMAP)); if (addr < vma->vm_start || addr >= vma->vm_end) return -EFAULT; /* * If we don't have pte special, then we have to use the pfn_valid() * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must* * refcount the page if pfn_valid is true (hence insert_page rather * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP * without pte special, it would there be refcounted as a normal page. */ if (!HAVE_PTE_SPECIAL && pfn_valid(pfn)) { struct page *page; page = pfn_to_page(pfn); return insert_page(vma, addr, page, vma->vm_page_prot); } return insert_pfn(vma, addr, pfn, vma->vm_page_prot); } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 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: xfs_attr3_leaf_add_work( struct xfs_buf *bp, struct xfs_attr3_icleaf_hdr *ichdr, struct xfs_da_args *args, int mapindex) { struct xfs_attr_leafblock *leaf; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; struct xfs_mount *mp; int tmp; int i; trace_xfs_attr_leaf_add_work(args); leaf = bp->b_addr; ASSERT(mapindex >= 0 && mapindex < XFS_ATTR_LEAF_MAPSIZE); ASSERT(args->index >= 0 && args->index <= ichdr->count); /* * Force open some space in the entry array and fill it in. */ entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (args->index < ichdr->count) { tmp = ichdr->count - args->index; tmp *= sizeof(xfs_attr_leaf_entry_t); memmove(entry + 1, entry, tmp); xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(*entry))); } ichdr->count++; /* * Allocate space for the new string (at the end of the run). */ mp = args->trans->t_mountp; ASSERT(ichdr->freemap[mapindex].base < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].base & 0x3) == 0); ASSERT(ichdr->freemap[mapindex].size >= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, NULL)); ASSERT(ichdr->freemap[mapindex].size < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].size & 0x3) == 0); ichdr->freemap[mapindex].size -= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, &tmp); entry->nameidx = cpu_to_be16(ichdr->freemap[mapindex].base + ichdr->freemap[mapindex].size); entry->hashval = cpu_to_be32(args->hashval); entry->flags = tmp ? XFS_ATTR_LOCAL : 0; entry->flags |= XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags); if (args->op_flags & XFS_DA_OP_RENAME) { entry->flags |= XFS_ATTR_INCOMPLETE; if ((args->blkno2 == args->blkno) && (args->index2 <= args->index)) { args->index2++; } } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry))); ASSERT((args->index == 0) || (be32_to_cpu(entry->hashval) >= be32_to_cpu((entry-1)->hashval))); ASSERT((args->index == ichdr->count - 1) || (be32_to_cpu(entry->hashval) <= be32_to_cpu((entry+1)->hashval))); /* * For "remote" attribute values, simply note that we need to * allocate space for the "remote" value. We can't actually * allocate the extents in this transaction, and we can't decide * which blocks they should be as we might allocate more blocks * as part of this transaction (a split operation for example). */ if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); name_loc->namelen = args->namelen; name_loc->valuelen = cpu_to_be16(args->valuelen); memcpy((char *)name_loc->nameval, args->name, args->namelen); memcpy((char *)&name_loc->nameval[args->namelen], args->value, be16_to_cpu(name_loc->valuelen)); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); name_rmt->namelen = args->namelen; memcpy((char *)name_rmt->name, args->name, args->namelen); entry->flags |= XFS_ATTR_INCOMPLETE; /* just in case */ name_rmt->valuelen = 0; name_rmt->valueblk = 0; args->rmtblkno = 1; args->rmtblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen); } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index), xfs_attr_leaf_entsize(leaf, args->index))); /* * Update the control info for this leaf node */ if (be16_to_cpu(entry->nameidx) < ichdr->firstused) ichdr->firstused = be16_to_cpu(entry->nameidx); ASSERT(ichdr->firstused >= ichdr->count * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf)); tmp = (ichdr->count - 1) * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf); for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) { if (ichdr->freemap[i].base == tmp) { ichdr->freemap[i].base += sizeof(xfs_attr_leaf_entry_t); ichdr->freemap[i].size -= sizeof(xfs_attr_leaf_entry_t); } } ichdr->usedbytes += xfs_attr_leaf_entsize(leaf, args->index); return 0; } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19 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 HTMLDocument::removeItemFromMap(HashCountedSet<StringImpl*>& map, const AtomicString& name) { if (name.isEmpty()) return; map.remove(name.impl()); if (Frame* f = frame()) f->script()->namedItemRemoved(this, name); } Commit Message: Fix tracking of the id attribute string if it is shared across elements. The patch to remove AtomicStringImpl: http://src.chromium.org/viewvc/blink?view=rev&rev=154790 Exposed a lifetime issue with strings for id attributes. We simply need to use AtomicString. BUG=290566 Review URL: https://codereview.chromium.org/33793004 git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu) { int r = kvm_init_shadow_ept_mmu(vcpu, &vcpu->arch.mmu, nested_vmx_ept_caps & VMX_EPT_EXECUTE_ONLY_BIT); vcpu->arch.mmu.set_cr3 = vmx_set_cr3; vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3; vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault; vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu; return r; } Commit Message: nEPT: Nested INVEPT If we let L1 use EPT, we should probably also support the INVEPT instruction. In our current nested EPT implementation, when L1 changes its EPT table for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in the course of this modification already calls INVEPT. But if last level of shadow page is unsync not all L1's changes to EPT12 are intercepted, which means roots need to be synced when L1 calls INVEPT. Global INVEPT should not be different since roots are synced by kvm_mmu_load() each time EPTP02 changes. Reviewed-by: Xiao Guangrong <[email protected]> Signed-off-by: Nadav Har'El <[email protected]> Signed-off-by: Jun Nakajima <[email protected]> Signed-off-by: Xinhao Xu <[email protected]> Signed-off-by: Yang Zhang <[email protected]> Signed-off-by: Gleb Natapov <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len) { const sp<ProcessState> proc(ProcessState::self()); status_t err; const uint8_t *data = parcel->mData; const binder_size_t *objects = parcel->mObjects; size_t size = parcel->mObjectsSize; int startPos = mDataPos; int firstIndex = -1, lastIndex = -2; if (len == 0) { return NO_ERROR; } if ((offset > parcel->mDataSize) || (len > parcel->mDataSize) || (offset + len > parcel->mDataSize)) { return BAD_VALUE; } for (int i = 0; i < (int) size; i++) { size_t off = objects[i]; if ((off >= offset) && (off < offset + len)) { if (firstIndex == -1) { firstIndex = i; } lastIndex = i; } } int numObjects = lastIndex - firstIndex + 1; if ((mDataSize+len) > mDataCapacity) { err = growData(len); if (err != NO_ERROR) { return err; } } memcpy(mData + mDataPos, data + offset, len); mDataPos += len; mDataSize += len; err = NO_ERROR; if (numObjects > 0) { if (mObjectsCapacity < mObjectsSize + numObjects) { int newSize = ((mObjectsSize + numObjects)*3)/2; binder_size_t *objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t)); if (objects == (binder_size_t*)0) { return NO_MEMORY; } mObjects = objects; mObjectsCapacity = newSize; } int idx = mObjectsSize; for (int i = firstIndex; i <= lastIndex; i++) { size_t off = objects[i] - offset + startPos; mObjects[idx++] = off; mObjectsSize++; flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(mData + off); acquire_object(proc, *flat, this); if (flat->type == BINDER_TYPE_FD) { flat->handle = dup(flat->handle); flat->cookie = 1; mHasFds = mFdsKnown = true; if (!mAllowFds) { err = FDS_NOT_ALLOWED; } } } } return err; } Commit Message: Verify that the native handle was created The inputs to native_handle_create can cause an overflowed allocation, so check the return value of native_handle_create before accessing the memory it returns. Bug:19334482 Change-Id: I1f489382776c2a1390793a79dc27ea17baa9b2a2 (cherry picked from commit eaac99a7172da52a76ba48c26413778a74951b1a) 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 irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); struct sk_buff *skb; size_t copied; int err; IRDA_DEBUG(4, "%s()\n", __func__); msg->msg_namelen = 0; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &err); if (!skb) return err; skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n", __func__, copied, size); copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); skb_free_datagram(sk, skb); /* * Check if we have previously stopped IrTTP and we know * have more free space in our rx_queue. If so tell IrTTP * to start delivering frames again before our rx_queue gets * empty */ if (self->rx_flow == FLOW_STOP) { if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) { IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__); self->rx_flow = FLOW_START; irttp_flow_request(self->tsap, FLOW_START); } } return copied; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < num_samples) { int i; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= num_samples) k = num_samples - n; if (k) { for (i=0; i < z; ++i) memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k); for ( ; i < channels; ++i) memset(buffer[i]+n, 0, sizeof(float) * k); } n += k; f->channel_buffer_start += k; if (n == num_samples) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files 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 struct sock * tcp_v6_syn_recv_sock(struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst) { struct inet6_request_sock *treq; struct ipv6_pinfo *newnp, *np = inet6_sk(sk); struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; struct ipv6_txoptions *opt; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst); if (newsk == NULL) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); ipv6_addr_set_v4mapped(newinet->inet_daddr, &newnp->daddr); ipv6_addr_set_v4mapped(newinet->inet_saddr, &newnp->saddr); ipv6_addr_copy(&newnp->rcv_saddr, &newnp->saddr); inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } treq = inet6_rsk(req); opt = np->opt; if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, req); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; __ip6_dst_store(newsk, dst, NULL, NULL); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); ipv6_addr_copy(&newnp->daddr, &treq->rmt_addr); ipv6_addr_copy(&newnp->saddr, &treq->loc_addr); ipv6_addr_copy(&newnp->rcv_saddr, &treq->loc_addr); newsk->sk_bound_dev_if = treq->iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; /* Clone pktoptions received with SYN */ newnp->pktoptions = NULL; if (treq->pktopts != NULL) { newnp->pktoptions = skb_clone(treq->pktopts, GFP_ATOMIC); kfree_skb(treq->pktopts); treq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ if (opt) { newnp->opt = ipv6_dup_options(newsk, opt); if (opt != np->opt) sock_kfree_s(sk, opt, opt->tot_len); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newnp->opt) inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen + newnp->opt->opt_flen); tcp_mtup_init(newsk); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = dst_metric_advmss(dst); tcp_initialize_rcv_mss(newsk); if (tcp_rsk(req)->snt_synack) tcp_valid_rtt_meas(newsk, tcp_time_stamp - tcp_rsk(req)->snt_synack); newtp->total_retrans = req->retrans; newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ if ((key = tcp_v6_md5_do_lookup(sk, &newnp->daddr)) != NULL) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ char *newkey = kmemdup(key->key, key->keylen, GFP_ATOMIC); if (newkey != NULL) tcp_v6_md5_do_add(newsk, &newnp->daddr, newkey, key->keylen); } #endif if (__inet_inherit_port(sk, newsk) < 0) { sock_put(newsk); goto out; } __inet6_hash(newsk, NULL); return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: if (opt && opt != np->opt) sock_kfree_s(sk, opt, opt->tot_len); dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Output:
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 HTMLDocument::addItemToMap(HashCountedSet<StringImpl*>& map, const AtomicString& name) { if (name.isEmpty()) return; map.add(name.impl()); if (Frame* f = frame()) f->script()->namedItemAdded(this, name); } Commit Message: Fix tracking of the id attribute string if it is shared across elements. The patch to remove AtomicStringImpl: http://src.chromium.org/viewvc/blink?view=rev&rev=154790 Exposed a lifetime issue with strings for id attributes. We simply need to use AtomicString. BUG=290566 Review URL: https://codereview.chromium.org/33793004 git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: bool TaskManagerView::CanResize() const { return true; } Commit Message: accelerators: Remove deprecated Accelerator ctor that takes booleans. BUG=128242 [email protected] Review URL: https://chromiumcodereview.appspot.com/10399085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int adev_open_output_stream(struct audio_hw_device *dev, audio_io_handle_t handle, audio_devices_t devices, audio_output_flags_t flags, struct audio_config *config, struct audio_stream_out **stream_out, const char *address) { struct a2dp_audio_device *a2dp_dev = (struct a2dp_audio_device *)dev; struct a2dp_stream_out *out; int ret = 0; int i; UNUSED(address); UNUSED(handle); UNUSED(devices); UNUSED(flags); INFO("opening output"); out = (struct a2dp_stream_out *)calloc(1, sizeof(struct a2dp_stream_out)); if (!out) return -ENOMEM; out->stream.common.get_sample_rate = out_get_sample_rate; out->stream.common.set_sample_rate = out_set_sample_rate; out->stream.common.get_buffer_size = out_get_buffer_size; out->stream.common.get_channels = out_get_channels; out->stream.common.get_format = out_get_format; out->stream.common.set_format = out_set_format; out->stream.common.standby = out_standby; out->stream.common.dump = out_dump; out->stream.common.set_parameters = out_set_parameters; out->stream.common.get_parameters = out_get_parameters; out->stream.common.add_audio_effect = out_add_audio_effect; out->stream.common.remove_audio_effect = out_remove_audio_effect; out->stream.get_latency = out_get_latency; out->stream.set_volume = out_set_volume; out->stream.write = out_write; out->stream.get_render_position = out_get_render_position; out->stream.get_presentation_position = out_get_presentation_position; /* initialize a2dp specifics */ a2dp_stream_common_init(&out->common); out->common.cfg.channel_flags = AUDIO_STREAM_DEFAULT_CHANNEL_FLAG; out->common.cfg.format = AUDIO_STREAM_DEFAULT_FORMAT; out->common.cfg.rate = AUDIO_STREAM_DEFAULT_RATE; /* set output config values */ if (config) { config->format = out_get_format((const struct audio_stream *)&out->stream); config->sample_rate = out_get_sample_rate((const struct audio_stream *)&out->stream); config->channel_mask = out_get_channels((const struct audio_stream *)&out->stream); } *stream_out = &out->stream; a2dp_dev->output = out; a2dp_open_ctrl_path(&out->common); if (out->common.ctrl_fd == AUDIO_SKT_DISCONNECTED) { ERROR("ctrl socket failed to connect (%s)", strerror(errno)); ret = -1; goto err_open; } DEBUG("success"); /* Delay to ensure Headset is in proper state when START is initiated from DUT immediately after the connection due to ongoing music playback. */ usleep(250000); return 0; err_open: free(out); *stream_out = NULL; a2dp_dev->output = NULL; ERROR("failed"); return ret; } 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 DirectoryEntrySync::removeRecursively(ExceptionState& exceptionState) { RefPtr<VoidSyncCallbackHelper> helper = VoidSyncCallbackHelper::create(); m_fileSystem->removeRecursively(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); helper->getResult(exceptionState); } 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: 1 Example 2: Code: static void AppendQuadsToFillScreen(const gfx::Rect& root_scroll_layer_rect, RenderPass* target_render_pass, RenderSurfaceImpl* root_render_surface, SkColor screen_background_color, const Region& fill_region) { if (!root_render_surface || !SkColorGetA(screen_background_color)) return; if (fill_region.IsEmpty()) return; gfx::Rect root_target_rect = root_render_surface->content_rect(); float opacity = 1.f; int sorting_context_id = 0; SharedQuadState* shared_quad_state = target_render_pass->CreateAndAppendSharedQuadState(); shared_quad_state->SetAll(gfx::Transform(), root_target_rect.size(), root_target_rect, root_target_rect, false, opacity, SkBlendMode::kSrcOver, sorting_context_id); for (Region::Iterator fill_rects(fill_region); fill_rects.has_rect(); fill_rects.next()) { gfx::Rect screen_space_rect = fill_rects.rect(); gfx::Rect visible_screen_space_rect = screen_space_rect; SolidColorDrawQuad* quad = target_render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); quad->SetNew(shared_quad_state, screen_space_rect, visible_screen_space_rect, screen_background_color, false); } } Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 [email protected], [email protected] CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954} CWE ID: CWE-362 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 SoundPool::load(const char* path, int priority __unused) { ALOGV("load: path=%s, priority=%d", path, priority); Mutex::Autolock lock(&mLock); sp<Sample> sample = new Sample(++mNextSampleID, path); mSamples.add(sample->sampleID(), sample); doLoad(sample); return sample->sampleID(); } Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread Sample decoding still occurs in SoundPoolThread without holding the SoundPool lock. Bug: 25781119 Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8 CWE ID: CWE-264 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: LPSTR tr_esc_str(LPCSTR arg, bool format) { LPSTR tmp = NULL; size_t cs = 0, x, ds, len; size_t s; if (NULL == arg) return NULL; s = strlen(arg); /* Find trailing whitespaces */ while ((s > 0) && isspace(arg[s - 1])) s--; /* Prepare a initial buffer with the size of the result string. */ ds = s + 1; if (s) tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not allocate string buffer.\n"); exit(-2); } /* Copy character for character and check, if it is necessary to escape. */ memset(tmp, 0, ds * sizeof(CHAR)); for (x = 0; x < s; x++) { switch (arg[x]) { case '<': len = format ? 13 : 4; ds += len - 1; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-3); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "<replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '>': len = format ? 14 : 4; ds += len - 1; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-4); } if (format) /* coverity[buffer_size] */ strncpy(&tmp[cs], "</replaceable>", len); else /* coverity[buffer_size] */ strncpy(&tmp[cs], "&lt;", len); cs += len; break; case '\'': ds += 5; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-5); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'p'; tmp[cs++] = 'o'; tmp[cs++] = 's'; tmp[cs++] = ';'; break; case '"': ds += 5; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-6); } tmp[cs++] = '&'; tmp[cs++] = 'q'; tmp[cs++] = 'u'; tmp[cs++] = 'o'; tmp[cs++] = 't'; tmp[cs++] = ';'; break; case '&': ds += 4; tmp = (LPSTR)realloc(tmp, ds * sizeof(CHAR)); if (NULL == tmp) { fprintf(stderr, "Could not reallocate string buffer.\n"); exit(-7); } tmp[cs++] = '&'; tmp[cs++] = 'a'; tmp[cs++] = 'm'; tmp[cs++] = 'p'; tmp[cs++] = ';'; break; default: tmp[cs++] = arg[x]; break; } /* Assure, the string is '\0' terminated. */ tmp[ds - 1] = '\0'; } return tmp; } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772 Target: 1 Example 2: Code: static void *transit_hash_alloc(void *p) { /* Transit structure is already allocated. */ return p; } Commit Message: bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined Signed-off-by: Lou Berger <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void InspectorNetworkAgent::DidReceiveResourceResponse( unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, Resource* cached_resource) { String request_id = IdentifiersFactory::RequestId(identifier); bool is_not_modified = response.HttpStatusCode() == 304; bool resource_is_empty = true; std::unique_ptr<protocol::Network::Response> resource_response = BuildObjectForResourceResponse(response, cached_resource, &resource_is_empty); InspectorPageAgent::ResourceType type = cached_resource ? InspectorPageAgent::CachedResourceType(*cached_resource) : InspectorPageAgent::kOtherResource; InspectorPageAgent::ResourceType saved_type = resources_data_->GetResourceType(request_id); if (saved_type == InspectorPageAgent::kScriptResource || saved_type == InspectorPageAgent::kXHRResource || saved_type == InspectorPageAgent::kDocumentResource || saved_type == InspectorPageAgent::kFetchResource || saved_type == InspectorPageAgent::kEventSourceResource) { type = saved_type; } if (type == InspectorPageAgent::kDocumentResource && loader && loader->GetSubstituteData().IsValid()) return; if (cached_resource) resources_data_->AddResource(request_id, cached_resource); String frame_id = loader && loader->GetFrame() ? IdentifiersFactory::FrameId(loader->GetFrame()) : ""; String loader_id = loader ? IdentifiersFactory::LoaderId(loader) : ""; resources_data_->ResponseReceived(request_id, frame_id, response); resources_data_->SetResourceType(request_id, type); if (response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnknown && response.GetSecurityStyle() != ResourceResponse::kSecurityStyleUnauthenticated) { const ResourceResponse::SecurityDetails* response_security_details = response.GetSecurityDetails(); resources_data_->SetCertificate(request_id, response_security_details->certificate); } if (resource_response && !resource_is_empty) { Maybe<String> maybe_frame_id; if (!frame_id.IsEmpty()) maybe_frame_id = frame_id; GetFrontend()->responseReceived( request_id, loader_id, MonotonicallyIncreasingTime(), InspectorPageAgent::ResourceTypeJson(type), std::move(resource_response), std::move(maybe_frame_id)); } if (is_not_modified && cached_resource && cached_resource->EncodedSize()) DidReceiveData(identifier, loader, 0, cached_resource->EncodedSize()); } 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: crypto_retrieve_X509_sans(krb5_context context, pkinit_plg_crypto_context plgctx, pkinit_req_crypto_context reqctx, X509 *cert, krb5_principal **princs_ret, krb5_principal **upn_ret, unsigned char ***dns_ret) { krb5_error_code retval = EINVAL; char buf[DN_BUF_LEN]; int p = 0, u = 0, d = 0, ret = 0, l; krb5_principal *princs = NULL; krb5_principal *upns = NULL; unsigned char **dnss = NULL; unsigned int i, num_found = 0, num_sans = 0; X509_EXTENSION *ext = NULL; GENERAL_NAMES *ialt = NULL; GENERAL_NAME *gen = NULL; if (princs_ret != NULL) *princs_ret = NULL; if (upn_ret != NULL) *upn_ret = NULL; if (dns_ret != NULL) *dns_ret = NULL; if (princs_ret == NULL && upn_ret == NULL && dns_ret == NULL) { pkiDebug("%s: nowhere to return any values!\n", __FUNCTION__); return retval; } if (cert == NULL) { pkiDebug("%s: no certificate!\n", __FUNCTION__); return retval; } X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); pkiDebug("%s: looking for SANs in cert = %s\n", __FUNCTION__, buf); l = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1); if (l < 0) return 0; if (!(ext = X509_get_ext(cert, l)) || !(ialt = X509V3_EXT_d2i(ext))) { pkiDebug("%s: found no subject alt name extensions\n", __FUNCTION__); retval = ENOENT; goto cleanup; } num_sans = sk_GENERAL_NAME_num(ialt); pkiDebug("%s: found %d subject alt name extension(s)\n", __FUNCTION__, num_sans); /* OK, we're likely returning something. Allocate return values */ if (princs_ret != NULL) { princs = calloc(num_sans + 1, sizeof(krb5_principal)); if (princs == NULL) { retval = ENOMEM; goto cleanup; } } if (upn_ret != NULL) { upns = calloc(num_sans + 1, sizeof(krb5_principal)); if (upns == NULL) { retval = ENOMEM; goto cleanup; } } if (dns_ret != NULL) { dnss = calloc(num_sans + 1, sizeof(*dnss)); if (dnss == NULL) { retval = ENOMEM; goto cleanup; } } for (i = 0; i < num_sans; i++) { krb5_data name = { 0, 0, NULL }; gen = sk_GENERAL_NAME_value(ialt, i); switch (gen->type) { case GEN_OTHERNAME: name.length = gen->d.otherName->value->value.sequence->length; name.data = (char *)gen->d.otherName->value->value.sequence->data; if (princs != NULL && OBJ_cmp(plgctx->id_pkinit_san, gen->d.otherName->type_id) == 0) { #ifdef DEBUG_ASN1 print_buffer_bin((unsigned char *)name.data, name.length, "/tmp/pkinit_san"); #endif ret = k5int_decode_krb5_principal_name(&name, &princs[p]); if (ret) { pkiDebug("%s: failed decoding pkinit san value\n", __FUNCTION__); } else { p++; num_found++; } } else if (upns != NULL && OBJ_cmp(plgctx->id_ms_san_upn, gen->d.otherName->type_id) == 0) { /* Prevent abuse of embedded null characters. */ if (memchr(name.data, '\0', name.length)) break; ret = krb5_parse_name_flags(context, name.data, KRB5_PRINCIPAL_PARSE_ENTERPRISE, &upns[u]); if (ret) { pkiDebug("%s: failed parsing ms-upn san value\n", __FUNCTION__); } else { u++; num_found++; } } else { pkiDebug("%s: unrecognized othername oid in SAN\n", __FUNCTION__); continue; } break; case GEN_DNS: if (dnss != NULL) { /* Prevent abuse of embedded null characters. */ if (memchr(gen->d.dNSName->data, '\0', gen->d.dNSName->length)) break; pkiDebug("%s: found dns name = %s\n", __FUNCTION__, gen->d.dNSName->data); dnss[d] = (unsigned char *) strdup((char *)gen->d.dNSName->data); if (dnss[d] == NULL) { pkiDebug("%s: failed to duplicate dns name\n", __FUNCTION__); } else { d++; num_found++; } } break; default: pkiDebug("%s: SAN type = %d expecting %d\n", __FUNCTION__, gen->type, GEN_OTHERNAME); } } sk_GENERAL_NAME_pop_free(ialt, GENERAL_NAME_free); retval = 0; if (princs) *princs_ret = princs; if (upns) *upn_ret = upns; if (dnss) *dns_ret = dnss; cleanup: if (retval) { if (princs != NULL) { for (i = 0; princs[i] != NULL; i++) krb5_free_principal(context, princs[i]); free(princs); } if (upns != NULL) { for (i = 0; upns[i] != NULL; i++) krb5_free_principal(context, upns[i]); free(upns); } if (dnss != NULL) { for (i = 0; dnss[i] != NULL; i++) free(dnss[i]); free(dnss); } } return retval; } Commit Message: Fix certauth built-in module returns The PKINIT certauth eku module should never authoritatively authorize a certificate, because an extended key usage does not establish a relationship between the certificate and any specific user; it only establishes that the certificate was created for PKINIT client authentication. Therefore, pkinit_eku_authorize() should return KRB5_PLUGIN_NO_HANDLE on success, not 0. The certauth san module should pass if it does not find any SANs of the types it can match against; the presence of other types of SANs should not cause it to explicitly deny a certificate. Check for an empty result from crypto_retrieve_cert_sans() in verify_client_san(), instead of returning ENOENT from crypto_retrieve_cert_sans() when there are no SANs at all. ticket: 8561 CWE ID: CWE-287 Target: 1 Example 2: Code: int http_remove_header2(struct http_msg *msg, struct hdr_idx *idx, struct hdr_ctx *ctx) { int cur_idx = ctx->idx; char *sol = ctx->line; struct hdr_idx_elem *hdr; int delta, skip_comma; if (!cur_idx) return 0; hdr = &idx->v[cur_idx]; if (sol[ctx->del] == ':' && ctx->val + ctx->vlen + ctx->tws == hdr->len) { /* This was the only value of the header, we must now remove it entirely. */ delta = buffer_replace2(msg->chn->buf, sol, sol + hdr->len + hdr->cr + 1, NULL, 0); http_msg_move_end(msg, delta); idx->used--; hdr->len = 0; /* unused entry */ idx->v[ctx->prev].next = idx->v[ctx->idx].next; if (idx->tail == ctx->idx) idx->tail = ctx->prev; ctx->idx = ctx->prev; /* walk back to the end of previous header */ ctx->line -= idx->v[ctx->idx].len + idx->v[ctx->idx].cr + 1; ctx->val = idx->v[ctx->idx].len; /* point to end of previous header */ ctx->tws = ctx->vlen = 0; return ctx->idx; } /* This was not the only value of this header. We have to remove between * ctx->del+1 and ctx->val+ctx->vlen+ctx->tws+1 included. If it is the * last entry of the list, we remove the last separator. */ skip_comma = (ctx->val + ctx->vlen + ctx->tws == hdr->len) ? 0 : 1; delta = buffer_replace2(msg->chn->buf, sol + ctx->del + skip_comma, sol + ctx->val + ctx->vlen + ctx->tws + skip_comma, NULL, 0); hdr->len += delta; http_msg_move_end(msg, delta); ctx->val = ctx->del; ctx->tws = ctx->vlen = 0; return ctx->idx; } Commit Message: 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: DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb + tilew > imagew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } Commit Message: * tools/tiffcp.c: fix out-of-bounds write on tiled images with odd tile width vs image width. Reported as MSVR 35103 by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int __fsnotify_parent(const struct path *path, struct dentry *dentry, __u32 mask) { struct dentry *parent; struct inode *p_inode; int ret = 0; if (!dentry) dentry = path->dentry; if (!(dentry->d_flags & DCACHE_FSNOTIFY_PARENT_WATCHED)) return 0; parent = dget_parent(dentry); p_inode = parent->d_inode; if (unlikely(!fsnotify_inode_watches_children(p_inode))) __fsnotify_update_child_dentry_flags(p_inode); else if (p_inode->i_fsnotify_mask & mask) { /* we are notifying a parent so come up with the new mask which * specifies these are events which came from a child. */ mask |= FS_EVENT_ON_CHILD; if (path) ret = fsnotify(p_inode, mask, path, FSNOTIFY_EVENT_PATH, dentry->d_name.name, 0); else ret = fsnotify(p_inode, mask, dentry->d_inode, FSNOTIFY_EVENT_INODE, dentry->d_name.name, 0); } dput(parent); return ret; } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: e1000_send_packet(E1000State *s, const uint8_t *buf, int size) { if (s->phy_reg[PHY_CTRL] & MII_CR_LOOPBACK) { s->nic->nc.info->receive(&s->nic->nc, buf, size); } else { qemu_send_packet(&s->nic->nc, buf, size); } } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void IOHandler::Read( const std::string& handle, Maybe<int> offset, Maybe<int> max_size, std::unique_ptr<ReadCallback> callback) { static const size_t kDefaultChunkSize = 10 * 1024 * 1024; static const char kBlobPrefix[] = "blob:"; scoped_refptr<DevToolsIOContext::ROStream> stream = io_context_->GetByHandle(handle); if (!stream && process_host_ && StartsWith(handle, kBlobPrefix, base::CompareCase::SENSITIVE)) { BrowserContext* browser_context = process_host_->GetBrowserContext(); ChromeBlobStorageContext* blob_context = ChromeBlobStorageContext::GetFor(browser_context); StoragePartition* storage_partition = process_host_->GetStoragePartition(); std::string uuid = handle.substr(strlen(kBlobPrefix)); stream = io_context_->OpenBlob(blob_context, storage_partition, handle, uuid); } if (!stream) { callback->sendFailure(Response::InvalidParams("Invalid stream handle")); return; } stream->Read( offset.fromMaybe(-1), max_size.fromMaybe(kDefaultChunkSize), base::BindOnce(&IOHandler::ReadComplete, weak_factory_.GetWeakPtr(), base::Passed(std::move(callback)))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Browser::TabDetachedAtImpl(TabContents* contents, int index, DetachType type) { if (type == DETACH_TYPE_DETACH) { if (contents == chrome::GetActiveTabContents(this)) { LocationBar* location_bar = window()->GetLocationBar(); if (location_bar) location_bar->SaveStateToContents(contents->web_contents()); } if (!tab_strip_model_->closing_all()) SyncHistoryWithTabs(0); } SetAsDelegate(contents->web_contents(), NULL); RemoveScheduledUpdatesFor(contents->web_contents()); if (find_bar_controller_.get() && index == active_index()) { find_bar_controller_->ChangeWebContents(NULL); } search_delegate_->OnTabDetached(contents->web_contents()); registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED, content::Source<WebContents>(contents->web_contents())); registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED, content::Source<WebContents>(contents->web_contents())); } 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: 1 Example 2: Code: void ThreadHeap::InvokeEphemeronCallbacks(Visitor* visitor) { TRACE_EVENT0("blink_gc", "ThreadHeap::InvokeEphemeronCallbacks"); WTF::HashMap<void*, EphemeronCallback> iteration_set; WTF::HashMap<void*, EphemeronCallback> final_set; bool found_new = false; do { iteration_set = std::move(ephemeron_callbacks_); ephemeron_callbacks_.clear(); for (auto& tuple : iteration_set) { final_set.insert(tuple.key, tuple.value); tuple.value(visitor, tuple.key); } found_new = !ephemeron_callbacks_.IsEmpty(); } while (found_new); ephemeron_callbacks_ = std::move(final_set); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} 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: size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel) { DEBUGLOG(4, "ZSTD_initCStream"); return ZSTD_initCStream_srcSize(zcs, compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN); } Commit Message: fixed T36302429 CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RecordDailyContentLengthHistograms( int64 original_length, int64 received_length, int64 original_length_with_data_reduction_enabled, int64 received_length_with_data_reduction_enabled, int64 original_length_via_data_reduction_proxy, int64 received_length_via_data_reduction_proxy) { if (original_length <= 0 || received_length <= 0) return; UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength", original_length >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength", received_length >> 10); int percent = 0; if (original_length > received_length) { percent = (100 * (original_length - received_length)) / original_length; } UMA_HISTOGRAM_PERCENTAGE("Net.DailyContentSavingPercent", percent); if (original_length_with_data_reduction_enabled <= 0 || received_length_with_data_reduction_enabled <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_DataReductionProxyEnabled", original_length_with_data_reduction_enabled >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_DataReductionProxyEnabled", received_length_with_data_reduction_enabled >> 10); int percent_data_reduction_proxy_enabled = 0; if (original_length_with_data_reduction_enabled > received_length_with_data_reduction_enabled) { percent_data_reduction_proxy_enabled = 100 * (original_length_with_data_reduction_enabled - received_length_with_data_reduction_enabled) / original_length_with_data_reduction_enabled; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_DataReductionProxyEnabled", percent_data_reduction_proxy_enabled); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_DataReductionProxyEnabled", (100 * received_length_with_data_reduction_enabled) / received_length); if (original_length_via_data_reduction_proxy <= 0 || received_length_via_data_reduction_proxy <= 0) { return; } UMA_HISTOGRAM_COUNTS( "Net.DailyOriginalContentLength_ViaDataReductionProxy", original_length_via_data_reduction_proxy >> 10); UMA_HISTOGRAM_COUNTS( "Net.DailyContentLength_ViaDataReductionProxy", received_length_via_data_reduction_proxy >> 10); int percent_via_data_reduction_proxy = 0; if (original_length_via_data_reduction_proxy > received_length_via_data_reduction_proxy) { percent_via_data_reduction_proxy = 100 * (original_length_via_data_reduction_proxy - received_length_via_data_reduction_proxy) / original_length_via_data_reduction_proxy; } UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentSavingPercent_ViaDataReductionProxy", percent_via_data_reduction_proxy); UMA_HISTOGRAM_PERCENTAGE( "Net.DailyContentPercent_ViaDataReductionProxy", (100 * received_length_via_data_reduction_proxy) / received_length); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Target: 1 Example 2: Code: static NORETURN void die_nicely(const char *err, va_list params) { static int zombie; char message[2 * PATH_MAX]; vsnprintf(message, sizeof(message), err, params); fputs("fatal: ", stderr); fputs(message, stderr); fputc('\n', stderr); if (!zombie) { zombie = 1; write_crash_report(message); end_packfile(); unkeep_all_packs(); dump_marks(); } exit(128); } Commit Message: prefer memcpy to strcpy When we already know the length of a string (e.g., because we just malloc'd to fit it), it's nicer to use memcpy than strcpy, as it makes it more obvious that we are not going to overflow the buffer (because the size we pass matches the size in the allocation). This also eliminates calls to strcpy, which make auditing the code base harder. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[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 SyncManager::SyncInternal::OnEncryptedTypesChanged( syncable::ModelTypeSet encrypted_types, bool encrypt_everything) { FOR_EACH_OBSERVER( SyncManager::Observer, observers_, OnEncryptedTypesChanged(encrypted_types, encrypt_everything)); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int jpc_enc_encodemainhdr(jpc_enc_t *enc) { jpc_siz_t *siz; jpc_cod_t *cod; jpc_qcd_t *qcd; int i; long startoff; long mainhdrlen; jpc_enc_cp_t *cp; jpc_qcc_t *qcc; jpc_enc_tccp_t *tccp; uint_fast16_t cmptno; jpc_tsfb_band_t bandinfos[JPC_MAXBANDS]; jpc_fix_t mctsynweight; jpc_enc_tcp_t *tcp; jpc_tsfb_t *tsfb; jpc_tsfb_band_t *bandinfo; uint_fast16_t numbands; uint_fast16_t bandno; uint_fast16_t rlvlno; uint_fast16_t analgain; jpc_fix_t absstepsize; char buf[1024]; jpc_com_t *com; cp = enc->cp; startoff = jas_stream_getrwcount(enc->out); /* Write SOC marker segment. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) { return -1; } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf("cannot write SOC marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; /* Write SIZ marker segment. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) { return -1; } siz = &enc->mrk->parms.siz; siz->caps = 0; siz->xoff = cp->imgareatlx; siz->yoff = cp->imgareatly; siz->width = cp->refgrdwidth; siz->height = cp->refgrdheight; siz->tilexoff = cp->tilegrdoffx; siz->tileyoff = cp->tilegrdoffy; siz->tilewidth = cp->tilewidth; siz->tileheight = cp->tileheight; siz->numcomps = cp->numcmpts; siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)); assert(siz->comps); for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) { siz->comps[i].prec = cp->ccps[i].prec; siz->comps[i].sgnd = cp->ccps[i].sgnd; siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx; siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy; } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf("cannot write SIZ marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) { return -1; } sprintf(buf, "Creator: JasPer Version %s", jas_getversion()); com = &enc->mrk->parms.com; com->len = JAS_CAST(uint_fast16_t, strlen(buf)); com->regid = JPC_COM_LATIN; if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) { abort(); } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf("cannot write COM marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; #if 0 if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) { return -1; } crg = &enc->mrk->parms.crg; crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t)); if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf("cannot write CRG marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; #endif tcp = &cp->tcp; tccp = &cp->tccp; for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) { tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1); jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls, bandinfos); jpc_tsfb_destroy(tsfb); mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno); numbands = 3 * tccp->maxrlvls - 2; for (bandno = 0, bandinfo = bandinfos; bandno < numbands; ++bandno, ++bandinfo) { rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0; analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls, rlvlno, bandinfo->orient); if (!tcp->intmode) { absstepsize = jpc_fix_div(jpc_inttofix(1 << (analgain + 1)), bandinfo->synenergywt); } else { absstepsize = jpc_inttofix(1); } cp->ccps[cmptno].stepsizes[bandno] = jpc_abstorelstepsize(absstepsize, cp->ccps[cmptno].prec + analgain); } cp->ccps[cmptno].numstepsizes = numbands; } if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) { return -1; } cod = &enc->mrk->parms.cod; cod->csty = cp->tccp.csty | cp->tcp.csty; cod->compparms.csty = cp->tccp.csty | cp->tcp.csty; cod->compparms.numdlvls = cp->tccp.maxrlvls - 1; cod->compparms.numrlvls = cp->tccp.maxrlvls; cod->prg = cp->tcp.prg; cod->numlyrs = cp->tcp.numlyrs; cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn); cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn); cod->compparms.cblksty = cp->tccp.cblksty; cod->compparms.qmfbid = cp->tccp.qmfbid; cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE); if (tccp->csty & JPC_COX_PRT) { for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno]; cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno]; } } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf("cannot write COD marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) { return -1; } qcd = &enc->mrk->parms.qcd; qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes; qcd->compparms.numguard = cp->tccp.numgbits; qcd->compparms.stepsizes = cp->ccps[0].stepsizes; if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { return -1; } /* We do not want the step size array to be freed! */ qcd->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; tccp = &cp->tccp; for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) { if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) { return -1; } qcc = &enc->mrk->parms.qcc; qcc->compno = cmptno; qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes; qcc->compparms.numguard = cp->tccp.numgbits; qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes; if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { return -1; } /* We do not want the step size array to be freed! */ qcc->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; } #define MAINTLRLEN 2 mainhdrlen = jas_stream_getrwcount(enc->out) - startoff; enc->len += mainhdrlen; if (enc->cp->totalsize != UINT_FAST32_MAX) { uint_fast32_t overhead; overhead = mainhdrlen + MAINTLRLEN; enc->mainbodysize = (enc->cp->totalsize >= overhead) ? (enc->cp->totalsize - overhead) : 0; } else { enc->mainbodysize = UINT_FAST32_MAX; } return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Target: 1 Example 2: Code: DOMFeaturePolicy* Document::featurePolicy() { if (!policy_) policy_ = MakeGarbageCollected<DocumentPolicy>(this); return policy_.Get(); } Commit Message: Cleanup and remove dead code in SetFocusedElement This early-out was added in: https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc Back then, we applied fragment focus in LayoutUpdated() which could cause this issue. This got cleaned up in: https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2 so that focus is no longer applied after layout. +Cleanup: Goto considered harmful Bug: 795381 Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417 Commit-Queue: David Bokan <[email protected]> Reviewed-by: Stefan Zager <[email protected]> Cr-Commit-Position: refs/heads/master@{#641101} 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: struct dst_entry *inet_csk_route_req(struct sock *sk, const struct request_sock *req) { struct rtable *rt; const struct inet_request_sock *ireq = inet_rsk(req); struct ip_options *opt = inet_rsk(req)->opt; struct net *net = sock_net(sk); struct flowi4 fl4; flowi4_init_output(&fl4, sk->sk_bound_dev_if, sk->sk_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, sk->sk_protocol, inet_sk_flowi_flags(sk), (opt && opt->srr) ? opt->faddr : ireq->rmt_addr, ireq->loc_addr, ireq->rmt_port, inet_sk(sk)->inet_sport); security_req_classify_flow(req, flowi4_to_flowi(&fl4)); rt = ip_route_output_flow(net, &fl4, sk); if (IS_ERR(rt)) goto no_route; if (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway) goto route_err; return &rt->dst; route_err: ip_rt_put(rt); no_route: IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES); return NULL; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: dissect_ppi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { proto_tree *ppi_tree = NULL, *ppi_flags_tree = NULL, *seg_tree = NULL, *ampdu_tree = NULL; proto_tree *agg_tree = NULL; proto_item *ti = NULL; tvbuff_t *next_tvb; int offset = 0; guint version, flags; gint tot_len, data_len; guint data_type; guint32 dlt; guint32 n_ext_flags = 0; guint32 ampdu_id = 0; fragment_head *fd_head = NULL; fragment_item *ft_fdh = NULL; gint mpdu_count = 0; gchar *mpdu_str; gboolean first_mpdu = TRUE; guint last_frame = 0; gint len_remain, /*pad_len = 0,*/ ampdu_len = 0; struct ieee_802_11_phdr phdr; col_set_str(pinfo->cinfo, COL_PROTOCOL, "PPI"); col_clear(pinfo->cinfo, COL_INFO); version = tvb_get_guint8(tvb, offset); flags = tvb_get_guint8(tvb, offset + 1); tot_len = tvb_get_letohs(tvb, offset+2); dlt = tvb_get_letohl(tvb, offset+4); col_add_fstr(pinfo->cinfo, COL_INFO, "PPI version %u, %u bytes", version, tot_len); /* Dissect the packet */ if (tree) { ti = proto_tree_add_protocol_format(tree, proto_ppi, tvb, 0, tot_len, "PPI version %u, %u bytes", version, tot_len); ppi_tree = proto_item_add_subtree(ti, ett_ppi_pph); proto_tree_add_item(ppi_tree, hf_ppi_head_version, tvb, offset, 1, ENC_LITTLE_ENDIAN); ti = proto_tree_add_item(ppi_tree, hf_ppi_head_flags, tvb, offset + 1, 1, ENC_LITTLE_ENDIAN); ppi_flags_tree = proto_item_add_subtree(ti, ett_ppi_flags); proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_alignment, tvb, offset + 1, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_reserved, tvb, offset + 1, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(ppi_tree, hf_ppi_head_len, tvb, offset + 2, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(ppi_tree, hf_ppi_head_dlt, tvb, offset + 4, 4, ENC_LITTLE_ENDIAN); } tot_len -= PPI_V0_HEADER_LEN; offset += 8; /* We don't have any 802.11 metadata yet. */ memset(&phdr, 0, sizeof(phdr)); phdr.fcs_len = -1; phdr.decrypted = FALSE; phdr.datapad = FALSE; phdr.phy = PHDR_802_11_PHY_UNKNOWN; phdr.presence_flags = 0; while (tot_len > 0) { data_type = tvb_get_letohs(tvb, offset); data_len = tvb_get_letohs(tvb, offset + 2) + 4; tot_len -= data_len; switch (data_type) { case PPI_80211_COMMON: dissect_80211_common(tvb, pinfo, ppi_tree, offset, data_len, &phdr); break; case PPI_80211N_MAC: dissect_80211n_mac(tvb, pinfo, ppi_tree, offset, data_len, TRUE, &n_ext_flags, &ampdu_id, &phdr); break; case PPI_80211N_MAC_PHY: dissect_80211n_mac_phy(tvb, pinfo, ppi_tree, offset, data_len, &n_ext_flags, &ampdu_id, &phdr); break; case PPI_SPECTRUM_MAP: ADD_BASIC_TAG(hf_spectrum_map); break; case PPI_PROCESS_INFO: ADD_BASIC_TAG(hf_process_info); break; case PPI_CAPTURE_INFO: ADD_BASIC_TAG(hf_capture_info); break; case PPI_AGGREGATION_EXTENSION: dissect_aggregation_extension(tvb, pinfo, ppi_tree, offset, data_len); break; case PPI_8023_EXTENSION: dissect_8023_extension(tvb, pinfo, ppi_tree, offset, data_len); break; case PPI_GPS_INFO: if (ppi_gps_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_gps, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated GPS dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_gps_handle, next_tvb, pinfo, ppi_tree); } break; case PPI_VECTOR_INFO: if (ppi_vector_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_vector, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated VECTOR dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_vector_handle, next_tvb, pinfo, ppi_tree); } break; case PPI_SENSOR_INFO: if (ppi_sensor_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_harris, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated SENSOR dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_sensor_handle, next_tvb, pinfo, ppi_tree); } break; case PPI_ANTENNA_INFO: if (ppi_antenna_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_antenna, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated ANTENNA dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_antenna_handle, next_tvb, pinfo, ppi_tree); } break; case FNET_PRIVATE: if (ppi_fnet_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_fnet, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated FNET dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_fnet_handle, next_tvb, pinfo, ppi_tree); } break; default: proto_tree_add_item(ppi_tree, hf_ppi_reserved, tvb, offset, data_len, ENC_NA); } offset += data_len; if (IS_PPI_FLAG_ALIGN(flags)){ offset += PADDING4(offset); } } if (ppi_ampdu_reassemble && DOT11N_IS_AGGREGATE(n_ext_flags)) { len_remain = tvb_captured_length_remaining(tvb, offset); #if 0 /* XXX: pad_len never actually used ?? */ if (DOT11N_MORE_AGGREGATES(n_ext_flags)) { pad_len = PADDING4(len_remain); } #endif pinfo->fragmented = TRUE; /* Make sure we aren't going to go past AGGREGATE_MAX * and caclulate our full A-MPDU length */ fd_head = fragment_get(&ampdu_reassembly_table, pinfo, ampdu_id, NULL); while (fd_head) { ampdu_len += fd_head->len + PADDING4(fd_head->len) + 4; fd_head = fd_head->next; } if (ampdu_len > AGGREGATE_MAX) { if (tree) { proto_tree_add_expert_format(ppi_tree, pinfo, &ei_ppi_invalid_length, tvb, offset, -1, "Aggregate length greater than maximum (%u)", AGGREGATE_MAX); THROW(ReportedBoundsError); } else { return; } } /* * Note that we never actually reassemble our A-MPDUs. Doing * so would require prepending each MPDU with an A-MPDU delimiter * and appending it with padding, only to hand it off to some * routine which would un-do the work we just did. We're using * the reassembly code to track MPDU sizes and frame numbers. */ /*??fd_head = */fragment_add_seq_next(&ampdu_reassembly_table, tvb, offset, pinfo, ampdu_id, NULL, len_remain, TRUE); pinfo->fragmented = TRUE; /* Do reassembly? */ fd_head = fragment_get(&ampdu_reassembly_table, pinfo, ampdu_id, NULL); /* Show our fragments */ if (fd_head && tree) { ft_fdh = fd_head; /* List our fragments */ seg_tree = proto_tree_add_subtree_format(ppi_tree, tvb, offset, -1, ett_ampdu_segments, &ti, "A-MPDU (%u bytes w/hdrs):", ampdu_len); PROTO_ITEM_SET_GENERATED(ti); while (ft_fdh) { if (ft_fdh->tvb_data && ft_fdh->len) { last_frame = ft_fdh->frame; if (!first_mpdu) proto_item_append_text(ti, ","); first_mpdu = FALSE; proto_item_append_text(ti, " #%u(%u)", ft_fdh->frame, ft_fdh->len); proto_tree_add_uint_format(seg_tree, hf_ampdu_segment, tvb, 0, 0, last_frame, "Frame: %u (%u byte%s)", last_frame, ft_fdh->len, plurality(ft_fdh->len, "", "s")); } ft_fdh = ft_fdh->next; } if (last_frame && last_frame != pinfo->fd->num) proto_tree_add_uint(seg_tree, hf_ampdu_reassembled_in, tvb, 0, 0, last_frame); } if (fd_head && !DOT11N_MORE_AGGREGATES(n_ext_flags)) { if (tree) { ti = proto_tree_add_protocol_format(tree, proto_get_id_by_filter_name("wlan_aggregate"), tvb, 0, tot_len, "IEEE 802.11 Aggregate MPDU"); agg_tree = proto_item_add_subtree(ti, ett_ampdu); } while (fd_head) { if (fd_head->tvb_data && fd_head->len) { mpdu_count++; mpdu_str = wmem_strdup_printf(wmem_packet_scope(), "MPDU #%d", mpdu_count); next_tvb = tvb_new_chain(tvb, fd_head->tvb_data); add_new_data_source(pinfo, next_tvb, mpdu_str); ampdu_tree = proto_tree_add_subtree(agg_tree, next_tvb, 0, -1, ett_ampdu_segment, NULL, mpdu_str); call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, ampdu_tree, &phdr); } fd_head = fd_head->next; } proto_tree_add_uint(seg_tree, hf_ampdu_count, tvb, 0, 0, mpdu_count); pinfo->fragmented=FALSE; } else { next_tvb = tvb_new_subset_remaining(tvb, offset); col_set_str(pinfo->cinfo, COL_PROTOCOL, "IEEE 802.11n"); col_set_str(pinfo->cinfo, COL_INFO, "Unreassembled A-MPDU data"); call_dissector(data_handle, next_tvb, pinfo, tree); } return; } next_tvb = tvb_new_subset_remaining(tvb, offset); /* * You can't just call an arbitrary subdissector based on a * LINKTYPE_ value, because they may expect a particular * pseudo-header to be passed to them. * * So we look for LINKTYPE_IEEE802_11, which is 105, and, if * that's what the LINKTYPE_ value is, pass it a pointer * to a struct ieee_802_11_phdr; otherwise, we pass it * a null pointer - if it actually matters, we need to * construct the appropriate pseudo-header and pass that. */ if (dlt == 105) { /* LINKTYPE_IEEE802_11 */ call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, tree, &phdr); } else { /* Everything else. This will pass a NULL data argument. */ dissector_try_uint(wtap_encap_dissector_table, wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree); } } Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr. We now require that. Make it so. Bug: 12440 Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76 Reviewed-on: https://code.wireshark.org/review/15424 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: status_t Camera3Device::setStreamTransform(int id, int transform) { ATRACE_CALL(); Mutex::Autolock il(mInterfaceLock); Mutex::Autolock l(mLock); switch (mStatus) { case STATUS_ERROR: CLOGE("Device has encountered a serious error"); return INVALID_OPERATION; case STATUS_UNINITIALIZED: CLOGE("Device not initialized"); return INVALID_OPERATION; case STATUS_UNCONFIGURED: case STATUS_CONFIGURED: case STATUS_ACTIVE: break; default: SET_ERR_L("Unexpected status: %d", mStatus); return INVALID_OPERATION; } ssize_t idx = mOutputStreams.indexOfKey(id); if (idx == NAME_NOT_FOUND) { CLOGE("Stream %d does not exist", id); return BAD_VALUE; } return mOutputStreams.editValueAt(idx)->setTransform(transform); } 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: int kvm_available(void) { #ifdef CONFIG_KVM return 1; #else return 0; #endif } 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: static void *etm_setup_aux(int event_cpu, void **pages, int nr_pages, bool overwrite) { int cpu; cpumask_t *mask; struct coresight_device *sink; struct etm_event_data *event_data = NULL; event_data = alloc_event_data(event_cpu); if (!event_data) return NULL; /* * In theory nothing prevent tracers in a trace session from being * associated with different sinks, nor having a sink per tracer. But * until we have HW with this kind of topology we need to assume tracers * in a trace session are using the same sink. Therefore go through * the coresight bus and pick the first enabled sink. * * When operated from sysFS users are responsible to enable the sink * while from perf, the perf tools will do it based on the choice made * on the cmd line. As such the "enable_sink" flag in sysFS is reset. */ sink = coresight_get_enabled_sink(true); if (!sink) goto err; INIT_WORK(&event_data->work, free_event_data); mask = &event_data->mask; /* Setup the path for each CPU in a trace session */ for_each_cpu(cpu, mask) { struct coresight_device *csdev; csdev = per_cpu(csdev_src, cpu); if (!csdev) goto err; /* * Building a path doesn't enable it, it simply builds a * list of devices from source to sink that can be * referenced later when the path is actually needed. */ event_data->path[cpu] = coresight_build_path(csdev, sink); if (IS_ERR(event_data->path[cpu])) goto err; } if (!sink_ops(sink)->alloc_buffer) goto err; /* Get the AUX specific data from the sink buffer */ event_data->snk_config = sink_ops(sink)->alloc_buffer(sink, cpu, pages, nr_pages, overwrite); if (!event_data->snk_config) goto err; out: return event_data; err: etm_free_aux(event_data); event_data = NULL; goto out; } Commit Message: coresight: fix kernel panic caused by invalid CPU Commit d52c9750f150 ("coresight: reset "enable_sink" flag when need be") caused a kernel panic because of the using of an invalid value: after 'for_each_cpu(cpu, mask)', value of local variable 'cpu' become invalid, causes following 'cpu_to_node' access invalid memory area. This patch brings the deleted 'cpu = cpumask_first(mask)' back. Panic log: $ perf record -e cs_etm// ls Unable to handle kernel paging request at virtual address fffe801804af4f10 pgd = ffff8017ce031600 [fffe801804af4f10] *pgd=0000000000000000, *pud=0000000000000000 Internal error: Oops: 96000004 [#1] SMP Modules linked in: CPU: 33 PID: 1619 Comm: perf Not tainted 4.7.1+ #16 Hardware name: Huawei Taishan 2280 /CH05TEVBA, BIOS 1.10 11/24/2016 task: ffff8017cb0c8400 ti: ffff8017cb154000 task.ti: ffff8017cb154000 PC is at tmc_alloc_etf_buffer+0x60/0xd4 LR is at tmc_alloc_etf_buffer+0x44/0xd4 pc : [<ffff000008633df8>] lr : [<ffff000008633ddc>] pstate: 60000145 sp : ffff8017cb157b40 x29: ffff8017cb157b40 x28: 0000000000000000 ...skip... 7a60: ffff000008c64dc8 0000000000000006 0000000000000253 ffffffffffffffff 7a80: 0000000000000000 0000000000000000 ffff0000080872cc 0000000000000001 [<ffff000008633df8>] tmc_alloc_etf_buffer+0x60/0xd4 [<ffff000008632b9c>] etm_setup_aux+0x1dc/0x1e8 [<ffff00000816eed4>] rb_alloc_aux+0x2b0/0x338 [<ffff00000816a5e4>] perf_mmap+0x414/0x568 [<ffff0000081ab694>] mmap_region+0x324/0x544 [<ffff0000081abbe8>] do_mmap+0x334/0x3e0 [<ffff000008191150>] vm_mmap_pgoff+0xa4/0xc8 [<ffff0000081a9a30>] SyS_mmap_pgoff+0xb0/0x22c [<ffff0000080872e4>] sys_mmap+0x18/0x28 [<ffff0000080843f0>] el0_svc_naked+0x24/0x28 Code: 912040a5 d0001c00 f873d821 911c6000 (b8656822) ---[ end trace 98933da8f92b0c9a ]--- Signed-off-by: Wang Nan <[email protected]> Cc: Xia Kaixu <[email protected]> Cc: Li Zefan <[email protected]> Cc: Mathieu Poirier <[email protected]> Cc: [email protected] Cc: [email protected] Fixes: d52c9750f150 ("coresight: reset "enable_sink" flag when need be") Signed-off-by: Mathieu Poirier <[email protected]> Cc: stable <[email protected]> # 4.10 Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: RedChannel *red_channel_create(int size, SpiceCoreInterface *core, uint32_t type, uint32_t id, int handle_acks, channel_handle_message_proc handle_message, ChannelCbs *channel_cbs, uint32_t migration_flags) { RedChannel *channel; ClientCbs client_cbs = { NULL, }; spice_assert(size >= sizeof(*channel)); spice_assert(channel_cbs->config_socket && channel_cbs->on_disconnect && handle_message && channel_cbs->alloc_recv_buf && channel_cbs->release_item); spice_assert(channel_cbs->handle_migrate_data || !(migration_flags & SPICE_MIGRATE_NEED_DATA_TRANSFER)); channel = spice_malloc0(size); channel->type = type; channel->id = id; channel->refs = 1; channel->handle_acks = handle_acks; channel->migration_flags = migration_flags; memcpy(&channel->channel_cbs, channel_cbs, sizeof(ChannelCbs)); channel->core = core; ring_init(&channel->clients); channel->incoming_cb.alloc_msg_buf = (alloc_msg_recv_buf_proc)channel_cbs->alloc_recv_buf; channel->incoming_cb.release_msg_buf = (release_msg_recv_buf_proc)channel_cbs->release_recv_buf; channel->incoming_cb.handle_message = (handle_message_proc)handle_message; channel->incoming_cb.on_error = (on_incoming_error_proc)red_channel_client_default_peer_on_error; channel->outgoing_cb.get_msg_size = red_channel_client_peer_get_out_msg_size; channel->outgoing_cb.prepare = red_channel_client_peer_prepare_out_msg; channel->outgoing_cb.on_block = red_channel_client_peer_on_out_block; channel->outgoing_cb.on_error = (on_outgoing_error_proc)red_channel_client_default_peer_on_error; channel->outgoing_cb.on_msg_done = red_channel_peer_on_out_msg_done; channel->outgoing_cb.on_output = red_channel_client_on_output; client_cbs.connect = red_channel_client_default_connect; client_cbs.disconnect = red_channel_client_default_disconnect; client_cbs.migrate = red_channel_client_default_migrate; red_channel_register_client_cbs(channel, &client_cbs); red_channel_set_common_cap(channel, SPICE_COMMON_CAP_MINI_HEADER); channel->thread_id = pthread_self(); channel->out_bytes_counter = 0; spice_debug("channel type %d id %d thread_id 0x%lx", channel->type, channel->id, channel->thread_id); return channel; } 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: void ipc_rcu_putref(void *ptr) { if (--container_of(ptr, struct ipc_rcu_hdr, data)->refcount > 0) return; if (container_of(ptr, struct ipc_rcu_hdr, data)->is_vmalloc) { call_rcu(&container_of(ptr, struct ipc_rcu_grace, data)->rcu, ipc_schedule_free); } else { kfree_rcu(container_of(ptr, struct ipc_rcu_grace, data), rcu); } } Commit Message: ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> 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: jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { return 0; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = numrows * numcols; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_, sizeof(jas_seqent_t *)))) { jas_matrix_destroy(matrix); return 0; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_alloc2(matrix->datasize_, sizeof(jas_seqent_t)))) { jas_matrix_destroy(matrix); return 0; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; } Commit Message: Fixed a problem with a null pointer dereference in the BMP decoder. CWE ID: CWE-476 Target: 1 Example 2: Code: void ACodec::signalSetParameters(const sp<AMessage> &params) { sp<AMessage> msg = new AMessage(kWhatSetParameters, this); msg->setMessage("params", params); msg->post(); } Commit Message: Fix initialization of AAC presentation struct Otherwise the new size checks trip on this. Bug: 27207275 Change-Id: I1f8f01097e3a88ff041b69279a6121be842f1766 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 RList *maps(RBinFile *bf) { if (bf && bf->o) { return Elf_(r_bin_elf_get_maps)(bf->o->bin_obj); } return NULL; } Commit Message: Fix #9904 - crash in r2_hoobr_r_read_le32 (over 9000 entrypoints) and read_le oobread (#9923) 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: SyncType GetSyncType(const Extension* extension) { if (!IsSyncable(extension)) { return SYNC_TYPE_NONE; } if (!ManifestURL::GetUpdateURL(extension).is_empty() && !ManifestURL::UpdatesFromGallery(extension)) { return SYNC_TYPE_NONE; } if (PluginInfo::HasPlugins(extension)) return SYNC_TYPE_NONE; switch (extension->GetType()) { case Manifest::TYPE_EXTENSION: return SYNC_TYPE_EXTENSION; case Manifest::TYPE_USER_SCRIPT: if (ManifestURL::UpdatesFromGallery(extension)) return SYNC_TYPE_EXTENSION; return SYNC_TYPE_NONE; case Manifest::TYPE_HOSTED_APP: case Manifest::TYPE_LEGACY_PACKAGED_APP: case Manifest::TYPE_PLATFORM_APP: return SYNC_TYPE_APP; case Manifest::TYPE_UNKNOWN: case Manifest::TYPE_THEME: case Manifest::TYPE_SHARED_MODULE: return SYNC_TYPE_NONE; } NOTREACHED(); return SYNC_TYPE_NONE; } Commit Message: Fix syncing of NPAPI plugins. This fix adds a check for |plugin| permission while syncing NPAPI plugins. BUG=252034 Review URL: https://chromiumcodereview.appspot.com/16816024 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207830 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: static ssize_t debug_cow_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return single_flag_show(kobj, attr, buf, TRANSPARENT_HUGEPAGE_DEBUG_COW_FLAG); } Commit Message: mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups The huge_memory.c THP page fault was allowed to run if vm_ops was null (which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't setup a special vma->vm_ops and it would fallback to regular anonymous memory) but other THP logics weren't fully activated for vmas with vm_file not NULL (/dev/zero has a not NULL vma->vm_file). So this removes the vm_file checks so that /dev/zero also can safely use THP (the other albeit safer approach to fix this bug would have been to prevent the THP initial page fault to run if vm_file was set). After removing the vm_file checks, this also makes huge_memory.c stricter in khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file check with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP under VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should only be allowed to exist before the first page fault, and in turn when vma->anon_vma is null (so preventing khugepaged registration). So I tend to think the previous comment saying if vm_file was set, VM_PFNMAP might have been set and we could still be registered in khugepaged (despite anon_vma was not NULL to be registered in khugepaged) was too paranoid. The is_linear_pfn_mapping check is also I think superfluous (as described by comment) but under DEBUG_VM it is safe to stay. Addresses https://bugzilla.kernel.org/show_bug.cgi?id=33682 Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Caspar Zhang <[email protected]> Acked-by: Mel Gorman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: <[email protected]> [2.6.38.x] Signed-off-by: Andrew Morton <[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: bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index, struct drm_display_mode *mode) { struct radeon_mode_info *mode_info = &rdev->mode_info; ATOM_ANALOG_TV_INFO *tv_info; ATOM_ANALOG_TV_INFO_V1_2 *tv_info_v1_2; ATOM_DTD_FORMAT *dtd_timings; int data_index = GetIndexIntoMasterTable(DATA, AnalogTV_Info); u8 frev, crev; u16 data_offset, misc; if (!atom_parse_data_header(mode_info->atom_context, data_index, NULL, &frev, &crev, &data_offset)) return false; switch (crev) { case 1: tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset); if (index > MAX_SUPPORTED_TV_TIMING) return false; mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total); mode->crtc_hdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Disp); mode->crtc_hsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart); mode->crtc_hsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart) + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncWidth); mode->crtc_vtotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Total); mode->crtc_vdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Disp); mode->crtc_vsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart); mode->crtc_vsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart) + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncWidth); mode->flags = 0; misc = le16_to_cpu(tv_info->aModeTimings[index].susModeMiscInfo.usAccess); if (misc & ATOM_VSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NVSYNC; if (misc & ATOM_HSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NHSYNC; if (misc & ATOM_COMPOSITESYNC) mode->flags |= DRM_MODE_FLAG_CSYNC; if (misc & ATOM_INTERLACE) mode->flags |= DRM_MODE_FLAG_INTERLACE; if (misc & ATOM_DOUBLE_CLOCK_MODE) mode->flags |= DRM_MODE_FLAG_DBLSCAN; mode->clock = le16_to_cpu(tv_info->aModeTimings[index].usPixelClock) * 10; if (index == 1) { /* PAL timings appear to have wrong values for totals */ mode->crtc_htotal -= 1; mode->crtc_vtotal -= 1; } break; case 2: tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset); if (index > MAX_SUPPORTED_TV_TIMING_V1_2) return false; dtd_timings = &tv_info_v1_2->aModeTimings[index]; mode->crtc_htotal = le16_to_cpu(dtd_timings->usHActive) + le16_to_cpu(dtd_timings->usHBlanking_Time); mode->crtc_hdisplay = le16_to_cpu(dtd_timings->usHActive); mode->crtc_hsync_start = le16_to_cpu(dtd_timings->usHActive) + le16_to_cpu(dtd_timings->usHSyncOffset); mode->crtc_hsync_end = mode->crtc_hsync_start + le16_to_cpu(dtd_timings->usHSyncWidth); mode->crtc_vtotal = le16_to_cpu(dtd_timings->usVActive) + le16_to_cpu(dtd_timings->usVBlanking_Time); mode->crtc_vdisplay = le16_to_cpu(dtd_timings->usVActive); mode->crtc_vsync_start = le16_to_cpu(dtd_timings->usVActive) + le16_to_cpu(dtd_timings->usVSyncOffset); mode->crtc_vsync_end = mode->crtc_vsync_start + le16_to_cpu(dtd_timings->usVSyncWidth); mode->flags = 0; misc = le16_to_cpu(dtd_timings->susModeMiscInfo.usAccess); if (misc & ATOM_VSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NVSYNC; if (misc & ATOM_HSYNC_POLARITY) mode->flags |= DRM_MODE_FLAG_NHSYNC; if (misc & ATOM_COMPOSITESYNC) mode->flags |= DRM_MODE_FLAG_CSYNC; if (misc & ATOM_INTERLACE) mode->flags |= DRM_MODE_FLAG_INTERLACE; if (misc & ATOM_DOUBLE_CLOCK_MODE) mode->flags |= DRM_MODE_FLAG_DBLSCAN; mode->clock = le16_to_cpu(dtd_timings->usPixClk) * 10; break; } return true; } Commit Message: drivers/gpu/drm/radeon/radeon_atombios.c: range check issues This change makes the array larger, "MAX_SUPPORTED_TV_TIMING_V1_2" is 3 and the original size "MAX_SUPPORTED_TV_TIMING" is 2. Also there were checks that were off by one. Signed-off-by: Dan Carpenter <[email protected]> Acked-by: Alex Deucher <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Dave Airlie <[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: status_t SoundTriggerHwService::Module::startRecognition(sound_model_handle_t handle, const sp<IMemory>& dataMemory) { ALOGV("startRecognition() model handle %d", handle); if (!captureHotwordAllowed()) { return PERMISSION_DENIED; } if (dataMemory != 0 && dataMemory->pointer() == NULL) { ALOGE("startRecognition() dataMemory is non-0 but has NULL pointer()"); return BAD_VALUE; } AutoMutex lock(mLock); if (mServiceState == SOUND_TRIGGER_STATE_DISABLED) { return INVALID_OPERATION; } sp<Model> model = getModel(handle); if (model == 0) { return BAD_VALUE; } if ((dataMemory == 0) || (dataMemory->size() < sizeof(struct sound_trigger_recognition_config))) { return BAD_VALUE; } if (model->mState == Model::STATE_ACTIVE) { return INVALID_OPERATION; } struct sound_trigger_recognition_config *config = (struct sound_trigger_recognition_config *)dataMemory->pointer(); config->capture_handle = model->mCaptureIOHandle; config->capture_device = model->mCaptureDevice; status_t status = mHwDevice->start_recognition(mHwDevice, handle, config, SoundTriggerHwService::recognitionCallback, this); if (status == NO_ERROR) { model->mState = Model::STATE_ACTIVE; model->mConfig = *config; } return status; } Commit Message: soundtrigger: add size check on sound model and recogntion data Bug: 30148546 Change-Id: I082f535a853c96571887eeea37c6d41ecee7d8c0 (cherry picked from commit bb00d8f139ff51336ab3c810d35685003949bcf8) (cherry picked from commit ef0c91518446e65533ca8bab6726a845f27c73fd) CWE ID: CWE-264 Target: 1 Example 2: Code: static inline bool hasOneTextChild(ContainerNode* node) { return hasOneChild(node) && node->firstChild()->isTextNode(); } Commit Message: There are too many poorly named functions to create a fragment from markup https://bugs.webkit.org/show_bug.cgi?id=87339 Reviewed by Eric Seidel. Source/WebCore: Moved all functions that create a fragment from markup to markup.h/cpp. There should be no behavioral change. * dom/Range.cpp: (WebCore::Range::createContextualFragment): * dom/Range.h: Removed createDocumentFragmentForElement. * dom/ShadowRoot.cpp: (WebCore::ShadowRoot::setInnerHTML): * editing/markup.cpp: (WebCore::createFragmentFromMarkup): (WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource. (WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor. (WebCore::removeElementPreservingChildren): Moved from Range. (WebCore::createContextualFragment): Ditto. * editing/markup.h: * html/HTMLElement.cpp: (WebCore::HTMLElement::setInnerHTML): (WebCore::HTMLElement::setOuterHTML): (WebCore::HTMLElement::insertAdjacentHTML): * inspector/DOMPatchSupport.cpp: (WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using one of the functions listed in markup.h * xml/XSLTProcessor.cpp: (WebCore::XSLTProcessor::transformToFragment): Source/WebKit/qt: Replace calls to Range::createDocumentFragmentForElement by calls to createContextualDocumentFragment. * Api/qwebelement.cpp: (QWebElement::appendInside): (QWebElement::prependInside): (QWebElement::prependOutside): (QWebElement::appendOutside): (QWebElement::encloseContentsWith): (QWebElement::encloseWith): git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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 bool deadtime_fn(const struct timeval *now, void *private_data) { struct smbd_server_connection *sconn = smbd_server_conn; if ((conn_num_open(sconn) == 0) || (conn_idle_all(sconn, now->tv_sec))) { DEBUG( 2, ( "Closing idle connection\n" ) ); messaging_send(smbd_messaging_context(), procid_self(), MSG_SHUTDOWN, &data_blob_null); return False; } return True; } Commit Message: 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 DownloadRequestLimiter::TabDownloadState::DidStartNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->IsInMainFrame()) return; download_seen_ = false; ui_status_ = DOWNLOAD_UI_DEFAULT; if (navigation_handle->IsRendererInitiated() && (status_ == PROMPT_BEFORE_DOWNLOAD || status_ == DOWNLOADS_NOT_ALLOWED)) { return; } if (status_ == DownloadRequestLimiter::ALLOW_ALL_DOWNLOADS || status_ == DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED) { if (!initial_page_host_.empty() && navigation_handle->GetURL().host_piece() == initial_page_host_) { return; } } NotifyCallbacks(false); host_->Remove(this, web_contents()); } Commit Message: Don't reset TabDownloadState on history back/forward Currently performing forward/backward on a tab will reset the TabDownloadState. Which allows javascript code to do trigger multiple downloads. This CL disables that behavior by not resetting the TabDownloadState on forward/back. It is still possible to reset the TabDownloadState through user gesture or using browser initiated download. BUG=848535 Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863 Reviewed-on: https://chromium-review.googlesource.com/1108959 Commit-Queue: Min Qin <[email protected]> Reviewed-by: Xing Liu <[email protected]> Cr-Commit-Position: refs/heads/master@{#574437} CWE ID: Target: 1 Example 2: Code: static int x509_crt_verify_child( mbedtls_x509_crt *child, mbedtls_x509_crt *parent, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, int path_cnt, int self_cnt, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { int ret; uint32_t parent_flags = 0; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; mbedtls_x509_crt *grandparent; const mbedtls_md_info_t *md_info; /* Counting intermediate self signed certificates */ if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) self_cnt++; /* path_cnt is 0 for the first intermediate CA */ if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); } if( mbedtls_x509_time_is_past( &child->valid_to ) ) *flags |= MBEDTLS_X509_BADCERT_EXPIRED; if( mbedtls_x509_time_is_future( &child->valid_from ) ) *flags |= MBEDTLS_X509_BADCERT_FUTURE; if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_MD; if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_PK; md_info = mbedtls_md_info_from_type( child->sig_md ); if( md_info == NULL ) { /* * Cannot check 'unknown' hash */ *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; } else { mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ); if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, child->sig_md, hash, mbedtls_md_get_size( md_info ), child->sig.p, child->sig.len ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; } } #if defined(MBEDTLS_X509_CRL_PARSE_C) /* Check trusted CA's CRL for the given crt */ *flags |= x509_crt_verifycrl(child, parent, ca_crl, profile ); #endif /* Look for a grandparent in trusted CAs */ for( grandparent = trust_ca; grandparent != NULL; grandparent = grandparent->next ) { if( x509_crt_check_parent( parent, grandparent, 0, path_cnt == 0 ) == 0 ) break; } if( grandparent != NULL ) { ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { /* Look for a grandparent upwards the chain */ for( grandparent = parent->next; grandparent != NULL; grandparent = grandparent->next ) { /* +2 because the current step is not yet accounted for * and because max_pathlen is one higher than it should be. * Also self signed certificates do not count to the limit. */ if( grandparent->max_pathlen > 0 && grandparent->max_pathlen < 2 + path_cnt - self_cnt ) { continue; } if( x509_crt_check_parent( parent, grandparent, 0, path_cnt == 0 ) == 0 ) break; } /* Is our parent part of the chain or at the top? */ if( grandparent != NULL ) { ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile, path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } } /* child is verified to be a child of the parent, call verify callback */ if( NULL != f_vrfy ) if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 ) return( ret ); *flags |= parent_flags; return( 0 ); } Commit Message: Improve behaviour on fatal errors If we didn't walk the whole chain, then there may be any kind of errors in the part of the chain we didn't check, so setting all flags looks like the safe thing to do. CWE ID: CWE-287 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: BaseShadow::BaseShadow() { spool = NULL; fsDomain = uidDomain = NULL; jobAd = NULL; remove_requested = false; cluster = proc = -1; gjid = NULL; core_file_name = NULL; scheddAddr = NULL; job_updater = NULL; ASSERT( !myshadow_ptr ); // make cetain we're only instantiated once myshadow_ptr = this; exception_already_logged = false; began_execution = FALSE; reconnect_e_factor = 0.0; reconnect_ceiling = 300; prev_run_bytes_sent = 0.0; prev_run_bytes_recvd = 0.0; m_num_cleanup_retries = 0; m_max_cleanup_retries = 5; m_lazy_queue_update = true; m_cleanup_retry_tid = -1; m_cleanup_retry_delay = 30; m_RunAsNobody = false; } Commit Message: CWE ID: CWE-134 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 WebMediaPlayerMS::DidPassCORSAccessCheck() const { DCHECK(thread_checker_.CalledOnValidThread()); return true; } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Target: 1 Example 2: Code: void Layer::ClearRenderSurface() { draw_properties_.render_surface.reset(); } Commit Message: Removed pinch viewport scroll offset distribution The associated change in Blink makes the pinch viewport a proper ScrollableArea meaning the normal path for synchronizing layer scroll offsets is used. This is a 2 sided patch, the other CL: https://codereview.chromium.org/199253002/ BUG=349941 Review URL: https://codereview.chromium.org/210543002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260105 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct sock *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq; struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif struct flowi6 fl6; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (!newsk) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } ireq = inet_rsk(req); if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; __ip6_dst_store(newsk, dst, NULL, NULL); inet6_sk_rx_dst_set(newsk, skb); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ if (np->opt) newnp->opt = ipv6_dup_options(newsk, np->opt); inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newnp->opt) inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen + newnp->opt->opt_flen); tcp_ca_openreq_child(newsk, dst); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = dst_metric_advmss(dst); if (tcp_sk(sk)->rx_opt.user_mss && tcp_sk(sk)->rx_opt.user_mss < newtp->advmss) newtp->advmss = tcp_sk(sk)->rx_opt.user_mss; tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr); if (key) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr, AF_INET6, key->key, key->keylen, sk_gfp_atomic(sk, GFP_ATOMIC)); } #endif if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); tcp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); if (*own_req) { tcp_move_syn(newtp, req); /* Clone pktoptions received with SYN, if we own the req */ if (ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, sk_gfp_atomic(sk, GFP_ATOMIC)); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } } return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> 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 double digitize(double value, int depth, int do_round) { /* 'value' is in the range 0 to 1, the result is the same value rounded to a * multiple of the digitization factor - 8 or 16 bits depending on both the * sample depth and the 'assume' setting. Digitization is normally by * rounding and 'do_round' should be 1, if it is 0 the digitized value will * be truncated. */ PNG_CONST unsigned int digitization_factor = (1U << depth) -1; /* Limiting the range is done as a convenience to the caller - it's easier to * do it once here than every time at the call site. */ if (value <= 0) value = 0; else if (value >= 1) value = 1; value *= digitization_factor; if (do_round) value += .5; return floor(value)/digitization_factor; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: static void process_stat_settings(ADD_STAT add_stats, void *c) { assert(add_stats); APPEND_STAT("maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("maxconns", "%d", settings.maxconns); APPEND_STAT("tcpport", "%d", settings.port); APPEND_STAT("udpport", "%d", settings.udpport); APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL"); APPEND_STAT("verbosity", "%d", settings.verbose); APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live); APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off"); APPEND_STAT("domain_socket", "%s", settings.socketpath ? settings.socketpath : "NULL"); APPEND_STAT("umask", "%o", settings.access); APPEND_STAT("growth_factor", "%.2f", settings.factor); APPEND_STAT("chunk_size", "%d", settings.chunk_size); APPEND_STAT("num_threads", "%d", settings.num_threads); APPEND_STAT("num_threads_per_udp", "%d", settings.num_threads_per_udp); APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter); APPEND_STAT("detail_enabled", "%s", settings.detail_enabled ? "yes" : "no"); APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event); APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no"); APPEND_STAT("tcp_backlog", "%d", settings.backlog); APPEND_STAT("binding_protocol", "%s", prot_text(settings.binding_protocol)); APPEND_STAT("auth_enabled_sasl", "%s", settings.sasl ? "yes" : "no"); APPEND_STAT("item_size_max", "%d", settings.item_size_max); APPEND_STAT("maxconns_fast", "%s", settings.maxconns_fast ? "yes" : "no"); APPEND_STAT("hashpower_init", "%d", settings.hashpower_init); APPEND_STAT("slab_reassign", "%s", settings.slab_reassign ? "yes" : "no"); APPEND_STAT("slab_automove", "%d", settings.slab_automove); APPEND_STAT("slab_chunk_max", "%d", settings.slab_chunk_size_max); APPEND_STAT("lru_crawler", "%s", settings.lru_crawler ? "yes" : "no"); APPEND_STAT("lru_crawler_sleep", "%d", settings.lru_crawler_sleep); APPEND_STAT("lru_crawler_tocrawl", "%lu", (unsigned long)settings.lru_crawler_tocrawl); APPEND_STAT("tail_repair_time", "%d", settings.tail_repair_time); APPEND_STAT("flush_enabled", "%s", settings.flush_enabled ? "yes" : "no"); APPEND_STAT("dump_enabled", "%s", settings.dump_enabled ? "yes" : "no"); APPEND_STAT("hash_algorithm", "%s", settings.hash_algorithm); APPEND_STAT("lru_maintainer_thread", "%s", settings.lru_maintainer_thread ? "yes" : "no"); APPEND_STAT("lru_segmented", "%s", settings.lru_segmented ? "yes" : "no"); APPEND_STAT("hot_lru_pct", "%d", settings.hot_lru_pct); APPEND_STAT("warm_lru_pct", "%d", settings.warm_lru_pct); APPEND_STAT("hot_max_age", "%u", settings.hot_max_age); APPEND_STAT("warm_max_factor", "%.2f", settings.warm_max_factor); APPEND_STAT("temp_lru", "%s", settings.temp_lru ? "yes" : "no"); APPEND_STAT("temporary_ttl", "%u", settings.temporary_ttl); APPEND_STAT("idle_timeout", "%d", settings.idle_timeout); APPEND_STAT("watcher_logbuf_size", "%u", settings.logger_watcher_buf_size); APPEND_STAT("worker_logbuf_size", "%u", settings.logger_buf_size); APPEND_STAT("track_sizes", "%s", item_stats_sizes_status() ? "yes" : "no"); APPEND_STAT("inline_ascii_response", "%s", settings.inline_ascii_response ? "yes" : "no"); } Commit Message: Don't overflow item refcount on get Counts as a miss if the refcount is too high. ASCII multigets are the only time refcounts can be held for so long. doing a dirty read of refcount. is aligned. trying to avoid adding an extra refcount branch for all calls of item_get due to performance. might be able to move it in there after logging refactoring simplifies some of the branches. 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 ListAttributeTargetObserver::IdTargetChanged() { element_->ListAttributeTargetChanged(); } 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: PHP_METHOD(Phar, mount) { char *fname, *arch = NULL, *entry = NULL, *path, *actual; int fname_len, arch_len, entry_len; size_t path_len, actual_len; phar_archive_data *pphar; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &path, &path_len, &actual, &actual_len) == FAILURE) { return; } fname = (char*)zend_get_executed_filename(); fname_len = strlen(fname); #ifdef PHP_WIN32 phar_unixify_path_separators(fname, fname_len); #endif if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { efree(entry); entry = NULL; if (path_len > 7 && !memcmp(path, "phar://", 7)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path); efree(arch); return; } carry_on2: if (NULL == (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len))) { if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len))) { if (SUCCESS == phar_copy_on_write(&pphar)) { goto carry_on; } } zend_throw_exception_ex(phar_ce_PharException, 0, "%s is not a phar archive, cannot mount", arch); if (arch) { efree(arch); } return; } carry_on: if (SUCCESS != phar_mount_entry(pphar, actual, actual_len, path, path_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s within phar %s failed", path, actual, arch); if (path && path == entry) { efree(entry); } if (arch) { efree(arch); } return; } if (entry && path && path == entry) { efree(entry); } if (arch) { efree(arch); } return; } else if (PHAR_G(phar_fname_map.u.flags) && NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len))) { goto carry_on; } else if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) { if (SUCCESS == phar_copy_on_write(&pphar)) { goto carry_on; } goto carry_on; } else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { path = entry; path_len = entry_len; goto carry_on2; } zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s failed", path, actual); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static void nfs4_layoutreturn_done(struct rpc_task *task, void *calldata) { struct nfs4_layoutreturn *lrp = calldata; struct nfs_server *server; dprintk("--> %s\n", __func__); if (!nfs41_sequence_done(task, &lrp->res.seq_res)) return; server = NFS_SERVER(lrp->args.inode); switch (task->tk_status) { default: task->tk_status = 0; case 0: break; case -NFS4ERR_DELAY: if (nfs4_async_handle_error(task, server, NULL, NULL) != -EAGAIN) break; rpc_restart_call_prepare(task); return; } dprintk("<-- %s\n", __func__); } Commit Message: NFS: Fix a NULL pointer dereference of migration recovery ops for v4.2 client ---Steps to Reproduce-- <nfs-server> # cat /etc/exports /nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt) /nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt) <nfs-client> # mount -t nfs nfs-server:/nfs/ /mnt/ # ll /mnt/*/ <nfs-server> # cat /etc/exports /nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt,refer=/nfs/old/@nfs-server) /nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt) # service nfs restart <nfs-client> # ll /mnt/*/ --->>>>> oops here [ 5123.102925] BUG: unable to handle kernel NULL pointer dereference at (null) [ 5123.103363] IP: [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.103752] PGD 587b9067 PUD 3cbf5067 PMD 0 [ 5123.104131] Oops: 0000 [#1] [ 5123.104529] Modules linked in: nfsv4(OE) nfs(OE) fscache(E) nfsd(OE) xfs libcrc32c iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi coretemp crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel ppdev vmw_balloon parport_pc parport i2c_piix4 shpchp auth_rpcgss nfs_acl vmw_vmci lockd grace sunrpc vmwgfx drm_kms_helper ttm drm mptspi serio_raw scsi_transport_spi e1000 mptscsih mptbase ata_generic pata_acpi [last unloaded: nfsd] [ 5123.105887] CPU: 0 PID: 15853 Comm: ::1-manager Tainted: G OE 4.2.0-rc6+ #214 [ 5123.106358] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 05/20/2014 [ 5123.106860] task: ffff88007620f300 ti: ffff88005877c000 task.ti: ffff88005877c000 [ 5123.107363] RIP: 0010:[<ffffffffa03ed38b>] [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.107909] RSP: 0018:ffff88005877fdb8 EFLAGS: 00010246 [ 5123.108435] RAX: ffff880053f3bc00 RBX: ffff88006ce6c908 RCX: ffff880053a0d240 [ 5123.108968] RDX: ffffea0000e6d940 RSI: ffff8800399a0000 RDI: ffff88006ce6c908 [ 5123.109503] RBP: ffff88005877fe28 R08: ffffffff81c708a0 R09: 0000000000000000 [ 5123.110045] R10: 00000000000001a2 R11: ffff88003ba7f5c8 R12: ffff880054c55800 [ 5123.110618] R13: 0000000000000000 R14: ffff880053a0d240 R15: ffff880053a0d240 [ 5123.111169] FS: 0000000000000000(0000) GS:ffffffff81c27000(0000) knlGS:0000000000000000 [ 5123.111726] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 [ 5123.112286] CR2: 0000000000000000 CR3: 0000000054cac000 CR4: 00000000001406f0 [ 5123.112888] Stack: [ 5123.113458] ffffea0000e6d940 ffff8800399a0000 00000000000167d0 0000000000000000 [ 5123.114049] 0000000000000000 0000000000000000 0000000000000000 00000000a7ec82c6 [ 5123.114662] ffff88005877fe18 ffffea0000e6d940 ffff8800399a0000 ffff880054c55800 [ 5123.115264] Call Trace: [ 5123.115868] [<ffffffffa03fb44b>] nfs4_try_migration+0xbb/0x220 [nfsv4] [ 5123.116487] [<ffffffffa03fcb3b>] nfs4_run_state_manager+0x4ab/0x7b0 [nfsv4] [ 5123.117104] [<ffffffffa03fc690>] ? nfs4_do_reclaim+0x510/0x510 [nfsv4] [ 5123.117813] [<ffffffff810a4527>] kthread+0xd7/0xf0 [ 5123.118456] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160 [ 5123.119108] [<ffffffff816d9cdf>] ret_from_fork+0x3f/0x70 [ 5123.119723] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160 [ 5123.120329] Code: 4c 8b 6a 58 74 17 eb 52 48 8d 55 a8 89 c6 4c 89 e7 e8 4a b5 ff ff 8b 45 b0 85 c0 74 1c 4c 89 f9 48 8b 55 90 48 8b 75 98 48 89 df <41> ff 55 00 3d e8 d8 ff ff 41 89 c6 74 cf 48 8b 4d c8 65 48 33 [ 5123.121643] RIP [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4] [ 5123.122308] RSP <ffff88005877fdb8> [ 5123.122942] CR2: 0000000000000000 Fixes: ec011fe847 ("NFS: Introduce a vector of migration recovery ops") Cc: [email protected] # v3.13+ Signed-off-by: Kinglong Mee <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> CWE ID: 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 xdr_set_next_buffer(struct xdr_stream *xdr) { if (xdr->page_ptr != NULL) xdr_set_next_page(xdr); else if (xdr->iov == xdr->buf->head) { if (xdr_set_page_base(xdr, 0, PAGE_SIZE) < 0) xdr_set_iov(xdr, xdr->buf->tail, NULL, xdr->buf->len); } return xdr->p != xdr->end; } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: [email protected] Signed-off-by: Andy Adamson <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> CWE ID: CWE-189 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: network_init () { #ifdef HAVE_GNUTLS char *ca_path, *ca_path2; gnutls_global_init (); gnutls_certificate_allocate_credentials (&gnutls_xcred); ca_path = string_expand_home (CONFIG_STRING(config_network_gnutls_ca_file)); if (ca_path) { ca_path2 = string_replace (ca_path, "%h", weechat_home); if (ca_path2) { gnutls_certificate_set_x509_trust_file (gnutls_xcred, ca_path2, GNUTLS_X509_FMT_PEM); free (ca_path2); } free (ca_path); } gnutls_certificate_client_set_retrieve_function (gnutls_xcred, &hook_connect_gnutls_set_certificates); network_init_ok = 1; gcry_check_version (GCRYPT_VERSION); gcry_control (GCRYCTL_DISABLE_SECMEM, 0); gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static void virtio_register_types(void) { type_register_static(&virtio_gpu_info); } Commit Message: CWE ID: CWE-772 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: compute_frac_paths_available(const networkstatus_t *consensus, const or_options_t *options, time_t now, int *num_present_out, int *num_usable_out, char **status_out) { smartlist_t *guards = smartlist_new(); smartlist_t *mid = smartlist_new(); smartlist_t *exits = smartlist_new(); double f_guard, f_mid, f_exit; double f_path = 0.0; /* Used to determine whether there are any exits in the consensus */ int np = 0; /* Used to determine whether there are any exits with descriptors */ int nu = 0; const int authdir = authdir_mode_v3(options); count_usable_descriptors(num_present_out, num_usable_out, mid, consensus, options, now, NULL, USABLE_DESCRIPTOR_ALL); if (options->EntryNodes) { count_usable_descriptors(&np, &nu, guards, consensus, options, now, options->EntryNodes, USABLE_DESCRIPTOR_ALL); } else { SMARTLIST_FOREACH(mid, const node_t *, node, { if (authdir) { if (node->rs && node->rs->is_possible_guard) smartlist_add(guards, (node_t*)node); } else { if (node->is_possible_guard) smartlist_add(guards, (node_t*)node); } }); } /* All nodes with exit flag * If we're in a network with TestingDirAuthVoteExit set, * this can cause false positives on have_consensus_path, * incorrectly setting it to CONSENSUS_PATH_EXIT. This is * an unavoidable feature of forcing authorities to declare * certain nodes as exits. */ count_usable_descriptors(&np, &nu, exits, consensus, options, now, NULL, USABLE_DESCRIPTOR_EXIT_ONLY); log_debug(LD_NET, "%s: %d present, %d usable", "exits", np, nu); /* We need at least 1 exit present in the consensus to consider * building exit paths */ /* Update our understanding of whether the consensus has exits */ consensus_path_type_t old_have_consensus_path = have_consensus_path; have_consensus_path = ((nu > 0) ? CONSENSUS_PATH_EXIT : CONSENSUS_PATH_INTERNAL); if (have_consensus_path == CONSENSUS_PATH_INTERNAL && old_have_consensus_path != have_consensus_path) { log_notice(LD_NET, "The current consensus has no exit nodes. " "Tor can only build internal paths, " "such as paths to hidden services."); /* However, exit nodes can reachability self-test using this consensus, * join the network, and appear in a later consensus. This will allow * the network to build exit paths, such as paths for world wide web * browsing (as distinct from hidden service web browsing). */ } f_guard = frac_nodes_with_descriptors(guards, WEIGHT_FOR_GUARD); f_mid = frac_nodes_with_descriptors(mid, WEIGHT_FOR_MID); f_exit = frac_nodes_with_descriptors(exits, WEIGHT_FOR_EXIT); log_debug(LD_NET, "f_guard: %.2f, f_mid: %.2f, f_exit: %.2f", f_guard, f_mid, f_exit); smartlist_free(guards); smartlist_free(mid); smartlist_free(exits); if (options->ExitNodes) { double f_myexit, f_myexit_unflagged; smartlist_t *myexits= smartlist_new(); smartlist_t *myexits_unflagged = smartlist_new(); /* All nodes with exit flag in ExitNodes option */ count_usable_descriptors(&np, &nu, myexits, consensus, options, now, options->ExitNodes, USABLE_DESCRIPTOR_EXIT_ONLY); log_debug(LD_NET, "%s: %d present, %d usable", "myexits", np, nu); /* Now compute the nodes in the ExitNodes option where which we don't know * what their exit policy is, or we know it permits something. */ count_usable_descriptors(&np, &nu, myexits_unflagged, consensus, options, now, options->ExitNodes, USABLE_DESCRIPTOR_ALL); log_debug(LD_NET, "%s: %d present, %d usable", "myexits_unflagged (initial)", np, nu); SMARTLIST_FOREACH_BEGIN(myexits_unflagged, const node_t *, node) { if (node_has_descriptor(node) && node_exit_policy_rejects_all(node)) { SMARTLIST_DEL_CURRENT(myexits_unflagged, node); /* this node is not actually an exit */ np--; /* this node is unusable as an exit */ nu--; } } SMARTLIST_FOREACH_END(node); log_debug(LD_NET, "%s: %d present, %d usable", "myexits_unflagged (final)", np, nu); f_myexit= frac_nodes_with_descriptors(myexits,WEIGHT_FOR_EXIT); f_myexit_unflagged= frac_nodes_with_descriptors(myexits_unflagged,WEIGHT_FOR_EXIT); log_debug(LD_NET, "f_exit: %.2f, f_myexit: %.2f, f_myexit_unflagged: %.2f", f_exit, f_myexit, f_myexit_unflagged); /* If our ExitNodes list has eliminated every possible Exit node, and there * were some possible Exit nodes, then instead consider nodes that permit * exiting to some ports. */ if (smartlist_len(myexits) == 0 && smartlist_len(myexits_unflagged)) { f_myexit = f_myexit_unflagged; } smartlist_free(myexits); smartlist_free(myexits_unflagged); /* This is a tricky point here: we don't want to make it easy for a * directory to trickle exits to us until it learns which exits we have * configured, so require that we have a threshold both of total exits * and usable exits. */ if (f_myexit < f_exit) f_exit = f_myexit; } /* if the consensus has no exits, treat the exit fraction as 100% */ if (router_have_consensus_path() != CONSENSUS_PATH_EXIT) { f_exit = 1.0; } f_path = f_guard * f_mid * f_exit; if (status_out) tor_asprintf(status_out, "%d%% of guards bw, " "%d%% of midpoint bw, and " "%d%% of exit bw%s = " "%d%% of path bw", (int)(f_guard*100), (int)(f_mid*100), (int)(f_exit*100), (router_have_consensus_path() == CONSENSUS_PATH_EXIT ? "" : " (no exits in consensus)"), (int)(f_path*100)); return f_path; } Commit Message: Consider the exit family when applying guard restrictions. When the new path selection logic went into place, I accidentally dropped the code that considered the _family_ of the exit node when deciding if the guard was usable, and we didn't catch that during code review. This patch makes the guard_restriction_t code consider the exit family as well, and adds some (hopefully redundant) checks for the case where we lack a node_t for a guard but we have a bridge_info_t for it. Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006 and CVE-2017-0377. 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: psf_binheader_writef (SF_PRIVATE *psf, const char *format, ...) { va_list argptr ; sf_count_t countdata ; unsigned long longdata ; unsigned int data ; float floatdata ; double doubledata ; void *bindata ; size_t size ; char c, *strptr ; int count = 0, trunc_8to4 ; trunc_8to4 = SF_FALSE ; va_start (argptr, format) ; while ((c = *format++)) { switch (c) { case ' ' : /* Do nothing. Just used to space out format string. */ break ; case 'e' : /* All conversions are now from LE to host. */ psf->rwf_endian = SF_ENDIAN_LITTLE ; break ; case 'E' : /* All conversions are now from BE to host. */ psf->rwf_endian = SF_ENDIAN_BIG ; break ; case 't' : /* All 8 byte values now get written as 4 bytes. */ trunc_8to4 = SF_TRUE ; break ; case 'T' : /* All 8 byte values now get written as 8 bytes. */ trunc_8to4 = SF_FALSE ; break ; case 'm' : data = va_arg (argptr, unsigned int) ; header_put_marker (psf, data) ; count += 4 ; break ; case '1' : data = va_arg (argptr, unsigned int) ; header_put_byte (psf, data) ; count += 1 ; break ; case '2' : data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_short (psf, data) ; } else { header_put_le_short (psf, data) ; } ; count += 2 ; break ; case '3' : /* tribyte */ data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_3byte (psf, data) ; } else { header_put_le_3byte (psf, data) ; } ; count += 3 ; break ; case '4' : data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_int (psf, data) ; } else { header_put_le_int (psf, data) ; } ; count += 4 ; break ; case '8' : countdata = va_arg (argptr, sf_count_t) ; if (psf->rwf_endian == SF_ENDIAN_BIG && trunc_8to4 == SF_FALSE) { header_put_be_8byte (psf, countdata) ; count += 8 ; } else if (psf->rwf_endian == SF_ENDIAN_LITTLE && trunc_8to4 == SF_FALSE) { header_put_le_8byte (psf, countdata) ; count += 8 ; } else if (psf->rwf_endian == SF_ENDIAN_BIG && trunc_8to4 == SF_TRUE) { longdata = countdata & 0xFFFFFFFF ; header_put_be_int (psf, longdata) ; count += 4 ; } else if (psf->rwf_endian == SF_ENDIAN_LITTLE && trunc_8to4 == SF_TRUE) { longdata = countdata & 0xFFFFFFFF ; header_put_le_int (psf, longdata) ; count += 4 ; } break ; case 'f' : /* Floats are passed as doubles. Is this always true? */ floatdata = (float) va_arg (argptr, double) ; if (psf->rwf_endian == SF_ENDIAN_BIG) float32_be_write (floatdata, psf->header + psf->headindex) ; else float32_le_write (floatdata, psf->header + psf->headindex) ; psf->headindex += 4 ; count += 4 ; break ; case 'd' : doubledata = va_arg (argptr, double) ; if (psf->rwf_endian == SF_ENDIAN_BIG) double64_be_write (doubledata, psf->header + psf->headindex) ; else double64_le_write (doubledata, psf->header + psf->headindex) ; psf->headindex += 8 ; count += 8 ; break ; case 's' : /* Write a C string (guaranteed to have a zero terminator). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) + 1 ; size += (size & 1) ; if (psf->rwf_endian == SF_ENDIAN_BIG) header_put_be_int (psf, size) ; else header_put_le_int (psf, size) ; memcpy (&(psf->header [psf->headindex]), strptr, size) ; psf->headindex += size ; psf->header [psf->headindex - 1] = 0 ; count += 4 + size ; break ; case 'S' : /* ** Write an AIFF style string (no zero terminator but possibly ** an extra pad byte if the string length is odd). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) ; if (psf->rwf_endian == SF_ENDIAN_BIG) header_put_be_int (psf, size) ; else header_put_le_int (psf, size) ; memcpy (&(psf->header [psf->headindex]), strptr, size + 1) ; size += (size & 1) ; psf->headindex += size ; psf->header [psf->headindex] = 0 ; count += 4 + size ; break ; case 'p' : /* Write a PASCAL string (as used by AIFF files). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) ; size = (size & 1) ? size : size + 1 ; size = (size > 254) ? 254 : size ; header_put_byte (psf, size) ; memcpy (&(psf->header [psf->headindex]), strptr, size) ; psf->headindex += size ; count += 1 + size ; break ; case 'b' : bindata = va_arg (argptr, void *) ; size = va_arg (argptr, size_t) ; if (psf->headindex + size < sizeof (psf->header)) { memcpy (&(psf->header [psf->headindex]), bindata, size) ; psf->headindex += size ; count += size ; } ; break ; case 'z' : size = va_arg (argptr, size_t) ; count += size ; while (size) { psf->header [psf->headindex] = 0 ; psf->headindex ++ ; size -- ; } ; break ; case 'h' : bindata = va_arg (argptr, void *) ; memcpy (&(psf->header [psf->headindex]), bindata, 16) ; psf->headindex += 16 ; count += 16 ; break ; case 'j' : /* Jump forwards/backwards by specified amount. */ size = va_arg (argptr, size_t) ; psf->headindex += size ; count += size ; break ; case 'o' : /* Jump to specified offset. */ size = va_arg (argptr, size_t) ; if (size < sizeof (psf->header)) { psf->headindex = size ; count = 0 ; } ; break ; default : psf_log_printf (psf, "*** Invalid format specifier `%c'\n", c) ; psf->error = SFE_INTERNAL ; break ; } ; } ; va_end (argptr) ; return count ; } /* psf_binheader_writef */ 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: 1 Example 2: Code: int orangefs_init_acl(struct inode *inode, struct inode *dir) { struct orangefs_inode_s *orangefs_inode = ORANGEFS_I(inode); struct posix_acl *default_acl, *acl; umode_t mode = inode->i_mode; int error = 0; ClearModeFlag(orangefs_inode); error = posix_acl_create(dir, &mode, &default_acl, &acl); if (error) return error; if (default_acl) { error = orangefs_set_acl(inode, default_acl, ACL_TYPE_DEFAULT); posix_acl_release(default_acl); } if (acl) { if (!error) error = orangefs_set_acl(inode, acl, ACL_TYPE_ACCESS); posix_acl_release(acl); } /* If mode of the inode was changed, then do a forcible ->setattr */ if (mode != inode->i_mode) { SetModeFlag(orangefs_inode); inode->i_mode = mode; orangefs_flush_inode(inode); } return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285 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 simple_free_urb(struct urb *urb) { unsigned long offset = buffer_offset(urb->transfer_buffer); if (urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP) usb_free_coherent( urb->dev, urb->transfer_buffer_length + offset, urb->transfer_buffer - offset, urb->transfer_dma - offset); else kfree(urb->transfer_buffer - offset); usb_free_urb(urb); } Commit Message: usb: usbtest: fix NULL pointer dereference If the usbtest driver encounters a device with an IN bulk endpoint but no OUT bulk endpoint, it will try to dereference a NULL pointer (out->desc.bEndpointAddress). The problem can be solved by adding a missing test. Signed-off-by: Alan Stern <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Signed-off-by: Felipe Balbi <[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: static int flashsv_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { int buf_size = avpkt->size; FlashSVContext *s = avctx->priv_data; int h_blocks, v_blocks, h_part, v_part, i, j, ret; GetBitContext gb; int last_blockwidth = s->block_width; int last_blockheight= s->block_height; /* no supplementary picture */ if (buf_size == 0) return 0; if (buf_size < 4) return -1; init_get_bits(&gb, avpkt->data, buf_size * 8); /* start to parse the bitstream */ s->block_width = 16 * (get_bits(&gb, 4) + 1); s->image_width = get_bits(&gb, 12); s->block_height = 16 * (get_bits(&gb, 4) + 1); s->image_height = get_bits(&gb, 12); if ( last_blockwidth != s->block_width || last_blockheight!= s->block_height) av_freep(&s->blocks); if (s->ver == 2) { skip_bits(&gb, 6); if (get_bits1(&gb)) { avpriv_request_sample(avctx, "iframe"); return AVERROR_PATCHWELCOME; } if (get_bits1(&gb)) { avpriv_request_sample(avctx, "Custom palette"); return AVERROR_PATCHWELCOME; } } /* calculate number of blocks and size of border (partial) blocks */ h_blocks = s->image_width / s->block_width; h_part = s->image_width % s->block_width; v_blocks = s->image_height / s->block_height; v_part = s->image_height % s->block_height; /* the block size could change between frames, make sure the buffer * is large enough, if not, get a larger one */ if (s->block_size < s->block_width * s->block_height) { int tmpblock_size = 3 * s->block_width * s->block_height; s->tmpblock = av_realloc(s->tmpblock, tmpblock_size); if (!s->tmpblock) { av_log(avctx, AV_LOG_ERROR, "Can't allocate decompression buffer.\n"); return AVERROR(ENOMEM); } if (s->ver == 2) { s->deflate_block_size = calc_deflate_block_size(tmpblock_size); if (s->deflate_block_size <= 0) { av_log(avctx, AV_LOG_ERROR, "Can't determine deflate buffer size.\n"); return -1; } s->deflate_block = av_realloc(s->deflate_block, s->deflate_block_size); if (!s->deflate_block) { av_log(avctx, AV_LOG_ERROR, "Can't allocate deflate buffer.\n"); return AVERROR(ENOMEM); } } } s->block_size = s->block_width * s->block_height; /* initialize the image size once */ if (avctx->width == 0 && avctx->height == 0) { avcodec_set_dimensions(avctx, s->image_width, s->image_height); } /* check for changes of image width and image height */ if (avctx->width != s->image_width || avctx->height != s->image_height) { av_log(avctx, AV_LOG_ERROR, "Frame width or height differs from first frame!\n"); av_log(avctx, AV_LOG_ERROR, "fh = %d, fv %d vs ch = %d, cv = %d\n", avctx->height, avctx->width, s->image_height, s->image_width); return AVERROR_INVALIDDATA; } /* we care for keyframes only in Screen Video v2 */ s->is_keyframe = (avpkt->flags & AV_PKT_FLAG_KEY) && (s->ver == 2); if (s->is_keyframe) { s->keyframedata = av_realloc(s->keyframedata, avpkt->size); memcpy(s->keyframedata, avpkt->data, avpkt->size); } if(s->ver == 2 && !s->blocks) s->blocks = av_mallocz((v_blocks + !!v_part) * (h_blocks + !!h_part) * sizeof(s->blocks[0])); av_dlog(avctx, "image: %dx%d block: %dx%d num: %dx%d part: %dx%d\n", s->image_width, s->image_height, s->block_width, s->block_height, h_blocks, v_blocks, h_part, v_part); if ((ret = ff_reget_buffer(avctx, &s->frame)) < 0) return ret; /* loop over all block columns */ for (j = 0; j < v_blocks + (v_part ? 1 : 0); j++) { int y_pos = j * s->block_height; // vertical position in frame int cur_blk_height = (j < v_blocks) ? s->block_height : v_part; /* loop over all block rows */ for (i = 0; i < h_blocks + (h_part ? 1 : 0); i++) { int x_pos = i * s->block_width; // horizontal position in frame int cur_blk_width = (i < h_blocks) ? s->block_width : h_part; int has_diff = 0; /* get the size of the compressed zlib chunk */ int size = get_bits(&gb, 16); s->color_depth = 0; s->zlibprime_curr = 0; s->zlibprime_prev = 0; s->diff_start = 0; s->diff_height = cur_blk_height; if (8 * size > get_bits_left(&gb)) { av_frame_unref(&s->frame); return AVERROR_INVALIDDATA; } if (s->ver == 2 && size) { skip_bits(&gb, 3); s->color_depth = get_bits(&gb, 2); has_diff = get_bits1(&gb); s->zlibprime_curr = get_bits1(&gb); s->zlibprime_prev = get_bits1(&gb); if (s->color_depth != 0 && s->color_depth != 2) { av_log(avctx, AV_LOG_ERROR, "%dx%d invalid color depth %d\n", i, j, s->color_depth); return AVERROR_INVALIDDATA; } if (has_diff) { if (!s->keyframe) { av_log(avctx, AV_LOG_ERROR, "inter frame without keyframe\n"); return AVERROR_INVALIDDATA; } s->diff_start = get_bits(&gb, 8); s->diff_height = get_bits(&gb, 8); av_log(avctx, AV_LOG_DEBUG, "%dx%d diff start %d height %d\n", i, j, s->diff_start, s->diff_height); size -= 2; } if (s->zlibprime_prev) av_log(avctx, AV_LOG_DEBUG, "%dx%d zlibprime_prev\n", i, j); if (s->zlibprime_curr) { int col = get_bits(&gb, 8); int row = get_bits(&gb, 8); av_log(avctx, AV_LOG_DEBUG, "%dx%d zlibprime_curr %dx%d\n", i, j, col, row); size -= 2; avpriv_request_sample(avctx, "zlibprime_curr"); return AVERROR_PATCHWELCOME; } if (!s->blocks && (s->zlibprime_curr || s->zlibprime_prev)) { av_log(avctx, AV_LOG_ERROR, "no data available for zlib " "priming\n"); return AVERROR_INVALIDDATA; } size--; // account for flags byte } if (has_diff) { int k; int off = (s->image_height - y_pos - 1) * s->frame.linesize[0]; for (k = 0; k < cur_blk_height; k++) memcpy(s->frame.data[0] + off - k*s->frame.linesize[0] + x_pos*3, s->keyframe + off - k*s->frame.linesize[0] + x_pos*3, cur_blk_width * 3); } /* skip unchanged blocks, which have size 0 */ if (size) { if (flashsv_decode_block(avctx, avpkt, &gb, size, cur_blk_width, cur_blk_height, x_pos, y_pos, i + j * (h_blocks + !!h_part))) av_log(avctx, AV_LOG_ERROR, "error in decompression of block %dx%d\n", i, j); } } } if (s->is_keyframe && s->ver == 2) { if (!s->keyframe) { s->keyframe = av_malloc(s->frame.linesize[0] * avctx->height); if (!s->keyframe) { av_log(avctx, AV_LOG_ERROR, "Cannot allocate image data\n"); return AVERROR(ENOMEM); } } memcpy(s->keyframe, s->frame.data[0], s->frame.linesize[0] * avctx->height); } if ((ret = av_frame_ref(data, &s->frame)) < 0) return ret; *got_frame = 1; if ((get_bits_count(&gb) / 8) != buf_size) av_log(avctx, AV_LOG_ERROR, "buffer not fully consumed (%d != %d)\n", buf_size, (get_bits_count(&gb) / 8)); /* report that the buffer was completely consumed */ return buf_size; } Commit Message: avcodec/flashsv: check diff_start/height Fixes out of array accesses Fixes Ticket2844 Found-by: ami_stuff Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: int FLTParseGMLEnvelope(CPLXMLNode *psRoot, rectObj *psBbox, char **ppszSRS) { CPLXMLNode *psUpperCorner=NULL, *psLowerCorner=NULL; const char *pszLowerCorner=NULL, *pszUpperCorner=NULL; int bValid = 0; char **tokens; int n; if (psRoot && psBbox && psRoot->eType == CXT_Element && EQUAL(psRoot->pszValue,"Envelope")) { /*Get the srs if available*/ if (ppszSRS) { const char* pszSRS = CPLGetXMLValue(psRoot, "srsName", NULL); if( pszSRS != NULL ) *ppszSRS = msStrdup(pszSRS); } psLowerCorner = CPLSearchXMLNode(psRoot, "lowerCorner"); psUpperCorner = CPLSearchXMLNode(psRoot, "upperCorner"); if (psLowerCorner && psUpperCorner) { pszLowerCorner = CPLGetXMLValue(psLowerCorner, NULL, NULL); pszUpperCorner = CPLGetXMLValue(psUpperCorner, NULL, NULL); if (pszLowerCorner && pszUpperCorner) { tokens = msStringSplit(pszLowerCorner, ' ', &n); if (tokens && n >= 2) { psBbox->minx = atof(tokens[0]); psBbox->miny = atof(tokens[1]); msFreeCharArray(tokens, n); tokens = msStringSplit(pszUpperCorner, ' ', &n); if (tokens && n >= 2) { psBbox->maxx = atof(tokens[0]); psBbox->maxy = atof(tokens[1]); bValid = 1; } } msFreeCharArray(tokens, n); } } } return bValid; } Commit Message: security fix (patch by EvenR) 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: stringprep_utf8_nfkc_normalize (const char *str, ssize_t len) { return g_utf8_normalize (str, len, G_NORMALIZE_NFKC); } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ProcSendEvent(ClientPtr client) { WindowPtr pWin; WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */ DeviceIntPtr dev = PickPointer(client); DeviceIntPtr keybd = GetMaster(dev, MASTER_KEYBOARD); SpritePtr pSprite = dev->spriteInfo->sprite; REQUEST(xSendEventReq); REQUEST_SIZE_MATCH(xSendEventReq); /* libXext and other extension libraries may set the bit indicating * that this event came from a SendEvent request so remove it * since otherwise the event type may fail the range checks * and cause an invalid BadValue error to be returned. * * This is safe to do since we later add the SendEvent bit (0x80) * back in once we send the event to the client */ stuff->event.u.u.type &= ~(SEND_EVENT_BIT); /* The client's event type must be a core event type or one defined by an extension. */ if (!((stuff->event.u.u.type > X_Reply && stuff->event.u.u.type < LASTEvent) || (stuff->event.u.u.type >= EXTENSION_EVENT_BASE && stuff->event.u.u.type < (unsigned) lastEvent))) { client->errorValue = stuff->event.u.u.type; return BadValue; } if (stuff->event.u.u.type == ClientMessage && stuff->event.u.u.detail != 8 && stuff->event.u.u.detail != 16 && stuff->event.u.u.detail != 32) { } if (stuff->destination == PointerWindow) pWin = pSprite->win; else if (stuff->destination == InputFocus) { WindowPtr inputFocus = (keybd) ? keybd->focus->win : NoneWin; if (inputFocus == NoneWin) return Success; /* If the input focus is PointerRootWin, send the event to where the pointer is if possible, then perhaps propogate up to root. */ if (inputFocus == PointerRootWin) inputFocus = GetCurrentRootWindow(dev); if (IsParent(inputFocus, pSprite->win)) { effectiveFocus = inputFocus; pWin = pSprite->win; } else effectiveFocus = pWin = inputFocus; } else dixLookupWindow(&pWin, stuff->destination, client, DixSendAccess); if (!pWin) return BadWindow; if ((stuff->propagate != xFalse) && (stuff->propagate != xTrue)) { client->errorValue = stuff->propagate; return BadValue; } stuff->event.u.u.type |= SEND_EVENT_BIT; if (stuff->propagate) { for (; pWin; pWin = pWin->parent) { if (XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) return Success; if (DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab)) return Success; if (pWin == effectiveFocus) return Success; stuff->eventMask &= ~wDontPropagateMask(pWin); if (!stuff->eventMask) break; } } else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, &stuff->event, 1)) DeliverEventsToWindow(dev, pWin, &stuff->event, 1, stuff->eventMask, NullGrab); return Success; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static void destroy_async_on_interface(struct usb_dev_state *ps, unsigned int ifnum) { struct list_head *p, *q, hitlist; unsigned long flags; INIT_LIST_HEAD(&hitlist); spin_lock_irqsave(&ps->lock, flags); list_for_each_safe(p, q, &ps->async_pending) if (ifnum == list_entry(p, struct async, asynclist)->ifnum) list_move_tail(p, &hitlist); spin_unlock_irqrestore(&ps->lock, flags); destroy_async(ps, &hitlist); } Commit Message: USB: usbfs: fix potential infoleak in devio The stack object “ci” has a total size of 8 bytes. Its last 3 bytes are padding bytes which are not initialized and leaked to userland via “copy_to_user”. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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: poolClear(STRING_POOL *pool) { if (!pool->freeBlocks) pool->freeBlocks = pool->blocks; else { BLOCK *p = pool->blocks; while (p) { BLOCK *tem = p->next; p->next = pool->freeBlocks; pool->freeBlocks = p; p = tem; } } pool->blocks = NULL; pool->start = NULL; pool->ptr = NULL; pool->end = NULL; } Commit Message: xmlparse.c: Fix extraction of namespace prefix from XML name (#186) CWE ID: CWE-611 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: std::unique_ptr<net::test_server::HttpResponse> GetConfigResponse( const net::test_server::HttpRequest& request) { auto response = std::make_unique<net::test_server::BasicHttpResponse>(); response->set_content(config_.SerializeAsString()); response->set_content_type("text/plain"); if (config_run_loop_) config_run_loop_->Quit(); return response; } 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: static void floppy_release_allocated_regions(int fdc, const struct io_region *p) { while (p != io_regions) { p--; release_region(FDCS->address + p->offset, p->size); } } 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 struct net_device *_init_airo_card( unsigned short irq, int port, int is_pcmcia, struct pci_dev *pci, struct device *dmdev ) { struct net_device *dev; struct airo_info *ai; int i, rc; CapabilityRid cap_rid; /* Create the network device object. */ dev = alloc_netdev(sizeof(*ai), "", ether_setup); if (!dev) { airo_print_err("", "Couldn't alloc_etherdev"); return NULL; } ai = dev->ml_priv = netdev_priv(dev); ai->wifidev = NULL; ai->flags = 1 << FLAG_RADIO_DOWN; ai->jobs = 0; ai->dev = dev; if (pci && (pci->device == 0x5000 || pci->device == 0xa504)) { airo_print_dbg("", "Found an MPI350 card"); set_bit(FLAG_MPI, &ai->flags); } spin_lock_init(&ai->aux_lock); sema_init(&ai->sem, 1); ai->config.len = 0; ai->pci = pci; init_waitqueue_head (&ai->thr_wait); ai->tfm = NULL; add_airo_dev(ai); if (airo_networks_allocate (ai)) goto err_out_free; airo_networks_initialize (ai); skb_queue_head_init (&ai->txq); /* The Airo-specific entries in the device structure. */ if (test_bit(FLAG_MPI,&ai->flags)) dev->netdev_ops = &mpi_netdev_ops; else dev->netdev_ops = &airo_netdev_ops; dev->wireless_handlers = &airo_handler_def; ai->wireless_data.spy_data = &ai->spy_data; dev->wireless_data = &ai->wireless_data; dev->irq = irq; dev->base_addr = port; SET_NETDEV_DEV(dev, dmdev); reset_card (dev, 1); msleep(400); if (!is_pcmcia) { if (!request_region(dev->base_addr, 64, DRV_NAME)) { rc = -EBUSY; airo_print_err(dev->name, "Couldn't request region"); goto err_out_nets; } } if (test_bit(FLAG_MPI,&ai->flags)) { if (mpi_map_card(ai, pci)) { airo_print_err("", "Could not map memory"); goto err_out_res; } } if (probe) { if (setup_card(ai, dev->dev_addr, 1) != SUCCESS) { airo_print_err(dev->name, "MAC could not be enabled" ); rc = -EIO; goto err_out_map; } } else if (!test_bit(FLAG_MPI,&ai->flags)) { ai->bap_read = fast_bap_read; set_bit(FLAG_FLASHING, &ai->flags); } strcpy(dev->name, "eth%d"); rc = register_netdev(dev); if (rc) { airo_print_err(dev->name, "Couldn't register_netdev"); goto err_out_map; } ai->wifidev = init_wifidev(ai, dev); if (!ai->wifidev) goto err_out_reg; rc = readCapabilityRid(ai, &cap_rid, 1); if (rc != SUCCESS) { rc = -EIO; goto err_out_wifi; } /* WEP capability discovery */ ai->wep_capable = (cap_rid.softCap & cpu_to_le16(0x02)) ? 1 : 0; ai->max_wep_idx = (cap_rid.softCap & cpu_to_le16(0x80)) ? 3 : 0; airo_print_info(dev->name, "Firmware version %x.%x.%02d", ((le16_to_cpu(cap_rid.softVer) >> 8) & 0xF), (le16_to_cpu(cap_rid.softVer) & 0xFF), le16_to_cpu(cap_rid.softSubVer)); /* Test for WPA support */ /* Only firmware versions 5.30.17 or better can do WPA */ if (le16_to_cpu(cap_rid.softVer) > 0x530 || (le16_to_cpu(cap_rid.softVer) == 0x530 && le16_to_cpu(cap_rid.softSubVer) >= 17)) { airo_print_info(ai->dev->name, "WPA supported."); set_bit(FLAG_WPA_CAPABLE, &ai->flags); ai->bssListFirst = RID_WPA_BSSLISTFIRST; ai->bssListNext = RID_WPA_BSSLISTNEXT; ai->bssListRidLen = sizeof(BSSListRid); } else { airo_print_info(ai->dev->name, "WPA unsupported with firmware " "versions older than 5.30.17."); ai->bssListFirst = RID_BSSLISTFIRST; ai->bssListNext = RID_BSSLISTNEXT; ai->bssListRidLen = sizeof(BSSListRid) - sizeof(BSSListRidExtra); } set_bit(FLAG_REGISTERED,&ai->flags); airo_print_info(dev->name, "MAC enabled %pM", dev->dev_addr); /* Allocate the transmit buffers */ if (probe && !test_bit(FLAG_MPI,&ai->flags)) for( i = 0; i < MAX_FIDS; i++ ) ai->fids[i] = transmit_allocate(ai,AIRO_DEF_MTU,i>=MAX_FIDS/2); if (setup_proc_entry(dev, dev->ml_priv) < 0) goto err_out_wifi; return dev; err_out_wifi: unregister_netdev(ai->wifidev); free_netdev(ai->wifidev); err_out_reg: unregister_netdev(dev); err_out_map: if (test_bit(FLAG_MPI,&ai->flags) && pci) { pci_free_consistent(pci, PCI_SHARED_LEN, ai->shared, ai->shared_dma); iounmap(ai->pciaux); iounmap(ai->pcimem); mpi_unmap_card(ai->pci); } err_out_res: if (!is_pcmcia) release_region( dev->base_addr, 64 ); err_out_nets: airo_networks_free(ai); err_out_free: del_airo_dev(ai); free_netdev(dev); return 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 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 WtsConsoleSessionProcessDriver::OnChannelConnected() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static int assign_host_irq(struct kvm *kvm, struct kvm_assigned_dev_kernel *dev, __u32 host_irq_type) { int r = -EEXIST; if (dev->irq_requested_type & KVM_DEV_IRQ_HOST_MASK) return r; snprintf(dev->irq_name, sizeof(dev->irq_name), "kvm:%s", pci_name(dev->dev)); switch (host_irq_type) { case KVM_DEV_IRQ_HOST_INTX: r = assigned_device_enable_host_intx(kvm, dev); break; #ifdef __KVM_HAVE_MSI case KVM_DEV_IRQ_HOST_MSI: r = assigned_device_enable_host_msi(kvm, dev); break; #endif #ifdef __KVM_HAVE_MSIX case KVM_DEV_IRQ_HOST_MSIX: r = assigned_device_enable_host_msix(kvm, dev); break; #endif default: r = -EINVAL; } if (!r) dev->irq_requested_type |= host_irq_type; return r; } Commit Message: KVM: Device assignment permission checks (cherry picked from commit 3d27e23b17010c668db311140b17bbbb70c78fb9) Only allow KVM device assignment to attach to devices which: - Are not bridges - Have BAR resources (assume others are special devices) - The user has permissions to use Assigning a bridge is a configuration error, it's not supported, and typically doesn't result in the behavior the user is expecting anyway. Devices without BAR resources are typically chipset components that also don't have host drivers. We don't want users to hold such devices captive or cause system problems by fencing them off into an iommu domain. We determine "permission to use" by testing whether the user has access to the PCI sysfs resource files. By default a normal user will not have access to these files, so it provides a good indication that an administration agent has granted the user access to the device. [Yang Bai: add missing #include] [avi: fix comment style] Signed-off-by: Alex Williamson <[email protected]> Signed-off-by: Yang Bai <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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 btif_config_flush(void) { assert(config != NULL); assert(alarm_timer != NULL); alarm_cancel(alarm_timer); pthread_mutex_lock(&lock); config_save(config, CONFIG_FILE_PATH); pthread_mutex_unlock(&lock); } Commit Message: Fix crashes with lots of discovered LE devices When loads of devices are discovered a config file which is too large can be written out, which causes the BT daemon to crash on startup. This limits the number of config entries for unpaired devices which are initialized, and prevents a large number from being saved to the filesystem. Bug: 26071376 Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184 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 RenderWidgetHostImpl::SendFrontSurfaceIsProtected( bool is_protected, uint32 protection_state_id, int32 route_id, int gpu_host_id) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id); if (ui_shim) { ui_shim->Send(new AcceleratedSurfaceMsg_SetFrontSurfaceIsProtected( route_id, is_protected, protection_state_id)); } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: static void get_current_time(struct timeval *t) { #if defined(_WIN32) SYSTEMTIME st; union { unsigned __int64 ul; FILETIME ft; } now; GetSystemTime(&st); SystemTimeToFileTime(&st, &now.ft); # ifdef __MINGW32__ now.ul -= 116444736000000000ULL; # else now.ul -= 116444736000000000UI64; /* re-bias to 1/1/1970 */ # endif t->tv_sec = (long)(now.ul / 10000000); t->tv_usec = ((int)(now.ul % 10000000)) / 10; #elif defined(OPENSSL_SYS_VMS) struct timeb tb; ftime(&tb); t->tv_sec = (long)tb.time; t->tv_usec = (long)tb.millitm * 1000; #else gettimeofday(t, NULL); #endif } Commit Message: 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 GestureProviderAura::OnTouchEvent(const TouchEvent& event) { last_touch_event_flags_ = event.flags(); bool pointer_id_is_active = false; for (size_t i = 0; i < pointer_state_.GetPointerCount(); ++i) { if (event.touch_id() != pointer_state_.GetPointerId(i)) continue; pointer_id_is_active = true; break; } if (event.type() == ET_TOUCH_PRESSED && pointer_id_is_active) { return false; } else if (event.type() != ET_TOUCH_PRESSED && !pointer_id_is_active) { return false; } pointer_state_.OnTouch(event); bool result = filtered_gesture_provider_.OnTouchEvent(pointer_state_); pointer_state_.CleanupRemovedTouchPoints(event); return result; } Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura. BUG=379812 TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent Review URL: https://codereview.chromium.org/309823002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98 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: status_t OMXNodeInstance::prepareForAdaptivePlayback( OMX_U32 portIndex, OMX_BOOL enable, OMX_U32 maxFrameWidth, OMX_U32 maxFrameHeight) { Mutex::Autolock autolock(mLock); CLOG_CONFIG(prepareForAdaptivePlayback, "%s:%u en=%d max=%ux%u", portString(portIndex), portIndex, enable, maxFrameWidth, maxFrameHeight); OMX_INDEXTYPE index; OMX_STRING name = const_cast<OMX_STRING>( "OMX.google.android.index.prepareForAdaptivePlayback"); OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index); if (err != OMX_ErrorNone) { CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name); return StatusFromOMXError(err); } PrepareForAdaptivePlaybackParams params; InitOMXParams(&params); params.nPortIndex = portIndex; params.bEnable = enable; params.nMaxFrameWidth = maxFrameWidth; params.nMaxFrameHeight = maxFrameHeight; err = OMX_SetParameter(mHandle, index, &params); CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d max=%ux%u", name, index, portString(portIndex), portIndex, enable, maxFrameWidth, maxFrameHeight); return StatusFromOMXError(err); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200 Target: 1 Example 2: Code: static void bond_vlan_rx_kill_vid(struct net_device *bond_dev, uint16_t vid) { struct bonding *bond = netdev_priv(bond_dev); struct slave *slave; int i, res; bond_for_each_slave(bond, slave, i) { struct net_device *slave_dev = slave->dev; const struct net_device_ops *slave_ops = slave_dev->netdev_ops; if ((slave_dev->features & NETIF_F_HW_VLAN_FILTER) && slave_ops->ndo_vlan_rx_kill_vid) { slave_ops->ndo_vlan_rx_kill_vid(slave_dev, vid); } } res = bond_del_vlan(bond, vid); if (res) { pr_err("%s: Error: Failed to remove vlan id %d\n", bond_dev->name, vid); } } 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: unsigned long perf_instruction_pointer(struct pt_regs *regs) { unsigned long ip; if (TRAP(regs) != 0xf00) return regs->nip; /* not a PMU interrupt */ ip = mfspr(SPRN_SIAR) + perf_ip_adjust(regs); return ip; } 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 NetworkHandler::SetNetworkConditions( network::mojom::NetworkConditionsPtr conditions) { if (!process_) return; StoragePartition* partition = process_->GetStoragePartition(); network::mojom::NetworkContext* context = partition->GetNetworkContext(); context->SetNetworkConditions(host_id_, std::move(conditions)); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 Target: 1 Example 2: Code: virtual status_t allocateBufferWithBackup( node_id node, OMX_U32 port_index, const sp<IMemory> &params, buffer_id *buffer) { Parcel data, reply; data.writeInterfaceToken(IOMX::getInterfaceDescriptor()); data.writeInt32((int32_t)node); data.writeInt32(port_index); data.writeStrongBinder(params->asBinder()); remote()->transact(ALLOC_BUFFER_WITH_BACKUP, data, &reply); status_t err = reply.readInt32(); if (err != OK) { *buffer = 0; return err; } *buffer = (buffer_id)reply.readInt32(); return err; } Commit Message: Clear allocation to avoid info leak Bug: 26914474 Change-Id: Ie1a86e86d78058d041149fe599a4996e7f8185cf 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: URLRequestContext* BrowserContextIOData::CreateMainRequestContext( content::ProtocolHandlerMap& protocol_handlers, content::URLRequestInterceptorScopedVector request_interceptors) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(!main_request_context_); std::unique_ptr<net::CookieStore> cookie_store; scoped_refptr<net::SQLiteChannelIDStore> channel_id_store; if (!IsOffTheRecord() && !GetPath().empty()) { cookie_store = content::CreateCookieStore( content::CookieStoreConfig(GetPath().Append(kCookiesFilename), GetSessionCookieMode(), nullptr, nullptr)); channel_id_store = new net::SQLiteChannelIDStore( GetPath().Append(kChannelIDFilename), content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner( base::SequencedWorkerPool::GetSequenceToken())); } else { cookie_store = content::CreateCookieStore(content::CookieStoreConfig()); } cookie_store_owner_->set_store(std::move(cookie_store)); IOThread::Globals* io_thread_globals = IOThread::instance()->globals(); ssl_config_service_ = new SSLConfigService(); http_user_agent_settings_.reset(new HttpUserAgentSettings(this)); ftp_transaction_factory_.reset( new net::FtpNetworkLayer(io_thread_globals->host_resolver())); http_server_properties_.reset(new net::HttpServerPropertiesImpl()); network_delegate_.reset(new NetworkDelegate(this)); transport_security_state_.reset(new net::TransportSecurityState()); transport_security_persister_.reset( new net::TransportSecurityPersister( transport_security_state_.get(), GetPath(), content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::FILE), IsOffTheRecord())); host_mapping_rules_.reset(new net::HostMappingRules()); const std::vector<std::string>& host_mapping_rules = GetSharedData().host_mapping_rules; for (std::vector<std::string>::const_iterator it = host_mapping_rules.begin(); it != host_mapping_rules.end(); ++it) { host_mapping_rules_->AddRuleFromString(*it); } main_request_context_.reset(new URLRequestContext()); URLRequestContext* context = main_request_context_.get(); net::URLRequestContextStorage* storage = context->storage(); storage->set_ssl_config_service(ssl_config_service_.get()); context->set_network_delegate(network_delegate_.get()); context->set_http_user_agent_settings(http_user_agent_settings_.get()); storage->set_channel_id_service( base::MakeUnique<net::ChannelIDService>( new net::DefaultChannelIDStore(channel_id_store.get()), base::WorkerPool::GetTaskRunner(true))); context->set_http_server_properties(http_server_properties_.get()); context->set_cookie_store(cookie_store_owner_->store()); context->set_transport_security_state(transport_security_state_.get()); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&CleanupOldCacheDir, GetCachePath().Append(kCacheDirname))); std::unique_ptr<net::HttpCache::BackendFactory> cache_backend; if (IsOffTheRecord() || GetCachePath().empty()) { cache_backend = net::HttpCache::DefaultBackend::InMemory(0); } else { cache_backend.reset(new net::HttpCache::DefaultBackend( net::DISK_CACHE, net::CACHE_BACKEND_SIMPLE, GetCachePath().Append(kCacheDirname2), GetMaxCacheSizeHint() * 1024 * 1024, // MB -> bytes content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::CACHE))); } net::HttpNetworkSession::Params session_params; session_params.host_resolver = context->host_resolver(); session_params.cert_verifier = context->cert_verifier(); session_params.channel_id_service = context->channel_id_service(); session_params.transport_security_state = context->transport_security_state(); session_params.cert_transparency_verifier = context->cert_transparency_verifier(); session_params.ct_policy_enforcer = context->ct_policy_enforcer(); session_params.proxy_service = context->proxy_service(); session_params.ssl_config_service = context->ssl_config_service(); session_params.http_auth_handler_factory = context->http_auth_handler_factory(); session_params.http_server_properties = context->http_server_properties(); session_params.net_log = context->net_log(); session_params.host_mapping_rules = host_mapping_rules_.get(); http_network_session_ = base::WrapUnique(new net::HttpNetworkSession(session_params)); { base::ThreadRestrictions::ScopedAllowIO allow_io; storage->set_http_transaction_factory( base::WrapUnique( new net::HttpCache(http_network_session_.get(), std::move(cache_backend), true))); } std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory( new net::URLRequestJobFactoryImpl()); bool set_protocol = false; for (content::ProtocolHandlerMap::iterator it = protocol_handlers.begin(); it != protocol_handlers.end(); ++it) { set_protocol = job_factory->SetProtocolHandler(it->first, base::WrapUnique(it->second.release())); DCHECK(set_protocol); } protocol_handlers.clear(); set_protocol = job_factory->SetProtocolHandler( oxide::kFileScheme, base::WrapUnique( new net::FileProtocolHandler( content::BrowserThread::GetTaskRunnerForThread( content::BrowserThread::FILE)))); DCHECK(set_protocol); set_protocol = job_factory->SetProtocolHandler( oxide::kDataScheme, base::WrapUnique(new net::DataProtocolHandler())); DCHECK(set_protocol); set_protocol = job_factory->SetProtocolHandler( oxide::kFtpScheme, base::WrapUnique(new net::FtpProtocolHandler( ftp_transaction_factory_.get()))); DCHECK(set_protocol); std::unique_ptr<net::URLRequestJobFactory> top_job_factory( new URLRequestDelegatedJobFactory(std::move(job_factory), this)); for (content::URLRequestInterceptorScopedVector::reverse_iterator it = request_interceptors.rbegin(); it != request_interceptors.rend(); ++it) { top_job_factory.reset( new net::URLRequestInterceptingJobFactory(std::move(top_job_factory), base::WrapUnique(*it))); } request_interceptors.weak_clear(); storage->set_job_factory(std::move(top_job_factory)); resource_context_->request_context_ = context; return main_request_context_.get(); } 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: void CreateFile(const FilePath& file_path) { const std::string kFoo = "foo"; ASSERT_TRUE(file_util::WriteFile(file_path, kFoo.data(), kFoo.size())) << ": " << file_path.value(); } 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 Target: 1 Example 2: Code: bool HTMLMediaElement::layoutObjectIsNeeded(const ComputedStyle& style) { return shouldShowControls() && HTMLElement::layoutObjectIsNeeded(style); } Commit Message: [Blink>Media] Allow autoplay muted on Android by default There was a mistake causing autoplay muted is shipped on Android but it will be disabled if the chromium embedder doesn't specify content setting for "AllowAutoplay" preference. This CL makes the AllowAutoplay preference true by default so that it is allowed by embedders (including AndroidWebView) unless they explicitly disable it. Intent to ship: https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ BUG=689018 Review-Url: https://codereview.chromium.org/2677173002 Cr-Commit-Position: refs/heads/master@{#448423} 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 RenderWidgetHostImpl::SetIgnoreInputEvents(bool ignore_input_events) { ignore_input_events_ = ignore_input_events; } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SPL_METHOD(SplFileInfo, getFileInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; 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) { spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC); } 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 perf_group_attach(struct perf_event *event) { struct perf_event *group_leader = event->group_leader, *pos; /* * We can have double attach due to group movement in perf_event_open. */ if (event->attach_state & PERF_ATTACH_GROUP) return; event->attach_state |= PERF_ATTACH_GROUP; if (group_leader == event) return; if (group_leader->group_flags & PERF_GROUP_SOFTWARE && !is_software_event(event)) group_leader->group_flags &= ~PERF_GROUP_SOFTWARE; list_add_tail(&event->group_entry, &group_leader->sibling_list); group_leader->nr_siblings++; perf_event__header_size(group_leader); list_for_each_entry(pos, &group_leader->sibling_list, group_entry) perf_event__header_size(pos); } 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: 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 extract_command_name(int index, char **argv) { EUID_ASSERT(); assert(argv); assert(argv[index]); cfg.original_program_index = index; char *str = strdup(argv[index]); if (!str) errExit("strdup"); cfg.command_name = str; if (!cfg.command_name) errExit("strdup"); char *ptr = cfg.command_name; while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0') ptr++; *ptr = '\0'; ptr = strrchr(cfg.command_name, '/'); if (ptr) { ptr++; if (*ptr == '\0') { fprintf(stderr, "Error: invalid command name\n"); exit(1); } char *tmp = strdup(ptr); if (!tmp) errExit("strdup"); char *ptr2 = tmp; while (*ptr2 != '.' && *ptr2 != '\0') ptr2++; *ptr2 = '\0'; free(cfg.command_name); cfg.command_name = tmp; } } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269 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 dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; int interlaced = dctx->interlaced; int cur_field = dctx->cur_field; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; interlaced = (state&2)>>1; /* byte following the 5-byte header prefix */ cur_field = state&1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; if (cid <= 0) continue; dctx->remaining = avpriv_dnxhd_get_frame_size(cid); if (dctx->remaining <= 0) { dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (dctx->remaining <= 0) return dctx->remaining; } if (buf_size - i >= dctx->remaining && (!dctx->interlaced || dctx->cur_field)) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->interlaced = interlaced; dctx->cur_field = 0; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->interlaced = interlaced; dctx->cur_field = 0; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; dctx->interlaced = interlaced; dctx->cur_field = cur_field; return END_NOT_FOUND; } Commit Message: avcodec/dnxhd_parser: Do not return invalid value from dnxhd_find_frame_end() on error Fixes: Null pointer dereference Fixes: CVE-2017-9608 Found-by: Yihan Lian Signed-off-by: Michael Niedermayer <[email protected]> (cherry picked from commit 611b35627488a8d0763e75c25ee0875c5b7987dd) Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: void WebPluginProxy::OnPaint(const gfx::Rect& damaged_rect) { content::GetContentClient()->SetActiveURL(page_url_); Paint(damaged_rect); bool allow_buffer_flipping; #if defined(OS_MACOSX) allow_buffer_flipping = delegate_->AllowBufferFlipping(); #else allow_buffer_flipping = true; #endif Send(new PluginHostMsg_InvalidateRect(route_id_, damaged_rect, allow_buffer_flipping)); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void __kprobes single_step_exception(struct pt_regs *regs) { regs->msr &= ~(MSR_SE | MSR_BE); /* Turn off 'trace' bits */ if (notify_die(DIE_SSTEP, "single_step", regs, 5, 5, SIGTRAP) == NOTIFY_STOP) return; if (debugger_sstep(regs)) return; _exception(SIGTRAP, regs, TRAP_TRACE, regs->nip); } Commit Message: [POWERPC] Never panic when taking altivec exceptions from userspace At the moment we rely on a cpu feature bit or a firmware property to detect altivec. If we dont have either of these and the cpu does in fact support altivec we can cause a panic from userspace. It seems safer to always send a signal if we manage to get an 0xf20 exception from userspace. Signed-off-by: Anton Blanchard <[email protected]> Signed-off-by: Paul Mackerras <[email protected]> CWE ID: CWE-19 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 WebContentsImpl::IsLoading() const { return frame_tree_.IsLoading() && !(ShowingInterstitialPage() && GetRenderManager()->interstitial_page()->pause_throbber()); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20 Target: 1 Example 2: Code: ExecuteCodeFunction::InitResult ExecuteCodeInTabFunction::Init() { if (init_result_) return init_result_.value(); int tab_id = -1; if (args_->GetInteger(0, &tab_id) && tab_id < 0) return set_init_result(VALIDATION_FAILURE); base::DictionaryValue* details_value = NULL; if (!args_->GetDictionary(1, &details_value)) return set_init_result(VALIDATION_FAILURE); std::unique_ptr<InjectDetails> details(new InjectDetails()); if (!InjectDetails::Populate(*details_value, details.get())) return set_init_result(VALIDATION_FAILURE); if (tab_id == -1) { Browser* browser = chrome_details_.GetCurrentBrowser(); if (!browser) return set_init_result_error(tabs_constants::kNoCurrentWindowError); content::WebContents* web_contents = NULL; if (!ExtensionTabUtil::GetDefaultTab(browser, &web_contents, &tab_id)) return set_init_result_error(tabs_constants::kNoTabInBrowserWindowError); } execute_tab_id_ = tab_id; details_ = std::move(details); set_host_id(HostID(HostID::EXTENSIONS, extension()->id())); return set_init_result(SUCCESS); } Commit Message: Call CanCaptureVisiblePage in page capture API. Currently the pageCapture permission allows access to arbitrary local files and chrome:// pages which can be a security concern. In order to address this, the page capture API needs to be changed similar to the captureVisibleTab API. The API will now only allow extensions to capture otherwise-restricted URLs if the user has granted activeTab. In addition, file:// URLs are only capturable with the "Allow on file URLs" option enabled. Bug: 893087 Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624 Reviewed-on: https://chromium-review.googlesource.com/c/1330689 Commit-Queue: Bettina Dea <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Varun Khaneja <[email protected]> Cr-Commit-Position: refs/heads/master@{#615248} 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: run_cmd(int fd, ...) { pid_t pid; sigset_t sigm, sigm_old; /* block signals, let child establish its own handlers */ sigemptyset(&sigm); sigaddset(&sigm, SIGTERM); sigprocmask(SIG_BLOCK, &sigm, &sigm_old); pid = fork(); if ( pid < 0 ) { sigprocmask(SIG_SETMASK, &sigm_old, NULL); fd_printf(STO, "*** cannot fork: %s ***\r\n", strerror(errno)); return -1; } else if ( pid ) { /* father: picocom */ int status, r; /* reset the mask */ sigprocmask(SIG_SETMASK, &sigm_old, NULL); /* wait for child to finish */ do { r = waitpid(pid, &status, 0); } while ( r < 0 && errno == EINTR ); /* reset terminal (back to raw mode) */ term_apply(STI); /* check and report child return status */ if ( WIFEXITED(status) ) { fd_printf(STO, "\r\n*** exit status: %d ***\r\n", WEXITSTATUS(status)); return WEXITSTATUS(status); } else if ( WIFSIGNALED(status) ) { fd_printf(STO, "\r\n*** killed by signal: %d ***\r\n", WTERMSIG(status)); return -1; } else { fd_printf(STO, "\r\n*** abnormal termination: 0x%x ***\r\n", r); return -1; } } else { /* child: external program */ long fl; char cmd[512]; /* unmanage terminal, and reset it to canonical mode */ term_remove(STI); /* unmanage serial port fd, without reset */ term_erase(fd); /* set serial port fd to blocking mode */ fl = fcntl(fd, F_GETFL); fl &= ~O_NONBLOCK; fcntl(fd, F_SETFL, fl); /* connect stdin and stdout to serial port */ close(STI); close(STO); dup2(fd, STI); dup2(fd, STO); { /* build command-line */ char *c, *ce; const char *s; int n; va_list vls; strcpy(cmd, EXEC); c = &cmd[sizeof(EXEC)- 1]; ce = cmd + sizeof(cmd) - 1; va_start(vls, fd); while ( (s = va_arg(vls, const char *)) ) { n = strlen(s); if ( c + n + 1 >= ce ) break; memcpy(c, s, n); c += n; *c++ = ' '; } va_end(vls); *c = '\0'; } /* run extenral command */ fd_printf(STDERR_FILENO, "%s\n", &cmd[sizeof(EXEC) - 1]); establish_child_signal_handlers(); sigprocmask(SIG_SETMASK, &sigm_old, NULL); execl("/bin/sh", "sh", "-c", cmd, NULL); exit(42); } } Commit Message: Do not use "/bin/sh" to run external commands. Picocom no longer uses /bin/sh to run external commands for file-transfer operations. Parsing the command line and spliting it into arguments is now performed internally by picocom, using quoting rules very similar to those of the Unix shell. Hopefully, this makes it impossible to inject shell-commands when supplying filenames or extra arguments to the send- and receive-file commands. CWE ID: CWE-77 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: netscreen_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { int pkt_len; char line[NETSCREEN_LINE_LENGTH]; char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH]; gboolean cap_dir; char cap_dst[13]; if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) { return FALSE; } if (file_gets(line, NETSCREEN_LINE_LENGTH, wth->random_fh) == NULL) { *err = file_error(wth->random_fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } pkt_len = parse_netscreen_rec_hdr(phdr, line, cap_int, &cap_dir, cap_dst, err, err_info); if (pkt_len == -1) return FALSE; if (!parse_netscreen_hex_dump(wth->random_fh, pkt_len, cap_int, cap_dst, phdr, buf, err, err_info)) return FALSE; return TRUE; } Commit Message: Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12396 Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f Reviewed-on: https://code.wireshark.org/review/15176 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: void LayerTreeHostQt::removeTile(WebLayerID layerID, int tileID) { m_webPage->send(Messages::LayerTreeHostProxy::RemoveTileForLayer(layerID, tileID)); } Commit Message: [Qt][WK2] Allow transparent WebViews https://bugs.webkit.org/show_bug.cgi?id=80608 Reviewed by Tor Arne Vestbø. Added support for transparentBackground in QQuickWebViewExperimental. This uses the existing drawsTransparentBackground property in WebKit2. Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes, otherwise the change doesn't take effect. A new API test was added. * UIProcess/API/qt/qquickwebview.cpp: (QQuickWebViewPrivate::setTransparentBackground): (QQuickWebViewPrivate::transparentBackground): (QQuickWebViewExperimental::transparentBackground): (QQuickWebViewExperimental::setTransparentBackground): * UIProcess/API/qt/qquickwebview_p.h: * UIProcess/API/qt/qquickwebview_p_p.h: (QQuickWebViewPrivate): * UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp: (tst_QQuickWebView): (tst_QQuickWebView::transparentWebViews): * WebProcess/WebPage/qt/LayerTreeHostQt.cpp: (WebKit::LayerTreeHostQt::LayerTreeHostQt): (WebKit::LayerTreeHostQt::setRootCompositingLayer): git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int attr_list_has_file( const char *attr, const char *path ) { char const *file; MyString str; file = condor_basename(path); Shadow->getJobAd()->LookupString(attr,str); StringList list(str.Value()); if( list.contains_withwildcard(path) || list.contains_withwildcard(file) ) { return 1; } else { return 0; } } Commit Message: CWE ID: CWE-134 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 VaapiJpegDecoder::Initialize(const base::RepeatingClosure& error_uma_cb) { vaapi_wrapper_ = VaapiWrapper::Create(VaapiWrapper::kDecode, VAProfileJPEGBaseline, error_uma_cb); if (!vaapi_wrapper_) { VLOGF(1) << "Failed initializing VAAPI"; return false; } return true; } Commit Message: Move Initialize() to VaapiImageDecoder parent class. This CL moves the implementation of Initialize() to VaapiImageDecoder, since it is common to all implementing classes. Bug: 877694 Test: jpeg_decode_accelerator_unittest Change-Id: Ic99601953ae1c7a572ba8a0b0bf43675b2b0969d Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1654249 Commit-Queue: Gil Dekel <[email protected]> Reviewed-by: Andres Calderon Jaramillo <[email protected]> Reviewed-by: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#668645} CWE ID: CWE-79 Target: 1 Example 2: Code: static void deactivate_slab(struct kmem_cache *s, struct kmem_cache_cpu *c) { struct page *page = c->page; int tail = 1; if (page->freelist) stat(c, DEACTIVATE_REMOTE_FREES); /* * Merge cpu freelist into slab freelist. Typically we get here * because both freelists are empty. So this is unlikely * to occur. */ while (unlikely(c->freelist)) { void **object; tail = 0; /* Hot objects. Put the slab first */ /* Retrieve object from cpu_freelist */ object = c->freelist; c->freelist = c->freelist[c->offset]; /* And put onto the regular freelist */ object[c->offset] = page->freelist; page->freelist = object; page->inuse--; } c->page = NULL; unfreeze_slab(s, page, tail); } 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: static void Rp_exec(js_State *J) { js_RegExp_prototype_exec(J, js_toregexp(J, 0), js_tostring(J, 1)); } 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 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: char *ldb_dn_escape_value(TALLOC_CTX *mem_ctx, struct ldb_val value) { char *dst; if (!value.length) return NULL; /* allocate destination string, it will be at most 3 times the source */ dst = talloc_array(mem_ctx, char, value.length * 3 + 1); if ( ! dst) { talloc_free(dst); return NULL; } ldb_dn_escape_internal(dst, (const char *)value.data, value.length); dst = talloc_realloc(mem_ctx, dst, char, strlen(dst) + 1); return dst; } Commit Message: CWE ID: CWE-200 Target: 1 Example 2: Code: bool InspectorPageAgent::deviceMetricsOverrideEnabled() { return m_enabled && m_deviceMetricsOverridden; } Commit Message: DevTools: remove references to modules/device_orientation from core BUG=340221 Review URL: https://codereview.chromium.org/150913003 git-svn-id: svn://svn.chromium.org/blink/trunk@166493 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: void V8Float64Array::derefObject(void* object) { static_cast<Float64Array*>(object)->deref(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: 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: privsep_preauth(Authctxt *authctxt) { int status, r; pid_t pid; struct ssh_sandbox *box = NULL; /* Set up unprivileged child process to deal with network data */ pmonitor = monitor_init(); /* Store a pointer to the kex for later rekeying */ pmonitor->m_pkex = &active_state->kex; if (use_privsep == PRIVSEP_ON) box = ssh_sandbox_init(); pid = fork(); if (pid == -1) { fatal("fork of unprivileged child failed"); } else if (pid != 0) { debug2("Network child is on pid %ld", (long)pid); pmonitor->m_pid = pid; if (have_agent) { r = ssh_get_authentication_socket(&auth_sock); if (r != 0) { error("Could not get agent socket: %s", ssh_err(r)); have_agent = 0; } } if (box != NULL) ssh_sandbox_parent_preauth(box, pid); monitor_child_preauth(authctxt, pmonitor); /* Sync memory */ monitor_sync(pmonitor); /* Wait for the child's exit status */ while (waitpid(pid, &status, 0) < 0) { if (errno == EINTR) continue; pmonitor->m_pid = -1; fatal("%s: waitpid: %s", __func__, strerror(errno)); } privsep_is_preauth = 0; pmonitor->m_pid = -1; if (WIFEXITED(status)) { if (WEXITSTATUS(status) != 0) fatal("%s: preauth child exited with status %d", __func__, WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) fatal("%s: preauth child terminated by signal %d", __func__, WTERMSIG(status)); if (box != NULL) ssh_sandbox_parent_finish(box); return 1; } else { /* child */ close(pmonitor->m_sendfd); close(pmonitor->m_log_recvfd); /* Arrange for logging to be sent to the monitor */ set_log_handler(mm_log_handler, pmonitor); privsep_preauth_child(); setproctitle("%s", "[net]"); if (box != NULL) ssh_sandbox_child(box); return 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: 1 Example 2: Code: virDomainLookupByID(virConnectPtr conn, int id) { VIR_DEBUG("conn=%p, id=%d", conn, id); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNegativeArgGoto(id, error); if (conn->driver->domainLookupByID) { virDomainPtr ret; ret = conn->driver->domainLookupByID(conn, id); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } Commit Message: virDomainGetTime: Deny on RO connections We have a policy that if API may end up talking to a guest agent it should require RW connection. We don't obey the rule in virDomainGetTime(). Signed-off-by: Michal Privoznik <[email protected]> CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void webkitWebViewBaseExitFullScreen(WebKitWebViewBase* webkitWebViewBase) { #if ENABLE(FULLSCREEN_API) WebKitWebViewBasePrivate* priv = webkitWebViewBase->priv; if (!priv->fullScreenModeActive) return; if (!priv->fullScreenClient.willExitFullScreen()) return; WebFullScreenManagerProxy* fullScreenManagerProxy = priv->pageProxy->fullScreenManager(); fullScreenManagerProxy->willExitFullScreen(); GtkWidget* topLevelWindow = gtk_widget_get_toplevel(GTK_WIDGET(webkitWebViewBase)); if (gtk_widget_is_toplevel(topLevelWindow)) gtk_window_unfullscreen(GTK_WINDOW(topLevelWindow)); fullScreenManagerProxy->didExitFullScreen(); priv->fullScreenModeActive = false; #endif } Commit Message: [GTK] Inspector should set a default attached height before being attached https://bugs.webkit.org/show_bug.cgi?id=90767 Reviewed by Xan Lopez. We are currently using the minimum attached height in WebKitWebViewBase as the default height for the inspector when attached. It would be easier for WebKitWebViewBase and embedders implementing attach() if the inspector already had an attached height set when it's being attached. * UIProcess/API/gtk/WebKitWebViewBase.cpp: (webkitWebViewBaseContainerAdd): Don't initialize inspectorViewHeight. (webkitWebViewBaseSetInspectorViewHeight): Allow to set the inspector view height before having an inpector view, but only queue a resize when the view already has an inspector view. * UIProcess/API/gtk/tests/TestInspector.cpp: (testInspectorDefault): (testInspectorManualAttachDetach): * UIProcess/gtk/WebInspectorProxyGtk.cpp: (WebKit::WebInspectorProxy::platformAttach): Set the default attached height before attach the inspector view. git-svn-id: svn://svn.chromium.org/blink/trunk@124479 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: ipt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); const struct iphdr *ip; /* Initializing verdict to NF_DROP keeps gcc happy. */ unsigned int verdict = NF_DROP; const char *indev, *outdev; const void *table_base; struct ipt_entry *e, **jumpstack; unsigned int stackidx, cpu; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; /* Initialization */ stackidx = 0; ip = ip_hdr(skb); indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; /* We handle fragments by dealing with the first fragment as * if it was a normal packet. All other fragments are treated * normally, except that they will NEVER match rules that ask * things we don't know, ie. tcp syn flag or ports). If the * rule is also a fragment-specific rule, non-fragments won't * match it. */ acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET; acpar.thoff = ip_hdrlen(skb); acpar.hotdrop = false; acpar.state = state; WARN_ON(!(table->valid_hooks & (1 << hook))); local_bh_disable(); addend = xt_write_recseq_begin(); private = READ_ONCE(table->private); /* Address dependency. */ cpu = smp_processor_id(); table_base = private->entries; jumpstack = (struct ipt_entry **)private->jumpstack[cpu]; /* Switch to alternate jumpstack if we're being invoked via TEE. * TEE issues XT_CONTINUE verdict on original skb so we must not * clobber the jumpstack. * * For recursion via REJECT or SYNPROXY the stack will be clobbered * but it is no problem since absolute verdict is issued by these. */ if (static_key_false(&xt_tee_enabled)) jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated); e = get_entry(table_base, private->hook_entry[hook]); do { const struct xt_entry_target *t; const struct xt_entry_match *ematch; struct xt_counters *counter; WARN_ON(!e); if (!ip_packet_match(ip, indev, outdev, &e->ip, acpar.fragoff)) { no_match: e = ipt_next_entry(e); continue; } xt_ematch_foreach(ematch, e) { acpar.match = ematch->u.kernel.match; acpar.matchinfo = ematch->data; if (!acpar.match->match(skb, &acpar)) goto no_match; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, skb->len, 1); t = ipt_get_target(e); WARN_ON(!t->u.kernel.target); #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) /* The packet is traced: log it */ if (unlikely(skb->nf_trace)) trace_packet(state->net, skb, hook, state->in, state->out, table->name, private, e); #endif /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); } else { e = jumpstack[--stackidx]; e = ipt_next_entry(e); } continue; } if (table_base + v != ipt_next_entry(e) && !(e->ip.flags & IPT_F_GOTO)) jumpstack[stackidx++] = e; e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); if (verdict == XT_CONTINUE) { /* Target might have changed stuff. */ ip = ip_hdr(skb); e = ipt_next_entry(e); } else { /* Verdict */ break; } } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } Commit Message: netfilter: add back stackpointer size checks The rationale for removing the check is only correct for rulesets generated by ip(6)tables. In iptables, a jump can only occur to a user-defined chain, i.e. because we size the stack based on number of user-defined chains we cannot exceed stack size. However, the underlying binary format has no such restriction, and the validation step only ensures that the jump target is a valid rule start point. IOW, its possible to build a rule blob that has no user-defined chains but does contain a jump. If this happens, no jump stack gets allocated and crash occurs because no jumpstack was allocated. Fixes: 7814b6ec6d0d6 ("netfilter: xtables: don't save/restore jumpstack offset") Reported-by: [email protected] Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer) { while (renderer && !(renderer->isBox() && toRenderBox(renderer)->canAutoscroll())) { if (!renderer->parent() && renderer->node() == renderer->document() && renderer->document().ownerElement()) renderer = renderer->document().ownerElement()->renderer(); else renderer = renderer->parent(); } return renderer && renderer->isBox() ? toRenderBox(renderer) : 0; } 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 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 ap_device_probe(struct device *dev) { struct ap_device *ap_dev = to_ap_dev(dev); struct ap_driver *ap_drv = to_ap_drv(dev->driver); int rc; ap_dev->drv = ap_drv; spin_lock_bh(&ap_device_list_lock); list_add(&ap_dev->list, &ap_device_list); spin_unlock_bh(&ap_device_list_lock); rc = ap_drv->probe ? ap_drv->probe(ap_dev) : -ENODEV; if (rc) { spin_lock_bh(&ap_device_list_lock); list_del_init(&ap_dev->list); spin_unlock_bh(&ap_device_list_lock); } return rc; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Utterance::Utterance(Profile* profile, const std::string& text, DictionaryValue* options, Task* completion_task) : profile_(profile), id_(next_utterance_id_++), text_(text), rate_(-1.0), pitch_(-1.0), volume_(-1.0), can_enqueue_(false), completion_task_(completion_task) { if (!options) { options_.reset(new DictionaryValue()); return; } options_.reset(options->DeepCopy()); if (options->HasKey(util::kVoiceNameKey)) options->GetString(util::kVoiceNameKey, &voice_name_); if (options->HasKey(util::kLocaleKey)) options->GetString(util::kLocaleKey, &locale_); if (options->HasKey(util::kGenderKey)) options->GetString(util::kGenderKey, &gender_); if (options->GetDouble(util::kRateKey, &rate_)) { if (!base::IsFinite(rate_) || rate_ < 0.0 || rate_ > 1.0) rate_ = -1.0; } if (options->GetDouble(util::kPitchKey, &pitch_)) { if (!base::IsFinite(pitch_) || pitch_ < 0.0 || pitch_ > 1.0) pitch_ = -1.0; } if (options->GetDouble(util::kVolumeKey, &volume_)) { if (!base::IsFinite(volume_) || volume_ < 0.0 || volume_ > 1.0) volume_ = -1.0; } if (options->HasKey(util::kEnqueueKey)) options->GetBoolean(util::kEnqueueKey, &can_enqueue_); } 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: server_file(struct httpd *env, struct client *clt) { struct http_descriptor *desc = clt->clt_descreq; struct server_config *srv_conf = clt->clt_srv_conf; char path[PATH_MAX]; const char *stripped, *errstr = NULL; int ret = 500; if (srv_conf->flags & SRVFLAG_FCGI) return (server_fcgi(env, clt)); /* Request path is already canonicalized */ stripped = server_root_strip( desc->http_path_alias != NULL ? desc->http_path_alias : desc->http_path, srv_conf->strip); if ((size_t)snprintf(path, sizeof(path), "%s%s", srv_conf->root, stripped) >= sizeof(path)) { errstr = desc->http_path; goto abort; } /* Returns HTTP status code on error */ if ((ret = server_file_access(env, clt, path, sizeof(path))) > 0) { errstr = desc->http_path_alias != NULL ? desc->http_path_alias : desc->http_path; goto abort; } return (ret); abort: if (errstr == NULL) errstr = strerror(errno); server_abort_http(clt, ret, errstr); return (-1); } Commit Message: Reimplement httpd's support for byte ranges. The previous implementation loaded all the output into a single output buffer and used its size to determine the Content-Length of the body. The new implementation calculates the body length first and writes the individual ranges in an async way using the bufferevent mechanism. This prevents httpd from using too much memory and applies the watermark and throttling mechanisms to range requests. Problem reported by Pierre Kim (pierre.kim.sec at gmail.com) OK benno@ sunil@ CWE ID: CWE-770 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 BluetoothDeviceChromeOS::ExpectingPinCode() const { return !pincode_callback_.is_null(); } 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: 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 mp_unpack_full(lua_State *L, int limit, int offset) { size_t len; const char *s; mp_cur c; int cnt; /* Number of objects unpacked */ int decode_all = (!limit && !offset); s = luaL_checklstring(L,1,&len); /* if no match, exits */ if (offset < 0 || limit < 0) /* requesting negative off or lim is invalid */ return luaL_error(L, "Invalid request to unpack with offset of %d and limit of %d.", offset, len); else if (offset > len) return luaL_error(L, "Start offset %d greater than input length %d.", offset, len); if (decode_all) limit = INT_MAX; mp_cur_init(&c,(const unsigned char *)s+offset,len-offset); /* We loop over the decode because this could be a stream * of multiple top-level values serialized together */ for(cnt = 0; c.left > 0 && cnt < limit; cnt++) { mp_decode_to_lua_type(L,&c); if (c.err == MP_CUR_ERROR_EOF) { return luaL_error(L,"Missing bytes in input."); } else if (c.err == MP_CUR_ERROR_BADFMT) { return luaL_error(L,"Bad data format in input."); } } if (!decode_all) { /* c->left is the remaining size of the input buffer. * subtract the entire buffer size from the unprocessed size * to get our next start offset */ int offset = len - c.left; /* Return offset -1 when we have have processed the entire buffer. */ lua_pushinteger(L, c.left == 0 ? -1 : offset); /* Results are returned with the arg elements still * in place. Lua takes care of only returning * elements above the args for us. * In this case, we have one arg on the stack * for this function, so we insert our first return * value at position 2. */ lua_insert(L, 2); cnt += 1; /* increase return count by one to make room for offset */ } return cnt; } Commit Message: Security: more cmsgpack fixes by @soloestoy. @soloestoy sent me this additional fixes, after searching for similar problems to the one reported in mp_pack(). I'm committing the changes because it was not possible during to make a public PR to protect Redis users and give Redis providers some time to patch their systems. CWE ID: CWE-119 Target: 1 Example 2: Code: void setJSTestObjConditionalAttr4Constructor(ExecState* exec, JSObject* thisObject, JSValue value) { jsCast<JSTestObj*>(thisObject)->putDirect(exec->globalData(), Identifier(exec, "conditionalAttr4"), value); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool DownloadManagerImpl::InterceptDownload( const download::DownloadCreateInfo& info) { WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID( info.render_process_id, info.render_frame_id); if (info.is_new_download && info.result == download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) { if (web_contents) { std::vector<GURL> url_chain(info.url_chain); GURL url = url_chain.back(); url_chain.pop_back(); NavigationController::LoadURLParams params(url); params.has_user_gesture = info.has_user_gesture; params.referrer = Referrer( info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy( info.referrer_policy)); params.redirect_chain = url_chain; web_contents->GetController().LoadURLWithParams(params); } if (info.request_handle) info.request_handle->CancelRequest(false); return true; } if (!delegate_ || !delegate_->InterceptDownloadIfApplicable( info.url(), info.mime_type, info.request_origin, web_contents)) { return false; } if (info.request_handle) info.request_handle->CancelRequest(false); return true; } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} 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: static struct ip_options *ip_options_get_alloc(const int optlen) { return kzalloc(sizeof(struct ip_options) + ((optlen + 3) & ~3), GFP_KERNEL); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: WRITE_TRAN ossl_statem_client_write_transition(SSL *s) { OSSL_STATEM *st = &s->statem; switch (st->hand_state) { case TLS_ST_OK: /* Renegotiation - fall through */ case TLS_ST_BEFORE: st->hand_state = TLS_ST_CW_CLNT_HELLO; return WRITE_TRAN_CONTINUE; case TLS_ST_CW_CLNT_HELLO: /* * No transition at the end of writing because we don't know what * we will be sent */ return WRITE_TRAN_FINISHED; case DTLS_ST_CR_HELLO_VERIFY_REQUEST: st->hand_state = TLS_ST_CW_CLNT_HELLO; return WRITE_TRAN_CONTINUE; case TLS_ST_CR_SRVR_DONE: if (s->s3->tmp.cert_req) st->hand_state = TLS_ST_CW_CERT; else st->hand_state = TLS_ST_CW_KEY_EXCH; return WRITE_TRAN_CONTINUE; case TLS_ST_CW_CERT: st->hand_state = TLS_ST_CW_KEY_EXCH; return WRITE_TRAN_CONTINUE; case TLS_ST_CW_KEY_EXCH: /* * For TLS, cert_req is set to 2, so a cert chain of nothing is * sent, but no verify packet is sent */ /* * XXX: For now, we do not support client authentication in ECDH * cipher suites with ECDH (rather than ECDSA) certificates. We * need to skip the certificate verify message when client's * ECDH public key is sent inside the client certificate. */ if (s->s3->tmp.cert_req == 1) { st->hand_state = TLS_ST_CW_CERT_VRFY; } else { st->hand_state = TLS_ST_CW_CHANGE; } if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) { st->hand_state = TLS_ST_CW_CHANGE; } return WRITE_TRAN_CONTINUE; case TLS_ST_CW_CERT_VRFY: st->hand_state = TLS_ST_CW_CHANGE; return WRITE_TRAN_CONTINUE; case TLS_ST_CW_CHANGE: #if defined(OPENSSL_NO_NEXTPROTONEG) st->hand_state = TLS_ST_CW_FINISHED; #else if (!SSL_IS_DTLS(s) && s->s3->next_proto_neg_seen) st->hand_state = TLS_ST_CW_NEXT_PROTO; else st->hand_state = TLS_ST_CW_FINISHED; #endif return WRITE_TRAN_CONTINUE; #if !defined(OPENSSL_NO_NEXTPROTONEG) case TLS_ST_CW_NEXT_PROTO: st->hand_state = TLS_ST_CW_FINISHED; return WRITE_TRAN_CONTINUE; #endif case TLS_ST_CW_FINISHED: if (s->hit) { st->hand_state = TLS_ST_OK; ossl_statem_set_in_init(s, 0); return WRITE_TRAN_CONTINUE; } else { return WRITE_TRAN_FINISHED; } case TLS_ST_CR_FINISHED: if (s->hit) { st->hand_state = TLS_ST_CW_CHANGE; return WRITE_TRAN_CONTINUE; } else { st->hand_state = TLS_ST_OK; ossl_statem_set_in_init(s, 0); return WRITE_TRAN_CONTINUE; } default: /* Shouldn't happen */ return WRITE_TRAN_ERROR; } } Commit Message: Fix missing NULL checks in CKE processing Reviewed-by: Rich Salz <[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 StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p, StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq) { if (ssn == NULL) return -1; SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ? "toclient":"toserver"); /* RST */ if (p->tcph->th_flags & TH_RST) { if (!StreamTcpValidateRst(ssn, p)) return -1; if (PKT_IS_TOSERVER(p)) { if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) && SEQ_EQ(TCP_GET_WINDOW(p), 0) && SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1))) { StreamTcpPacketSetState(p, ssn, TCP_CLOSED); SCLogDebug("ssn %p: Reset received and state changed to " "TCP_CLOSED", ssn); } } else { StreamTcpPacketSetState(p, ssn, TCP_CLOSED); SCLogDebug("ssn %p: Reset received and state changed to " "TCP_CLOSED", ssn); } /* FIN */ } else if (p->tcph->th_flags & TH_FIN) { /** \todo */ /* SYN/ACK */ } else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) { if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn); /* Check if the SYN/ACK packet ack's the earlier * received SYN packet. */ if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) { StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK); SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32"" " != %" PRIu32 " from stream", ssn, TCP_GET_ACK(p), ssn->server.isn + 1); return -1; } /* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN * packet. */ if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) { StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN); SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32"" " != %" PRIu32 " from *first* SYN pkt", ssn, TCP_GET_SEQ(p), ssn->client.isn); return -1; } /* update state */ StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV); SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn); /* sequence number & window */ ssn->client.isn = TCP_GET_SEQ(p); STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn); ssn->client.next_seq = ssn->client.isn + 1; ssn->server.window = TCP_GET_WINDOW(p); SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn, ssn->client.window); /* Set the timestamp values used to validate the timestamp of * received packets. */ if ((TCP_HAS_TS(p)) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP)) { ssn->client.last_ts = TCP_GET_TSVAL(p); SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" " "ssn->server.last_ts %" PRIu32"", ssn, ssn->client.last_ts, ssn->server.last_ts); ssn->flags |= STREAMTCP_FLAG_TIMESTAMP; ssn->client.last_pkt_ts = p->ts.tv_sec; if (ssn->client.last_ts == 0) ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP; } else { ssn->server.last_ts = 0; ssn->client.last_ts = 0; ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP; } ssn->server.last_ack = TCP_GET_ACK(p); ssn->client.last_ack = ssn->client.isn + 1; /** check for the presense of the ws ptr to determine if we * support wscale at all */ if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) && (TCP_HAS_WSCALE(p))) { ssn->server.wscale = TCP_GET_WSCALE(p); } else { ssn->server.wscale = 0; } if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) && TCP_GET_SACKOK(p) == 1) { ssn->flags |= STREAMTCP_FLAG_SACKOK; SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn); } ssn->client.next_win = ssn->client.last_ack + ssn->client.window; ssn->server.next_win = ssn->server.last_ack + ssn->server.window; SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn, ssn->client.next_win); SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn, ssn->server.next_win); SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", " "ssn->client.next_seq %" PRIu32 ", " "ssn->client.last_ack %" PRIu32 " " "(ssn->server.last_ack %" PRIu32 ")", ssn, ssn->client.isn, ssn->client.next_seq, ssn->client.last_ack, ssn->server.last_ack); /* done here */ return 0; } if (PKT_IS_TOSERVER(p)) { StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION); SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn); return -1; } /* Check if the SYN/ACK packet ack's the earlier * received SYN packet. */ if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) { StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK); SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != " "%" PRIu32 " from stream", ssn, TCP_GET_ACK(p), ssn->client.isn + 1); return -1; } StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL); } else if (p->tcph->th_flags & TH_SYN) { SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn); if (ssn->flags & STREAMTCP_FLAG_4WHS) { SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of " "4WHS SYN", ssn); } if (PKT_IS_TOCLIENT(p)) { /** a SYN only packet in the opposite direction could be: * http://www.breakingpointsystems.com/community/blog/tcp- * portals-the-three-way-handshake-is-a-lie * * \todo improve resetting the session */ /* indicate that we're dealing with 4WHS here */ ssn->flags |= STREAMTCP_FLAG_4WHS; SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn); /* set the sequence numbers and window for server * We leave the ssn->client.isn in place as we will * check the SYN/ACK pkt with that. */ ssn->server.isn = TCP_GET_SEQ(p); STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn); ssn->server.next_seq = ssn->server.isn + 1; /* Set the stream timestamp value, if packet has timestamp * option enabled. */ if (TCP_HAS_TS(p)) { ssn->server.last_ts = TCP_GET_TSVAL(p); SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts); if (ssn->server.last_ts == 0) ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP; ssn->server.last_pkt_ts = p->ts.tv_sec; ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP; } ssn->server.window = TCP_GET_WINDOW(p); if (TCP_HAS_WSCALE(p)) { ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE; ssn->server.wscale = TCP_GET_WSCALE(p); } else { ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE; ssn->server.wscale = 0; } if (TCP_GET_SACKOK(p) == 1) { ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK; } else { ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK; } SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", " "ssn->server.next_seq %" PRIu32 ", " "ssn->server.last_ack %"PRIu32"", ssn, ssn->server.isn, ssn->server.next_seq, ssn->server.last_ack); SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", " "ssn->client.next_seq %" PRIu32 ", " "ssn->client.last_ack %"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq, ssn->client.last_ack); } /** \todo check if it's correct or set event */ } else if (p->tcph->th_flags & TH_ACK) { /* Handle the asynchronous stream, when we receive a SYN packet and now istead of receving a SYN/ACK we receive a ACK from the same host, which sent the SYN, this suggests the ASNYC streams.*/ if (stream_config.async_oneside == FALSE) return 0; /* we are in AYNC (one side) mode now. */ /* one side async means we won't see a SYN/ACK, so we can * only check the SYN. */ if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) { StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ); SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != " "%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p), ssn->client.next_seq); return -1; } ssn->flags |= STREAMTCP_FLAG_ASYNC; StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED); SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn); ssn->client.window = TCP_GET_WINDOW(p); ssn->client.last_ack = TCP_GET_SEQ(p); ssn->client.next_win = ssn->client.last_ack + ssn->client.window; /* Set the server side parameters */ ssn->server.isn = TCP_GET_ACK(p) - 1; STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn); ssn->server.next_seq = ssn->server.isn + 1; ssn->server.last_ack = ssn->server.next_seq; ssn->server.next_win = ssn->server.last_ack; SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ" " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " "ssn->client.next_seq %" PRIu32 "" ,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_seq); /* if SYN had wscale, assume it to be supported. Otherwise * we know it not to be supported. */ if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) { ssn->client.wscale = TCP_WSCALE_MAX; } /* Set the timestamp values used to validate the timestamp of * received packets.*/ if (TCP_HAS_TS(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP)) { ssn->flags |= STREAMTCP_FLAG_TIMESTAMP; ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP; ssn->client.last_pkt_ts = p->ts.tv_sec; } else { ssn->client.last_ts = 0; ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP; } if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) { ssn->flags |= STREAMTCP_FLAG_SACKOK; } StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq); } else { SCLogDebug("ssn %p: default case", ssn); } return 0; } Commit Message: stream: support RST getting lost/ignored In case of a valid RST on a SYN, the state is switched to 'TCP_CLOSED'. However, the target of the RST may not have received it, or may not have accepted it. Also, the RST may have been injected, so the supposed sender may not actually be aware of the RST that was sent in it's name. In this case the previous behavior was to switch the state to CLOSED and accept no further TCP updates or stream reassembly. This patch changes this. It still switches the state to CLOSED, as this is by far the most likely to be correct. However, it will reconsider the state if the receiver continues to talk. To do this on each state change the previous state will be recorded in TcpSession::pstate. If a non-RST packet is received after a RST, this TcpSession::pstate is used to try to continue the conversation. If the (supposed) sender of the RST is also continueing the conversation as normal, it's highly likely it didn't send the RST. In this case a stream event is generated. Ticket: #2501 Reported-By: Kirill Shipulin 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 NormalPageArena::coalesce() { if (m_promptlyFreedSize < 1024 * 1024) return false; if (getThreadState()->sweepForbidden()) return false; ASSERT(!hasCurrentAllocationArea()); TRACE_EVENT0("blink_gc", "BaseArena::coalesce"); m_freeList.clear(); size_t freedSize = 0; for (NormalPage* page = static_cast<NormalPage*>(m_firstPage); page; page = static_cast<NormalPage*>(page->next())) { Address startOfGap = page->payload(); for (Address headerAddress = startOfGap; headerAddress < page->payloadEnd();) { HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(headerAddress); size_t size = header->size(); ASSERT(size > 0); ASSERT(size < blinkPagePayloadSize()); if (header->isPromptlyFreed()) { ASSERT(size >= sizeof(HeapObjectHeader)); SET_MEMORY_INACCESSIBLE(headerAddress, sizeof(HeapObjectHeader)); CHECK_MEMORY_INACCESSIBLE(headerAddress, size); freedSize += size; headerAddress += size; continue; } if (header->isFree()) { SET_MEMORY_INACCESSIBLE(headerAddress, size < sizeof(FreeListEntry) ? size : sizeof(FreeListEntry)); CHECK_MEMORY_INACCESSIBLE(headerAddress, size); headerAddress += size; continue; } ASSERT(header->checkHeader()); if (startOfGap != headerAddress) addToFreeList(startOfGap, headerAddress - startOfGap); headerAddress += size; startOfGap = headerAddress; } if (startOfGap != page->payloadEnd()) addToFreeList(startOfGap, page->payloadEnd() - startOfGap); } getThreadState()->decreaseAllocatedObjectSize(freedSize); ASSERT(m_promptlyFreedSize == freedSize); m_promptlyFreedSize = 0; return true; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119 Target: 1 Example 2: Code: void AutomationProvider::InstallExtension(const FilePath& crx_path, IPC::Message* reply_message) { ExtensionService* service = profile_->GetExtensionService(); if (service) { new ExtensionInstallNotificationObserver(this, AutomationMsg_InstallExtension::ID, reply_message); scoped_refptr<CrxInstaller> installer( new CrxInstaller(service, NULL)); // silent install, no UI installer->InstallCrx(crx_path); } else { AutomationMsg_InstallExtension::WriteReplyParams( reply_message, AUTOMATION_MSG_EXTENSION_INSTALL_FAILED); Send(reply_message); } } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 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: Horizontal_Sweep_Drop( RAS_ARGS Short y, FT_F26Dot6 x1, FT_F26Dot6 x2, PProfile left, PProfile right ) { Long e1, e2, pxl; PByte bits; Byte f1; /* During the horizontal sweep, we only take care of drop-outs */ /* e1 + <-- pixel center */ /* | */ /* x1 ---+--> <-- contour */ /* | */ /* | */ /* x2 <--+--- <-- contour */ /* | */ /* | */ /* e2 + <-- pixel center */ e1 = CEILING( x1 ); e2 = FLOOR ( x2 ); pxl = e1; if ( e1 > e2 ) { Int dropOutControl = left->flags & 7; if ( e1 == e2 + ras.precision ) { switch ( dropOutControl ) { case 0: /* simple drop-outs including stubs */ pxl = e2; break; case 4: /* smart drop-outs including stubs */ pxl = FLOOR( ( x1 + x2 - 1 ) / 2 + ras.precision_half ); break; case 1: /* simple drop-outs excluding stubs */ case 5: /* smart drop-outs excluding stubs */ /* see Vertical_Sweep_Drop for details */ /* rightmost stub test */ if ( left->next == right && left->height <= 0 && !( left->flags & Overshoot_Top && x2 - x1 >= ras.precision_half ) ) return; /* leftmost stub test */ if ( right->next == left && left->start == y && !( left->flags & Overshoot_Bottom && x2 - x1 >= ras.precision_half ) ) return; if ( dropOutControl == 1 ) pxl = e2; else pxl = FLOOR( ( x1 + x2 - 1 ) / 2 + ras.precision_half ); break; default: /* modes 2, 3, 6, 7 */ return; /* no drop-out control */ } /* undocumented but confirmed: If the drop-out would result in a */ /* pixel outside of the bounding box, use the pixel inside of the */ /* bounding box instead */ if ( pxl < 0 ) pxl = e1; else if ( TRUNC( pxl ) >= ras.target.rows ) pxl = e2; /* check that the other pixel isn't set */ e1 = pxl == e1 ? e2 : e1; e1 = TRUNC( e1 ); bits = ras.bTarget + ( y >> 3 ); f1 = (Byte)( 0x80 >> ( y & 7 ) ); bits -= e1 * ras.target.pitch; if ( ras.target.pitch > 0 ) bits += ( ras.target.rows - 1 ) * ras.target.pitch; if ( e1 >= 0 && e1 < ras.target.rows && *bits & f1 ) return; } else return; } bits = ras.bTarget + ( y >> 3 ); f1 = (Byte)( 0x80 >> ( y & 7 ) ); e1 = TRUNC( pxl ); if ( e1 >= 0 && e1 < ras.target.rows ) { bits -= e1 * ras.target.pitch; if ( ras.target.pitch > 0 ) bits += ( ras.target.rows - 1 ) * ras.target.pitch; bits[0] |= f1; } } 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 GCInfoTable::Init() { CHECK(!g_gc_info_table); Resize(); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362 Target: 1 Example 2: Code: int ipc_addid(struct ipc_ids* ids, struct kern_ipc_perm* new, int size) { kuid_t euid; kgid_t egid; int id; int next_id = ids->next_id; if (size > IPCMNI) size = IPCMNI; if (ids->in_use >= size) return -ENOSPC; idr_preload(GFP_KERNEL); spin_lock_init(&new->lock); new->deleted = 0; rcu_read_lock(); spin_lock(&new->lock); id = idr_alloc(&ids->ipcs_idr, new, (next_id < 0) ? 0 : ipcid_to_idx(next_id), 0, GFP_NOWAIT); idr_preload_end(); if (id < 0) { spin_unlock(&new->lock); rcu_read_unlock(); return id; } ids->in_use++; current_euid_egid(&euid, &egid); new->cuid = new->uid = euid; new->gid = new->cgid = egid; if (next_id < 0) { new->seq = ids->seq++; if (ids->seq > ids->seq_max) ids->seq = 0; } else { new->seq = ipcid_to_seqx(next_id); ids->next_id = -1; } new->id = ipc_buildid(id, new->seq); return id; } Commit Message: ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [[email protected]: do not call sem_lock when bogus sma] [[email protected]: make refcounter atomic] Signed-off-by: Rik van Riel <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Acked-by: Davidlohr Bueso <[email protected]> Cc: Chegu Vinod <[email protected]> Cc: Jason Low <[email protected]> Reviewed-by: Michel Lespinasse <[email protected]> Cc: Peter Hurley <[email protected]> Cc: Stanislav Kinsbursky <[email protected]> Tested-by: Emmanuel Benisty <[email protected]> Tested-by: Sedat Dilek <[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: store_pool_error(png_store *ps, png_const_structp pp, PNG_CONST char *msg) { if (pp != NULL) png_error(pp, msg); /* Else we have to do it ourselves. png_error eventually calls store_log, * above. store_log accepts a NULL png_structp - it just changes what gets * output by store_message. */ store_log(ps, pp, msg, 1 /* error */); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) 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: ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms) { unsigned int nbits; gpg_err_code_t rc; struct pk_encoding_ctx ctx; gcry_sexp_t l1 = NULL; gcry_mpi_t data_e = NULL; ECC_secret_key sk; gcry_mpi_t mpi_g = NULL; char *curvename = NULL; mpi_ec_t ec = NULL; mpi_point_struct kG; mpi_point_struct R; gcry_mpi_t r = NULL; int flags = 0; memset (&sk, 0, sizeof sk); point_init (&kG); point_init (&R); _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, (nbits = ecc_get_nbits (keyparms))); /* Look for flags. */ l1 = sexp_find_token (keyparms, "flags", 0); if (l1) { rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL); if (rc) goto leave; } sexp_release (l1); l1 = NULL; /* * Extract the data. */ rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx); if (rc) goto leave; rc = sexp_extract_param (l1, NULL, "e", &data_e, NULL); if (rc) goto leave; if (DBG_CIPHER) log_printmpi ("ecc_decrypt d_e", data_e); if (mpi_is_opaque (data_e)) { rc = GPG_ERR_INV_DATA; goto leave; } /* * Extract the key. */ rc = sexp_extract_param (keyparms, NULL, "-p?a?b?g?n?h?+d", &sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n, &sk.E.h, &sk.d, NULL); if (rc) goto leave; if (mpi_g) { point_init (&sk.E.G); rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g); if (rc) goto leave; } /* Add missing parameters using the optional curve parameter. */ sexp_release (l1); l1 = sexp_find_token (keyparms, "curve", 5); if (l1) { curvename = sexp_nth_string (l1, 1); if (curvename) { rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL); if (rc) goto leave; } } /* Guess required fields if a curve parameter has not been given. */ if (!curvename) { sk.E.model = MPI_EC_WEIERSTRASS; sk.E.dialect = ECC_DIALECT_STANDARD; if (!sk.E.h) sk.E.h = mpi_const (MPI_C_ONE); } if (DBG_CIPHER) { log_debug ("ecc_decrypt info: %s/%s\n", _gcry_ecc_model2str (sk.E.model), _gcry_ecc_dialect2str (sk.E.dialect)); if (sk.E.name) log_debug ("ecc_decrypt name: %s\n", sk.E.name); log_printmpi ("ecc_decrypt p", sk.E.p); log_printmpi ("ecc_decrypt a", sk.E.a); log_printmpi ("ecc_decrypt b", sk.E.b); log_printpnt ("ecc_decrypt g", &sk.E.G, NULL); log_printmpi ("ecc_decrypt n", sk.E.n); log_printmpi ("ecc_decrypt h", sk.E.h); if (!fips_mode ()) log_printmpi ("ecc_decrypt d", sk.d); } if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d) { rc = GPG_ERR_NO_OBJ; goto leave; } ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags, sk.E.p, sk.E.a, sk.E.b); /* * Compute the plaintext. */ if (ec->model == MPI_EC_MONTGOMERY) rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG); else rc = _gcry_ecc_os2ec (&kG, data_e); if (rc) goto leave; if (DBG_CIPHER) log_printpnt ("ecc_decrypt kG", &kG, NULL); if (!(flags & PUBKEY_FLAG_DJB_TWEAK) /* For X25519, by its definition, validation should not be done. */ && !_gcry_mpi_ec_curve_point (&kG, ec)) { rc = GPG_ERR_INV_DATA; goto leave; y = mpi_new (0); if (_gcry_mpi_ec_get_affine (x, y, &R, ec)) { rc = GPG_ERR_INV_DATA; goto leave; /* * Note for X25519. * * By the definition of X25519, this is the case where X25519 * returns 0, mapping infinity to zero. However, we * deliberately let it return an error. * * For X25519 ECDH, comming here means that it might be * decrypted by anyone with the shared secret of 0 (the result * of this function could be always 0 by other scalar values, * other than the private key of SK.D). * * So, it looks like an encrypted message but it can be * decrypted by anyone, or at least something wrong * happens. Recipient should not proceed as if it were * properly encrypted message. * * This handling is needed for our major usage of GnuPG, * where it does the One-Pass Diffie-Hellman method, * C(1, 1, ECC CDH), with an ephemeral key. */ } if (y) r = _gcry_ecc_ec2os (x, y, sk.E.p); else { unsigned char *rawmpi; unsigned int rawmpilen; rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1, &rawmpilen, NULL); if (!rawmpi) { rc = gpg_err_code_from_syserror (); goto leave; } else { rawmpi[0] = 0x40; rawmpilen++; r = mpi_new (0); mpi_set_opaque (r, rawmpi, rawmpilen*8); } } if (!r) rc = gpg_err_code_from_syserror (); else rc = 0; mpi_free (x); mpi_free (y); } if (DBG_CIPHER) log_printmpi ("ecc_decrypt res", r); if (!rc) rc = sexp_build (r_plain, NULL, "(value %m)", r); leave: point_free (&R); point_free (&kG); _gcry_mpi_release (r); _gcry_mpi_release (sk.E.p); _gcry_mpi_release (sk.E.a); _gcry_mpi_release (sk.E.b); _gcry_mpi_release (mpi_g); point_free (&sk.E.G); _gcry_mpi_release (sk.E.n); _gcry_mpi_release (sk.E.h); _gcry_mpi_release (sk.d); _gcry_mpi_release (data_e); xfree (curvename); sexp_release (l1); _gcry_mpi_ec_free (ec); _gcry_pk_util_free_encoding_ctx (&ctx); if (DBG_CIPHER) log_debug ("ecc_decrypt => %s\n", gpg_strerror (rc)); return rc; } Commit Message: CWE ID: CWE-200 Target: 1 Example 2: Code: int create_flush_cmd_control(struct f2fs_sb_info *sbi) { dev_t dev = sbi->sb->s_bdev->bd_dev; struct flush_cmd_control *fcc; int err = 0; if (SM_I(sbi)->fcc_info) { fcc = SM_I(sbi)->fcc_info; if (fcc->f2fs_issue_flush) return err; goto init_thread; } fcc = kzalloc(sizeof(struct flush_cmd_control), GFP_KERNEL); if (!fcc) return -ENOMEM; atomic_set(&fcc->issued_flush, 0); atomic_set(&fcc->issing_flush, 0); init_waitqueue_head(&fcc->flush_wait_queue); init_llist_head(&fcc->issue_list); SM_I(sbi)->fcc_info = fcc; if (!test_opt(sbi, FLUSH_MERGE)) return err; init_thread: fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi, "f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev)); if (IS_ERR(fcc->f2fs_issue_flush)) { err = PTR_ERR(fcc->f2fs_issue_flush); kfree(fcc); SM_I(sbi)->fcc_info = NULL; return err; } return err; } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <[email protected]> Signed-off-by: Chao Yu <[email protected]> Signed-off-by: Jaegeuk Kim <[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: void __fput_sync(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { struct task_struct *task = current; file_sb_list_del(file); BUG_ON(!(task->flags & PF_KTHREAD)); __fput(file); } } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-17 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: _pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw) { PyObject *logical = NULL; /* input unicode or string object */ FriBidiParType base = FRIBIDI_TYPE_RTL; /* optional direction */ const char *encoding = "utf-8"; /* optional input string encoding */ int clean = 0; /* optional flag to clean the string */ int reordernsm = 1; /* optional flag to allow reordering of non spacing marks*/ static char *kwargs[] = { "logical", "base_direction", "encoding", "clean", "reordernsm", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kw, "O|isii", kwargs, &logical, &base, &encoding, &clean, &reordernsm)) return NULL; /* Validate base */ if (!(base == FRIBIDI_TYPE_RTL || base == FRIBIDI_TYPE_LTR || base == FRIBIDI_TYPE_ON)) return PyErr_Format (PyExc_ValueError, "invalid value %d: use either RTL, LTR or ON", base); /* Check object type and delegate to one of the log2vis functions */ if (PyUnicode_Check (logical)) return log2vis_unicode (logical, base, clean, reordernsm); else if (PyString_Check (logical)) return log2vis_encoded_string (logical, encoding, base, clean, reordernsm); else return PyErr_Format (PyExc_TypeError, "expected unicode or str, not %s", logical->ob_type->tp_name); } Commit Message: refactor pyfribidi.c module pyfribidi.c is now compiled as _pyfribidi. This module only handles unicode internally and doesn't use the fribidi_utf8_to_unicode function (which can't handle 4 byte utf-8 sequences). This fixes the buffer overflow in issue #2. The code is now also much simpler: pyfribidi.c is down from 280 to 130 lines of code. We now ship a pure python pyfribidi that handles the case when non-unicode strings are passed in. We now also adapt the size of the output string if clean=True is passed. CWE ID: CWE-119 Target: 1 Example 2: Code: static int handle_revision_opt(struct rev_info *revs, int argc, const char **argv, int *unkc, const char **unkv) { const char *arg = argv[0]; const char *optarg; int argcount; /* pseudo revision arguments */ if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") || !strcmp(arg, "--tags") || !strcmp(arg, "--remotes") || !strcmp(arg, "--reflog") || !strcmp(arg, "--not") || !strcmp(arg, "--no-walk") || !strcmp(arg, "--do-walk") || !strcmp(arg, "--bisect") || starts_with(arg, "--glob=") || !strcmp(arg, "--indexed-objects") || starts_with(arg, "--exclude=") || starts_with(arg, "--branches=") || starts_with(arg, "--tags=") || starts_with(arg, "--remotes=") || starts_with(arg, "--no-walk=")) { unkv[(*unkc)++] = arg; return 1; } if ((argcount = parse_long_opt("max-count", argv, &optarg))) { revs->max_count = atoi(optarg); revs->no_walk = 0; return argcount; } else if ((argcount = parse_long_opt("skip", argv, &optarg))) { revs->skip_count = atoi(optarg); return argcount; } else if ((*arg == '-') && isdigit(arg[1])) { /* accept -<digit>, like traditional "head" */ if (strtol_i(arg + 1, 10, &revs->max_count) < 0 || revs->max_count < 0) die("'%s': not a non-negative integer", arg + 1); revs->no_walk = 0; } else if (!strcmp(arg, "-n")) { if (argc <= 1) return error("-n requires an argument"); revs->max_count = atoi(argv[1]); revs->no_walk = 0; return 2; } else if (starts_with(arg, "-n")) { revs->max_count = atoi(arg + 2); revs->no_walk = 0; } else if ((argcount = parse_long_opt("max-age", argv, &optarg))) { revs->max_age = atoi(optarg); return argcount; } else if ((argcount = parse_long_opt("since", argv, &optarg))) { revs->max_age = approxidate(optarg); return argcount; } else if ((argcount = parse_long_opt("after", argv, &optarg))) { revs->max_age = approxidate(optarg); return argcount; } else if ((argcount = parse_long_opt("min-age", argv, &optarg))) { revs->min_age = atoi(optarg); return argcount; } else if ((argcount = parse_long_opt("before", argv, &optarg))) { revs->min_age = approxidate(optarg); return argcount; } else if ((argcount = parse_long_opt("until", argv, &optarg))) { revs->min_age = approxidate(optarg); return argcount; } else if (!strcmp(arg, "--first-parent")) { revs->first_parent_only = 1; } else if (!strcmp(arg, "--ancestry-path")) { revs->ancestry_path = 1; revs->simplify_history = 0; revs->limited = 1; } else if (!strcmp(arg, "-g") || !strcmp(arg, "--walk-reflogs")) { init_reflog_walk(&revs->reflog_info); } else if (!strcmp(arg, "--default")) { if (argc <= 1) return error("bad --default argument"); revs->def = argv[1]; return 2; } else if (!strcmp(arg, "--merge")) { revs->show_merge = 1; } else if (!strcmp(arg, "--topo-order")) { revs->sort_order = REV_SORT_IN_GRAPH_ORDER; revs->topo_order = 1; } else if (!strcmp(arg, "--simplify-merges")) { revs->simplify_merges = 1; revs->topo_order = 1; revs->rewrite_parents = 1; revs->simplify_history = 0; revs->limited = 1; } else if (!strcmp(arg, "--simplify-by-decoration")) { revs->simplify_merges = 1; revs->topo_order = 1; revs->rewrite_parents = 1; revs->simplify_history = 0; revs->simplify_by_decoration = 1; revs->limited = 1; revs->prune = 1; load_ref_decorations(DECORATE_SHORT_REFS); } else if (!strcmp(arg, "--date-order")) { revs->sort_order = REV_SORT_BY_COMMIT_DATE; revs->topo_order = 1; } else if (!strcmp(arg, "--author-date-order")) { revs->sort_order = REV_SORT_BY_AUTHOR_DATE; revs->topo_order = 1; } else if (starts_with(arg, "--early-output")) { int count = 100; switch (arg[14]) { case '=': count = atoi(arg+15); /* Fallthrough */ case 0: revs->topo_order = 1; revs->early_output = count; } } else if (!strcmp(arg, "--parents")) { revs->rewrite_parents = 1; revs->print_parents = 1; } else if (!strcmp(arg, "--dense")) { revs->dense = 1; } else if (!strcmp(arg, "--sparse")) { revs->dense = 0; } else if (!strcmp(arg, "--show-all")) { revs->show_all = 1; } else if (!strcmp(arg, "--remove-empty")) { revs->remove_empty_trees = 1; } else if (!strcmp(arg, "--merges")) { revs->min_parents = 2; } else if (!strcmp(arg, "--no-merges")) { revs->max_parents = 1; } else if (starts_with(arg, "--min-parents=")) { revs->min_parents = atoi(arg+14); } else if (starts_with(arg, "--no-min-parents")) { revs->min_parents = 0; } else if (starts_with(arg, "--max-parents=")) { revs->max_parents = atoi(arg+14); } else if (starts_with(arg, "--no-max-parents")) { revs->max_parents = -1; } else if (!strcmp(arg, "--boundary")) { revs->boundary = 1; } else if (!strcmp(arg, "--left-right")) { revs->left_right = 1; } else if (!strcmp(arg, "--left-only")) { if (revs->right_only) die("--left-only is incompatible with --right-only" " or --cherry"); revs->left_only = 1; } else if (!strcmp(arg, "--right-only")) { if (revs->left_only) die("--right-only is incompatible with --left-only"); revs->right_only = 1; } else if (!strcmp(arg, "--cherry")) { if (revs->left_only) die("--cherry is incompatible with --left-only"); revs->cherry_mark = 1; revs->right_only = 1; revs->max_parents = 1; revs->limited = 1; } else if (!strcmp(arg, "--count")) { revs->count = 1; } else if (!strcmp(arg, "--cherry-mark")) { if (revs->cherry_pick) die("--cherry-mark is incompatible with --cherry-pick"); revs->cherry_mark = 1; revs->limited = 1; /* needs limit_list() */ } else if (!strcmp(arg, "--cherry-pick")) { if (revs->cherry_mark) die("--cherry-pick is incompatible with --cherry-mark"); revs->cherry_pick = 1; revs->limited = 1; } else if (!strcmp(arg, "--objects")) { revs->tag_objects = 1; revs->tree_objects = 1; revs->blob_objects = 1; } else if (!strcmp(arg, "--objects-edge")) { revs->tag_objects = 1; revs->tree_objects = 1; revs->blob_objects = 1; revs->edge_hint = 1; } else if (!strcmp(arg, "--objects-edge-aggressive")) { revs->tag_objects = 1; revs->tree_objects = 1; revs->blob_objects = 1; revs->edge_hint = 1; revs->edge_hint_aggressive = 1; } else if (!strcmp(arg, "--verify-objects")) { revs->tag_objects = 1; revs->tree_objects = 1; revs->blob_objects = 1; revs->verify_objects = 1; } else if (!strcmp(arg, "--unpacked")) { revs->unpacked = 1; } else if (starts_with(arg, "--unpacked=")) { die("--unpacked=<packfile> no longer supported."); } else if (!strcmp(arg, "-r")) { revs->diff = 1; DIFF_OPT_SET(&revs->diffopt, RECURSIVE); } else if (!strcmp(arg, "-t")) { revs->diff = 1; DIFF_OPT_SET(&revs->diffopt, RECURSIVE); DIFF_OPT_SET(&revs->diffopt, TREE_IN_RECURSIVE); } else if (!strcmp(arg, "-m")) { revs->ignore_merges = 0; } else if (!strcmp(arg, "-c")) { revs->diff = 1; revs->dense_combined_merges = 0; revs->combine_merges = 1; } else if (!strcmp(arg, "--cc")) { revs->diff = 1; revs->dense_combined_merges = 1; revs->combine_merges = 1; } else if (!strcmp(arg, "-v")) { revs->verbose_header = 1; } else if (!strcmp(arg, "--pretty")) { revs->verbose_header = 1; revs->pretty_given = 1; get_commit_format(NULL, revs); } else if (starts_with(arg, "--pretty=") || starts_with(arg, "--format=")) { /* * Detached form ("--pretty X" as opposed to "--pretty=X") * not allowed, since the argument is optional. */ revs->verbose_header = 1; revs->pretty_given = 1; get_commit_format(arg+9, revs); } else if (!strcmp(arg, "--show-notes") || !strcmp(arg, "--notes")) { revs->show_notes = 1; revs->show_notes_given = 1; revs->notes_opt.use_default_notes = 1; } else if (!strcmp(arg, "--show-signature")) { revs->show_signature = 1; } else if (!strcmp(arg, "--show-linear-break") || starts_with(arg, "--show-linear-break=")) { if (starts_with(arg, "--show-linear-break=")) revs->break_bar = xstrdup(arg + 20); else revs->break_bar = " .........."; revs->track_linear = 1; revs->track_first_time = 1; } else if (starts_with(arg, "--show-notes=") || starts_with(arg, "--notes=")) { struct strbuf buf = STRBUF_INIT; revs->show_notes = 1; revs->show_notes_given = 1; if (starts_with(arg, "--show-notes")) { if (revs->notes_opt.use_default_notes < 0) revs->notes_opt.use_default_notes = 1; strbuf_addstr(&buf, arg+13); } else strbuf_addstr(&buf, arg+8); expand_notes_ref(&buf); string_list_append(&revs->notes_opt.extra_notes_refs, strbuf_detach(&buf, NULL)); } else if (!strcmp(arg, "--no-notes")) { revs->show_notes = 0; revs->show_notes_given = 1; revs->notes_opt.use_default_notes = -1; /* we have been strdup'ing ourselves, so trick * string_list into free()ing strings */ revs->notes_opt.extra_notes_refs.strdup_strings = 1; string_list_clear(&revs->notes_opt.extra_notes_refs, 0); revs->notes_opt.extra_notes_refs.strdup_strings = 0; } else if (!strcmp(arg, "--standard-notes")) { revs->show_notes_given = 1; revs->notes_opt.use_default_notes = 1; } else if (!strcmp(arg, "--no-standard-notes")) { revs->notes_opt.use_default_notes = 0; } else if (!strcmp(arg, "--oneline")) { revs->verbose_header = 1; get_commit_format("oneline", revs); revs->pretty_given = 1; revs->abbrev_commit = 1; } else if (!strcmp(arg, "--graph")) { revs->topo_order = 1; revs->rewrite_parents = 1; revs->graph = graph_init(revs); } else if (!strcmp(arg, "--root")) { revs->show_root_diff = 1; } else if (!strcmp(arg, "--no-commit-id")) { revs->no_commit_id = 1; } else if (!strcmp(arg, "--always")) { revs->always_show_header = 1; } else if (!strcmp(arg, "--no-abbrev")) { revs->abbrev = 0; } else if (!strcmp(arg, "--abbrev")) { revs->abbrev = DEFAULT_ABBREV; } else if (starts_with(arg, "--abbrev=")) { revs->abbrev = strtoul(arg + 9, NULL, 10); if (revs->abbrev < MINIMUM_ABBREV) revs->abbrev = MINIMUM_ABBREV; else if (revs->abbrev > 40) revs->abbrev = 40; } else if (!strcmp(arg, "--abbrev-commit")) { revs->abbrev_commit = 1; revs->abbrev_commit_given = 1; } else if (!strcmp(arg, "--no-abbrev-commit")) { revs->abbrev_commit = 0; } else if (!strcmp(arg, "--full-diff")) { revs->diff = 1; revs->full_diff = 1; } else if (!strcmp(arg, "--full-history")) { revs->simplify_history = 0; } else if (!strcmp(arg, "--relative-date")) { revs->date_mode.type = DATE_RELATIVE; revs->date_mode_explicit = 1; } else if ((argcount = parse_long_opt("date", argv, &optarg))) { parse_date_format(optarg, &revs->date_mode); revs->date_mode_explicit = 1; return argcount; } else if (!strcmp(arg, "--log-size")) { revs->show_log_size = 1; } /* * Grepping the commit log */ else if ((argcount = parse_long_opt("author", argv, &optarg))) { add_header_grep(revs, GREP_HEADER_AUTHOR, optarg); return argcount; } else if ((argcount = parse_long_opt("committer", argv, &optarg))) { add_header_grep(revs, GREP_HEADER_COMMITTER, optarg); return argcount; } else if ((argcount = parse_long_opt("grep-reflog", argv, &optarg))) { add_header_grep(revs, GREP_HEADER_REFLOG, optarg); return argcount; } else if ((argcount = parse_long_opt("grep", argv, &optarg))) { add_message_grep(revs, optarg); return argcount; } else if (!strcmp(arg, "--grep-debug")) { revs->grep_filter.debug = 1; } else if (!strcmp(arg, "--basic-regexp")) { grep_set_pattern_type_option(GREP_PATTERN_TYPE_BRE, &revs->grep_filter); } else if (!strcmp(arg, "--extended-regexp") || !strcmp(arg, "-E")) { grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, &revs->grep_filter); } else if (!strcmp(arg, "--regexp-ignore-case") || !strcmp(arg, "-i")) { revs->grep_filter.regflags |= REG_ICASE; DIFF_OPT_SET(&revs->diffopt, PICKAXE_IGNORE_CASE); } else if (!strcmp(arg, "--fixed-strings") || !strcmp(arg, "-F")) { grep_set_pattern_type_option(GREP_PATTERN_TYPE_FIXED, &revs->grep_filter); } else if (!strcmp(arg, "--perl-regexp")) { grep_set_pattern_type_option(GREP_PATTERN_TYPE_PCRE, &revs->grep_filter); } else if (!strcmp(arg, "--all-match")) { revs->grep_filter.all_match = 1; } else if (!strcmp(arg, "--invert-grep")) { revs->invert_grep = 1; } else if ((argcount = parse_long_opt("encoding", argv, &optarg))) { if (strcmp(optarg, "none")) git_log_output_encoding = xstrdup(optarg); else git_log_output_encoding = ""; return argcount; } else if (!strcmp(arg, "--reverse")) { revs->reverse ^= 1; } else if (!strcmp(arg, "--children")) { revs->children.name = "children"; revs->limited = 1; } else if (!strcmp(arg, "--ignore-missing")) { revs->ignore_missing = 1; } else { int opts = diff_opt_parse(&revs->diffopt, argv, argc, revs->prefix); if (!opts) unkv[(*unkc)++] = arg; return opts; } if (revs->graph && revs->track_linear) die("--show-linear-break and --graph are incompatible"); return 1; } 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 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 __netif_receive_skb(struct sk_buff *skb) { int ret; if (sk_memalloc_socks() && skb_pfmemalloc(skb)) { unsigned long pflags = current->flags; /* * PFMEMALLOC skbs are special, they should * - be delivered to SOCK_MEMALLOC sockets only * - stay away from userspace * - have bounded memory usage * * Use PF_MEMALLOC as this saves us from propagating the allocation * context down to all allocation sites. */ current->flags |= PF_MEMALLOC; ret = __netif_receive_skb_core(skb, true); tsk_restore_flags(current, pflags, PF_MEMALLOC); } else ret = __netif_receive_skb_core(skb, false); return ret; } Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation. When drivers express support for TSO of encapsulated packets, they only mean that they can do it for one layer of encapsulation. Supporting additional levels would mean updating, at a minimum, more IP length fields and they are unaware of this. No encapsulation device expresses support for handling offloaded encapsulated packets, so we won't generate these types of frames in the transmit path. However, GRO doesn't have a check for multiple levels of encapsulation and will attempt to build them. UDP tunnel GRO actually does prevent this situation but it only handles multiple UDP tunnels stacked on top of each other. This generalizes that solution to prevent any kind of tunnel stacking that would cause problems. Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack") Signed-off-by: Jesse Gross <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-400 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadICONImage(const ImageInfo *image_info, ExceptionInfo *exception) { IconFile icon_file; IconInfo icon_info; Image *image; MagickBooleanType status; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; size_t bit, byte, bytes_per_line, one, scanline_pad; ssize_t count, offset, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(CoderEvent,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); } icon_file.reserved=(short) ReadBlobLSBShort(image); icon_file.resource_type=(short) ReadBlobLSBShort(image); icon_file.count=(short) ReadBlobLSBShort(image); if ((icon_file.reserved != 0) || ((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) || (icon_file.count > MaxIcons)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (i=0; i < icon_file.count; i++) { icon_file.directory[i].width=(unsigned char) ReadBlobByte(image); icon_file.directory[i].height=(unsigned char) ReadBlobByte(image); icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image); icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image); icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].bits_per_pixel=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].size=ReadBlobLSBLong(image); icon_file.directory[i].offset=ReadBlobLSBLong(image); } one=1; for (i=0; i < icon_file.count; i++) { /* Verify Icon identifier. */ offset=(ssize_t) SeekBlob(image,(MagickOffsetType) icon_file.directory[i].offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.size=ReadBlobLSBLong(image); icon_info.width=(unsigned char) ((int) ReadBlobLSBLong(image)); icon_info.height=(unsigned char) ((int) ReadBlobLSBLong(image)/2); icon_info.planes=ReadBlobLSBShort(image); icon_info.bits_per_pixel=ReadBlobLSBShort(image); if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) || (icon_info.size == 0x474e5089)) { Image *icon_image; ImageInfo *read_info; size_t length; unsigned char *png; /* Icon image encoded as a compressed PNG image. */ length=icon_file.directory[i].size; png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png)); if (png == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickMemory(png,"\211PNG\r\n\032\n\000\000\000\015",12); png[12]=(unsigned char) icon_info.planes; png[13]=(unsigned char) (icon_info.planes >> 8); png[14]=(unsigned char) icon_info.bits_per_pixel; png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8); count=ReadBlob(image,length-16,png+16); icon_image=(Image *) NULL; if (count > 0) { read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->magick,"PNG",MaxTextExtent); icon_image=BlobToImage(read_info,png,length+16,exception); read_info=DestroyImageInfo(read_info); } png=(unsigned char *) RelinquishMagickMemory(png); if (icon_image == (Image *) NULL) { if (count != (ssize_t) (length-16)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); image=DestroyImageList(image); return((Image *) NULL); } DestroyBlob(icon_image); icon_image->blob=ReferenceBlob(image->blob); ReplaceImageInList(&image,icon_image); icon_image->scene=i; } else { if (icon_info.bits_per_pixel > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.compression=ReadBlobLSBLong(image); icon_info.image_size=ReadBlobLSBLong(image); icon_info.x_pixels=ReadBlobLSBLong(image); icon_info.y_pixels=ReadBlobLSBLong(image); icon_info.number_colors=ReadBlobLSBLong(image); icon_info.colors_important=ReadBlobLSBLong(image); image->matte=MagickTrue; image->columns=(size_t) icon_file.directory[i].width; if ((ssize_t) image->columns > icon_info.width) image->columns=(size_t) icon_info.width; if (image->columns == 0) image->columns=256; image->rows=(size_t) icon_file.directory[i].height; if ((ssize_t) image->rows > icon_info.height) image->rows=(size_t) icon_info.height; if (image->rows == 0) image->rows=256; image->depth=icon_info.bits_per_pixel; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene = %.20g",(double) i); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " size = %.20g",(double) icon_info.size); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width = %.20g",(double) icon_file.directory[i].width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height = %.20g",(double) icon_file.directory[i].height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " colors = %.20g",(double ) icon_info.number_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " planes = %.20g",(double) icon_info.planes); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bpp = %.20g",(double) icon_info.bits_per_pixel); } if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U)) { image->storage_class=PseudoClass; image->colors=icon_info.number_colors; if (image->colors == 0) image->colors=one << icon_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { register ssize_t i; unsigned char *icon_colormap; /* Read Icon raster colormap. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4UL*sizeof(*icon_colormap)); if (icon_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap); if (count != (ssize_t) (4*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=icon_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++); p++; } icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap); } /* Convert Icon raster image to pixel packets. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & ~31) >> 3; (void) bytes_per_line; scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)- (image->columns*icon_info.bits_per_pixel)) >> 3; switch (icon_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) (image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00)); } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00)); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 4: { /* Read 4-bit Icon scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); SetPixelIndex(indexes+x+1,((byte) & 0xf)); } if ((image->columns % 2) != 0) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(indexes+x,byte); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); byte|=(size_t) (ReadBlobByte(image) << 8); SetPixelIndex(indexes+x,byte); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); SetPixelRed(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); if (icon_info.bits_per_pixel == 32) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) ReadBlobByte(image))); q++; } if (icon_info.bits_per_pixel == 24) for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (image_info->ping == MagickFalse) (void) SyncImage(image); if (icon_info.bits_per_pixel != 32) { /* Read the ICON alpha mask. */ image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? TransparentOpacity : OpaqueOpacity)); } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? TransparentOpacity : OpaqueOpacity)); } if ((image->columns % 32) != 0) for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (i < (ssize_t) (icon_file.count-1)) { /* 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; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static int ext4_quota_enable(struct super_block *sb, int type, int format_id, unsigned int flags) { int err; struct inode *qf_inode; unsigned long qf_inums[EXT4_MAXQUOTAS] = { le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum), le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum), le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum) }; BUG_ON(!ext4_has_feature_quota(sb)); if (!qf_inums[type]) return -EPERM; qf_inode = ext4_iget(sb, qf_inums[type]); if (IS_ERR(qf_inode)) { ext4_error(sb, "Bad quota inode # %lu", qf_inums[type]); return PTR_ERR(qf_inode); } /* Don't account quota for quota files to avoid recursion */ qf_inode->i_flags |= S_NOQUOTA; lockdep_set_quota_inode(qf_inode, I_DATA_SEM_QUOTA); err = dquot_enable(qf_inode, type, format_id, flags); iput(qf_inode); if (err) lockdep_set_quota_inode(qf_inode, I_DATA_SEM_NORMAL); return err; } Commit Message: ext4: validate s_first_meta_bg at mount time Ralf Spenneberg reported that he hit a kernel crash when mounting a modified ext4 image. And it turns out that kernel crashed when calculating fs overhead (ext4_calculate_overhead()), this is because the image has very large s_first_meta_bg (debug code shows it's 842150400), and ext4 overruns the memory in count_overhead() when setting bitmap buffer, which is PAGE_SIZE. ext4_calculate_overhead(): buf = get_zeroed_page(GFP_NOFS); <=== PAGE_SIZE buffer blks = count_overhead(sb, i, buf); count_overhead(): for (j = ext4_bg_num_gdb(sb, grp); j > 0; j--) { <=== j = 842150400 ext4_set_bit(EXT4_B2C(sbi, s++), buf); <=== buffer overrun count++; } This can be reproduced easily for me by this script: #!/bin/bash rm -f fs.img mkdir -p /mnt/ext4 fallocate -l 16M fs.img mke2fs -t ext4 -O bigalloc,meta_bg,^resize_inode -F fs.img debugfs -w -R "ssv first_meta_bg 842150400" fs.img mount -o loop fs.img /mnt/ext4 Fix it by validating s_first_meta_bg first at mount time, and refusing to mount if its value exceeds the largest possible meta_bg number. Reported-by: Ralf Spenneberg <[email protected]> Signed-off-by: Eryu Guan <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> Reviewed-by: Andreas Dilger <[email protected]> CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void fdctrl_handle_option(FDCtrl *fdctrl, int direction) { /* No result back */ fdctrl_reset_fifo(fdctrl); } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long 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 keyctl_set_reqkey_keyring() to not leak thread keyrings This fixes CVE-2017-7472. Running the following program as an unprivileged user exhausts kernel memory by leaking thread keyrings: #include <keyutils.h> int main() { for (;;) keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING); } Fix it by only creating a new thread keyring if there wasn't one before. To make things more consistent, make install_thread_keyring_to_cred() and install_process_keyring_to_cred() both return 0 if the corresponding keyring is already present. Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials") Cc: [email protected] # 2.6.29+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> CWE ID: CWE-404 Target: 1 Example 2: Code: static int http_close(git_smart_subtransport *subtransport) { http_subtransport *t = (http_subtransport *) subtransport; git_http_auth_context *context; size_t i; clear_parser_state(t); if (t->io) { git_stream_close(t->io); git_stream_free(t->io); t->io = NULL; } if (t->cred) { t->cred->free(t->cred); t->cred = NULL; } if (t->url_cred) { t->url_cred->free(t->url_cred); t->url_cred = NULL; } git_vector_foreach(&t->auth_contexts, i, context) { if (context->free) context->free(context); } git_vector_clear(&t->auth_contexts); gitno_connection_data_free_ptrs(&t->connection_data); memset(&t->connection_data, 0x0, sizeof(gitno_connection_data)); return 0; } Commit Message: http: check certificate validity before clobbering the error variable CWE ID: CWE-284 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: Pin jshGetPinFromVar( JsVar *pinv //!< The class instance representing a Pin. ) { if (jsvIsString(pinv) && pinv->varData.str[5]==0/*should never be more than 4 chars!*/) { return jshGetPinFromString(&pinv->varData.str[0]); } else if (jsvIsInt(pinv) /* This also tests for the Pin datatype */) { return (Pin)jsvGetInteger(pinv); } else return PIN_UNDEFINED; } Commit Message: Fix strncat/cpy bounding issues (fix #1425) 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: status_t BnOMX::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case LIVES_LOCALLY: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); pid_t pid = (pid_t)data.readInt32(); reply->writeInt32(livesLocally(node, pid)); return OK; } case LIST_NODES: { CHECK_OMX_INTERFACE(IOMX, data, reply); List<ComponentInfo> list; listNodes(&list); reply->writeInt32(list.size()); for (List<ComponentInfo>::iterator it = list.begin(); it != list.end(); ++it) { ComponentInfo &cur = *it; reply->writeString8(cur.mName); reply->writeInt32(cur.mRoles.size()); for (List<String8>::iterator role_it = cur.mRoles.begin(); role_it != cur.mRoles.end(); ++role_it) { reply->writeString8(*role_it); } } return NO_ERROR; } case ALLOCATE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); const char *name = data.readCString(); sp<IOMXObserver> observer = interface_cast<IOMXObserver>(data.readStrongBinder()); node_id node; status_t err = allocateNode(name, observer, &node); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)node); } return NO_ERROR; } case FREE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); reply->writeInt32(freeNode(node)); return NO_ERROR; } case SEND_COMMAND: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_COMMANDTYPE cmd = static_cast<OMX_COMMANDTYPE>(data.readInt32()); OMX_S32 param = data.readInt32(); reply->writeInt32(sendCommand(node, cmd, param)); return NO_ERROR; } case GET_PARAMETER: case SET_PARAMETER: case GET_CONFIG: case SET_CONFIG: case SET_INTERNAL_OPTION: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32()); size_t size = data.readInt64(); status_t err = NO_MEMORY; void *params = calloc(size, 1); if (params) { err = data.read(params, size); if (err != OK) { android_errorWriteLog(0x534e4554, "26914474"); } else { switch (code) { case GET_PARAMETER: err = getParameter(node, index, params, size); break; case SET_PARAMETER: err = setParameter(node, index, params, size); break; case GET_CONFIG: err = getConfig(node, index, params, size); break; case SET_CONFIG: err = setConfig(node, index, params, size); break; case SET_INTERNAL_OPTION: { InternalOptionType type = (InternalOptionType)data.readInt32(); err = setInternalOption(node, index, type, params, size); break; } default: TRESPASS(); } } } reply->writeInt32(err); if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { reply->write(params, size); } free(params); params = NULL; return NO_ERROR; } case GET_STATE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_STATETYPE state = OMX_StateInvalid; status_t err = getState(node, &state); reply->writeInt32(state); reply->writeInt32(err); return NO_ERROR; } case ENABLE_GRAPHIC_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = enableGraphicBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case GET_GRAPHIC_BUFFER_USAGE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_U32 usage = 0; status_t err = getGraphicBufferUsage(node, port_index, &usage); reply->writeInt32(err); reply->writeInt32(usage); return NO_ERROR; } case USE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = useBuffer(node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case USE_GRAPHIC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer; status_t err = useGraphicBuffer( node, port_index, graphicBuffer, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case UPDATE_GRAPHIC_BUFFER_IN_META: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer = (buffer_id)data.readInt32(); status_t err = updateGraphicBufferInMeta( node, port_index, graphicBuffer, buffer); reply->writeInt32(err); return NO_ERROR; } case CREATE_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IGraphicBufferProducer> bufferProducer; MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = createInputSurface(node, port_index, &bufferProducer, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, "26324358"); } reply->writeInt32(type); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); } return NO_ERROR; } case CREATE_PERSISTENT_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); sp<IGraphicBufferProducer> bufferProducer; sp<IGraphicBufferConsumer> bufferConsumer; status_t err = createPersistentInputSurface( &bufferProducer, &bufferConsumer); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); reply->writeStrongBinder(IInterface::asBinder(bufferConsumer)); } return NO_ERROR; } case SET_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IGraphicBufferConsumer> bufferConsumer = interface_cast<IGraphicBufferConsumer>(data.readStrongBinder()); MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = setInputSurface(node, port_index, bufferConsumer, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, "26324358"); } reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case SIGNAL_END_OF_INPUT_STREAM: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); status_t err = signalEndOfInputStream(node); reply->writeInt32(err); return NO_ERROR; } case STORE_META_DATA_IN_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = storeMetaDataInBuffers(node, port_index, enable, &type); reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case PREPARE_FOR_ADAPTIVE_PLAYBACK: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); OMX_U32 max_width = data.readInt32(); OMX_U32 max_height = data.readInt32(); status_t err = prepareForAdaptivePlayback( node, port_index, enable, max_width, max_height); reply->writeInt32(err); return NO_ERROR; } case CONFIGURE_VIDEO_TUNNEL_MODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); OMX_U32 audio_hw_sync = data.readInt32(); native_handle_t *sideband_handle = NULL; status_t err = configureVideoTunnelMode( node, port_index, tunneled, audio_hw_sync, &sideband_handle); reply->writeInt32(err); if(err == OK){ reply->writeNativeHandle(sideband_handle); } return NO_ERROR; } case ALLOC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) { ALOGE("b/24310423"); reply->writeInt32(INVALID_OPERATION); return NO_ERROR; } size_t size = data.readInt64(); buffer_id buffer; void *buffer_data; status_t err = allocateBuffer( node, port_index, size, &buffer, &buffer_data); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); reply->writeInt64((uintptr_t)buffer_data); } return NO_ERROR; } case ALLOC_BUFFER_WITH_BACKUP: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = allocateBufferWithBackup( node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case FREE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); reply->writeInt32(freeBuffer(node, port_index, buffer)); return NO_ERROR; } case FILL_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(fillBuffer(node, buffer, fenceFd)); return NO_ERROR; } case EMPTY_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); OMX_U32 range_offset = data.readInt32(); OMX_U32 range_length = data.readInt32(); OMX_U32 flags = data.readInt32(); OMX_TICKS timestamp = data.readInt64(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(emptyBuffer( node, buffer, range_offset, range_length, flags, timestamp, fenceFd)); return NO_ERROR; } case GET_EXTENSION_INDEX: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); const char *parameter_name = data.readCString(); OMX_INDEXTYPE index; status_t err = getExtensionIndex(node, parameter_name, &index); reply->writeInt32(err); if (err == OK) { reply->writeInt32(index); } return OK; } default: return BBinder::onTransact(code, data, reply, flags); } } 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: gfx::NativeView RenderWidgetHostViewGtk::BuildInputMethodsGtkMenu() { return im_context_->BuildInputMethodsGtkMenu(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) { struct passwd *pw = NULL, pw_s; const char *user = NULL; cfg_t cfg_st; cfg_t *cfg = &cfg_st; char buffer[BUFSIZE]; char *buf = NULL; char *authfile_dir; size_t authfile_dir_len; int pgu_ret, gpn_ret; int retval = PAM_IGNORE; device_t *devices = NULL; unsigned n_devices = 0; int openasuser; int should_free_origin = 0; int should_free_appid = 0; int should_free_auth_file = 0; int should_free_authpending_file = 0; parse_cfg(flags, argc, argv, cfg); if (!cfg->origin) { strcpy(buffer, DEFAULT_ORIGIN_PREFIX); if (gethostname(buffer + strlen(DEFAULT_ORIGIN_PREFIX), BUFSIZE - strlen(DEFAULT_ORIGIN_PREFIX)) == -1) { DBG("Unable to get host name"); goto done; } DBG("Origin not specified, using \"%s\"", buffer); cfg->origin = strdup(buffer); if (!cfg->origin) { DBG("Unable to allocate memory"); goto done; } else { should_free_origin = 1; } } if (!cfg->appid) { DBG("Appid not specified, using the same value of origin (%s)", cfg->origin); cfg->appid = strdup(cfg->origin); if (!cfg->appid) { DBG("Unable to allocate memory") goto done; } else { should_free_appid = 1; } } if (cfg->max_devs == 0) { DBG("Maximum devices number not set. Using default (%d)", MAX_DEVS); cfg->max_devs = MAX_DEVS; } devices = malloc(sizeof(device_t) * cfg->max_devs); if (!devices) { DBG("Unable to allocate memory"); retval = PAM_IGNORE; goto done; } pgu_ret = pam_get_user(pamh, &user, NULL); if (pgu_ret != PAM_SUCCESS || user == NULL) { DBG("Unable to access user %s", user); retval = PAM_CONV_ERR; goto done; } DBG("Requesting authentication for user %s", user); gpn_ret = getpwnam_r(user, &pw_s, buffer, sizeof(buffer), &pw); if (gpn_ret != 0 || pw == NULL || pw->pw_dir == NULL || pw->pw_dir[0] != '/') { DBG("Unable to retrieve credentials for user %s, (%s)", user, strerror(errno)); retval = PAM_USER_UNKNOWN; goto done; } DBG("Found user %s", user); DBG("Home directory for %s is %s", user, pw->pw_dir); if (!cfg->auth_file) { buf = NULL; authfile_dir = secure_getenv(DEFAULT_AUTHFILE_DIR_VAR); if (!authfile_dir) { DBG("Variable %s is not set. Using default value ($HOME/.config/)", DEFAULT_AUTHFILE_DIR_VAR); authfile_dir_len = strlen(pw->pw_dir) + strlen("/.config") + strlen(DEFAULT_AUTHFILE) + 1; buf = malloc(sizeof(char) * (authfile_dir_len)); if (!buf) { DBG("Unable to allocate memory"); retval = PAM_IGNORE; goto done; } snprintf(buf, authfile_dir_len, "%s/.config%s", pw->pw_dir, DEFAULT_AUTHFILE); } else { DBG("Variable %s set to %s", DEFAULT_AUTHFILE_DIR_VAR, authfile_dir); authfile_dir_len = strlen(authfile_dir) + strlen(DEFAULT_AUTHFILE) + 1; buf = malloc(sizeof(char) * (authfile_dir_len)); if (!buf) { DBG("Unable to allocate memory"); retval = PAM_IGNORE; goto done; } snprintf(buf, authfile_dir_len, "%s%s", authfile_dir, DEFAULT_AUTHFILE); } DBG("Using default authentication file %s", buf); cfg->auth_file = buf; /* cfg takes ownership */ should_free_auth_file = 1; buf = NULL; } else { DBG("Using authentication file %s", cfg->auth_file); } openasuser = geteuid() == 0 && cfg->openasuser; if (openasuser) { if (seteuid(pw_s.pw_uid)) { DBG("Unable to switch user to uid %i", pw_s.pw_uid); retval = PAM_IGNORE; goto done; } DBG("Switched to uid %i", pw_s.pw_uid); } retval = get_devices_from_authfile(cfg->auth_file, user, cfg->max_devs, cfg->debug, cfg->debug_file, devices, &n_devices); if (openasuser) { if (seteuid(0)) { DBG("Unable to switch back to uid 0"); retval = PAM_IGNORE; goto done; } DBG("Switched back to uid 0"); } if (retval != 1) { n_devices = 0; } if (n_devices == 0) { if (cfg->nouserok) { DBG("Found no devices but nouserok specified. Skipping authentication"); retval = PAM_SUCCESS; goto done; } else if (retval != 1) { DBG("Unable to get devices from file %s", cfg->auth_file); retval = PAM_AUTHINFO_UNAVAIL; goto done; } else { DBG("Found no devices. Aborting."); retval = PAM_AUTHINFO_UNAVAIL; goto done; } } if (!cfg->authpending_file) { int actual_size = snprintf(buffer, BUFSIZE, DEFAULT_AUTHPENDING_FILE_PATH, getuid()); if (actual_size >= 0 && actual_size < BUFSIZE) { cfg->authpending_file = strdup(buffer); } if (!cfg->authpending_file) { DBG("Unable to allocate memory for the authpending_file, touch request notifications will not be emitted"); } else { should_free_authpending_file = 1; } } else { if (strlen(cfg->authpending_file) == 0) { DBG("authpending_file is set to an empty value, touch request notifications will be disabled"); cfg->authpending_file = NULL; } } int authpending_file_descriptor = -1; if (cfg->authpending_file) { DBG("Using file '%s' for emitting touch request notifications", cfg->authpending_file); authpending_file_descriptor = open(cfg->authpending_file, O_RDONLY | O_CREAT, 0664); if (authpending_file_descriptor < 0) { DBG("Unable to emit 'authentication started' notification by opening the file '%s', (%s)", cfg->authpending_file, strerror(errno)); } } if (cfg->manual == 0) { if (cfg->interactive) { converse(pamh, PAM_PROMPT_ECHO_ON, cfg->prompt != NULL ? cfg->prompt : DEFAULT_PROMPT); } retval = do_authentication(cfg, devices, n_devices, pamh); } else { retval = do_manual_authentication(cfg, devices, n_devices, pamh); } if (authpending_file_descriptor >= 0) { if (close(authpending_file_descriptor) < 0) { DBG("Unable to emit 'authentication stopped' notification by closing the file '%s', (%s)", cfg->authpending_file, strerror(errno)); } } if (retval != 1) { DBG("do_authentication returned %d", retval); retval = PAM_AUTH_ERR; goto done; } retval = PAM_SUCCESS; done: free_devices(devices, n_devices); if (buf) { free(buf); buf = NULL; } if (should_free_origin) { free((char *) cfg->origin); cfg->origin = NULL; } if (should_free_appid) { free((char *) cfg->appid); cfg->appid = NULL; } if (should_free_auth_file) { free((char *) cfg->auth_file); cfg->auth_file = NULL; } if (should_free_authpending_file) { free((char *) cfg->authpending_file); cfg->authpending_file = NULL; } if (cfg->alwaysok && retval != PAM_SUCCESS) { DBG("alwaysok needed (otherwise return with %d)", retval); retval = PAM_SUCCESS; } DBG("done. [%s]", pam_strerror(pamh, retval)); return retval; } Commit Message: Do not leak file descriptor when doing exec When opening a custom debug file, the descriptor would stay open when calling exec and leak to the child process. Make sure all files are opened with close-on-exec. This fixes CVE-2019-12210. Thanks to Matthias Gerstner of the SUSE Security Team for reporting the issue. CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: find_extend_vma(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma; unsigned long start; addr &= PAGE_MASK; vma = find_vma(mm, addr); if (!vma) return NULL; if (vma->vm_start <= addr) return vma; if (!(vma->vm_flags & VM_GROWSDOWN)) return NULL; start = vma->vm_start; if (expand_stack(vma, addr)) return NULL; if (vma->vm_flags & VM_LOCKED) populate_vma_page_range(vma, addr, start, NULL); return vma; } Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping The core dumping code has always run without holding the mmap_sem for writing, despite that is the only way to ensure that the entire vma layout will not change from under it. Only using some signal serialization on the processes belonging to the mm is not nearly enough. This was pointed out earlier. For example in Hugh's post from Jul 2017: https://lkml.kernel.org/r/[email protected] "Not strictly relevant here, but a related note: I was very surprised to discover, only quite recently, how handle_mm_fault() may be called without down_read(mmap_sem) - when core dumping. That seems a misguided optimization to me, which would also be nice to correct" In particular because the growsdown and growsup can move the vm_start/vm_end the various loops the core dump does around the vma will not be consistent if page faults can happen concurrently. Pretty much all users calling mmget_not_zero()/get_task_mm() and then taking the mmap_sem had the potential to introduce unexpected side effects in the core dumping code. Adding mmap_sem for writing around the ->core_dump invocation is a viable long term fix, but it requires removing all copy user and page faults and to replace them with get_dump_page() for all binary formats which is not suitable as a short term fix. For the time being this solution manually covers the places that can confuse the core dump either by altering the vma layout or the vma flags while it runs. Once ->core_dump runs under mmap_sem for writing the function mmget_still_valid() can be dropped. Allowing mmap_sem protected sections to run in parallel with the coredump provides some minor parallelism advantage to the swapoff code (which seems to be safe enough by never mangling any vma field and can keep doing swapins in parallel to the core dumping) and to some other corner case. In order to facilitate the backporting I added "Fixes: 86039bd3b4e6" however the side effect of this same race condition in /proc/pid/mem should be reproducible since before 2.6.12-rc2 so I couldn't add any other "Fixes:" because there's no hash beyond the git genesis commit. Because find_extend_vma() is the only location outside of the process context that could modify the "mm" structures under mmap_sem for reading, by adding the mmget_still_valid() check to it, all other cases that take the mmap_sem for reading don't need the new check after mmget_not_zero()/get_task_mm(). The expand_stack() in page fault context also doesn't need the new check, because all tasks under core dumping are frozen. Link: http://lkml.kernel.org/r/[email protected] Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization") Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Jann Horn <[email protected]> Suggested-by: Oleg Nesterov <[email protected]> Acked-by: Peter Xu <[email protected]> Reviewed-by: Mike Rapoport <[email protected]> Reviewed-by: Oleg Nesterov <[email protected]> Reviewed-by: Jann Horn <[email protected]> Acked-by: Jason Gunthorpe <[email protected]> Acked-by: Michal Hocko <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: static int hub_ext_port_status(struct usb_hub *hub, int port1, int type, u16 *status, u16 *change, u32 *ext_status) { int ret; int len = 4; if (type != HUB_PORT_STATUS) len = 8; mutex_lock(&hub->status_mutex); ret = get_port_status(hub->hdev, port1, &hub->status->port, type, len); if (ret < len) { if (ret != -ENODEV) dev_err(hub->intfdev, "%s failed (err = %d)\n", __func__, ret); if (ret >= 0) ret = -EIO; } else { *status = le16_to_cpu(hub->status->port.wPortStatus); *change = le16_to_cpu(hub->status->port.wPortChange); if (type != HUB_PORT_STATUS && ext_status) *ext_status = le32_to_cpu( hub->status->port.dwExtPortStatus); ret = 0; } mutex_unlock(&hub->status_mutex); return ret; } Commit Message: USB: check usb_get_extra_descriptor for proper size When reading an extra descriptor, we need to properly check the minimum and maximum size allowed, to prevent from invalid data being sent by a device. Reported-by: Hui Peng <[email protected]> Reported-by: Mathias Payer <[email protected]> Co-developed-by: Linus Torvalds <[email protected]> Signed-off-by: Hui Peng <[email protected]> Signed-off-by: Mathias Payer <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-400 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 UserActivityDetector::MaybeNotify() { base::TimeTicks now = base::TimeTicks::Now(); if (last_observer_notification_time_.is_null() || (now - last_observer_notification_time_).InSecondsF() >= kNotifyIntervalSec) { FOR_EACH_OBSERVER(UserActivityObserver, observers_, OnUserActivity()); last_observer_notification_time_ = now; } } Commit Message: ash: Make UserActivityDetector ignore synthetic mouse events This may have been preventing us from suspending (e.g. mouse event is synthesized in response to lock window being shown so Chrome tells powerd that the user is active). BUG=133419 TEST=added Review URL: https://chromiumcodereview.appspot.com/10574044 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143437 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OTRBrowserContextImpl::OTRBrowserContextImpl( BrowserContextImpl* original, BrowserContextIODataImpl* original_io_data) : BrowserContext(new OTRBrowserContextIODataImpl(original_io_data)), original_context_(original), weak_ptr_factory_(this) { BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServices(this); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static int futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2, union futex_key *key1, union futex_key *key2, struct futex_pi_state **ps, int set_waiters) { struct futex_q *top_waiter = NULL; u32 curval; int ret, vpid; if (get_futex_value_locked(&curval, pifutex)) return -EFAULT; /* * Find the top_waiter and determine if there are additional waiters. * If the caller intends to requeue more than 1 waiter to pifutex, * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now, * as we have means to handle the possible fault. If not, don't set * the bit unecessarily as it will force the subsequent unlock to enter * the kernel. */ top_waiter = futex_top_waiter(hb1, key1); /* There are no waiters, nothing for us to do. */ if (!top_waiter) return 0; /* Ensure we requeue to the expected futex. */ if (!match_futex(top_waiter->requeue_pi_key, key2)) return -EINVAL; /* * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in * the contended case or if set_waiters is 1. The pi_state is returned * in ps in contended cases. */ vpid = task_pid_vnr(top_waiter->task); ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task, set_waiters); if (ret == 1) { requeue_pi_wake_futex(top_waiter, key2, hb2); return vpid; } return ret; } Commit Message: futex-prevent-requeue-pi-on-same-futex.patch futex: Forbid uaddr == uaddr2 in futex_requeue(..., requeue_pi=1) If uaddr == uaddr2, then we have broken the rule of only requeueing from a non-pi futex to a pi futex with this call. If we attempt this, then dangling pointers may be left for rt_waiter resulting in an exploitable condition. This change brings futex_requeue() in line with futex_wait_requeue_pi() which performs the same check as per commit 6f7b0a2a5c0f ("futex: Forbid uaddr == uaddr2 in futex_wait_requeue_pi()") [ tglx: Compare the resulting keys as well, as uaddrs might be different depending on the mapping ] Fixes CVE-2014-3153. Reported-by: Pinkie Pie Signed-off-by: Will Drewry <[email protected]> Signed-off-by: Kees Cook <[email protected]> Cc: [email protected] Signed-off-by: Thomas Gleixner <[email protected]> Reviewed-by: Darren Hart <[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 WebGLRenderingContextBase::SetupFlags() { DCHECK(GetDrawingBuffer()); if (canvas()) { if (Page* p = canvas()->GetDocument().GetPage()) { synthesized_errors_to_console_ = p->GetSettings().GetWebGLErrorsToConsoleEnabled(); } } is_depth_stencil_supported_ = ExtensionsUtil()->IsExtensionEnabled("GL_OES_packed_depth_stencil"); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} 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: init_global_keywords(bool global_active) { /* global definitions mapping */ install_keyword_root("linkbeat_use_polling", use_polling_handler, global_active); #if HAVE_DECL_CLONE_NEWNET install_keyword_root("net_namespace", &net_namespace_handler, global_active); install_keyword_root("namespace_with_ipsets", &namespace_ipsets_handler, global_active); #endif install_keyword_root("use_pid_dir", &use_pid_dir_handler, global_active); install_keyword_root("instance", &instance_handler, global_active); install_keyword_root("child_wait_time", &child_wait_handler, global_active); install_keyword_root("global_defs", NULL, global_active); install_keyword("router_id", &routerid_handler); install_keyword("notification_email_from", &emailfrom_handler); install_keyword("smtp_server", &smtpserver_handler); install_keyword("smtp_helo_name", &smtphelo_handler); install_keyword("smtp_connect_timeout", &smtpto_handler); install_keyword("notification_email", &email_handler); install_keyword("smtp_alert", &smtp_alert_handler); #ifdef _WITH_VRRP_ install_keyword("smtp_alert_vrrp", &smtp_alert_vrrp_handler); #endif #ifdef _WITH_LVS_ install_keyword("smtp_alert_checker", &smtp_alert_checker_handler); #endif #ifdef _WITH_VRRP_ install_keyword("dynamic_interfaces", &dynamic_interfaces_handler); install_keyword("no_email_faults", &no_email_faults_handler); install_keyword("default_interface", &default_interface_handler); #endif #ifdef _WITH_LVS_ install_keyword("lvs_timeouts", &lvs_timeouts); install_keyword("lvs_flush", &lvs_flush_handler); #ifdef _WITH_VRRP_ install_keyword("lvs_sync_daemon", &lvs_syncd_handler); #endif #endif #ifdef _WITH_VRRP_ install_keyword("vrrp_mcast_group4", &vrrp_mcast_group4_handler); install_keyword("vrrp_mcast_group6", &vrrp_mcast_group6_handler); install_keyword("vrrp_garp_master_delay", &vrrp_garp_delay_handler); install_keyword("vrrp_garp_master_repeat", &vrrp_garp_rep_handler); install_keyword("vrrp_garp_master_refresh", &vrrp_garp_refresh_handler); install_keyword("vrrp_garp_master_refresh_repeat", &vrrp_garp_refresh_rep_handler); install_keyword("vrrp_garp_lower_prio_delay", &vrrp_garp_lower_prio_delay_handler); install_keyword("vrrp_garp_lower_prio_repeat", &vrrp_garp_lower_prio_rep_handler); install_keyword("vrrp_garp_interval", &vrrp_garp_interval_handler); install_keyword("vrrp_gna_interval", &vrrp_gna_interval_handler); install_keyword("vrrp_lower_prio_no_advert", &vrrp_lower_prio_no_advert_handler); install_keyword("vrrp_higher_prio_send_advert", &vrrp_higher_prio_send_advert_handler); install_keyword("vrrp_version", &vrrp_version_handler); install_keyword("vrrp_iptables", &vrrp_iptables_handler); #ifdef _HAVE_LIBIPSET_ install_keyword("vrrp_ipsets", &vrrp_ipsets_handler); #endif install_keyword("vrrp_check_unicast_src", &vrrp_check_unicast_src_handler); install_keyword("vrrp_skip_check_adv_addr", &vrrp_check_adv_addr_handler); install_keyword("vrrp_strict", &vrrp_strict_handler); install_keyword("vrrp_priority", &vrrp_prio_handler); install_keyword("vrrp_no_swap", &vrrp_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("vrrp_rt_priority", &vrrp_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("vrrp_rlimit_rtime", &vrrp_rt_rlimit_handler); #endif #endif #endif install_keyword("notify_fifo", &global_notify_fifo); install_keyword("notify_fifo_script", &global_notify_fifo_script); #ifdef _WITH_VRRP_ install_keyword("vrrp_notify_fifo", &vrrp_notify_fifo); install_keyword("vrrp_notify_fifo_script", &vrrp_notify_fifo_script); #endif #ifdef _WITH_LVS_ install_keyword("lvs_notify_fifo", &lvs_notify_fifo); install_keyword("lvs_notify_fifo_script", &lvs_notify_fifo_script); install_keyword("checker_priority", &checker_prio_handler); install_keyword("checker_no_swap", &checker_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("checker_rt_priority", &checker_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("checker_rlimit_rtime", &checker_rt_rlimit_handler); #endif #endif #endif #ifdef _WITH_BFD_ install_keyword("bfd_priority", &bfd_prio_handler); install_keyword("bfd_no_swap", &bfd_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("bfd_rt_priority", &bfd_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("bfd_rlimit_rtime", &bfd_rt_rlimit_handler); #endif #endif #endif #ifdef _WITH_SNMP_ install_keyword("snmp_socket", &snmp_socket_handler); install_keyword("enable_traps", &trap_handler); #ifdef _WITH_SNMP_VRRP_ install_keyword("enable_snmp_vrrp", &snmp_vrrp_handler); install_keyword("enable_snmp_keepalived", &snmp_vrrp_handler); /* Deprecated v2.0.0 */ #endif #ifdef _WITH_SNMP_RFC_ install_keyword("enable_snmp_rfc", &snmp_rfc_handler); #endif #ifdef _WITH_SNMP_RFCV2_ install_keyword("enable_snmp_rfcv2", &snmp_rfcv2_handler); #endif #ifdef _WITH_SNMP_RFCV3_ install_keyword("enable_snmp_rfcv3", &snmp_rfcv3_handler); #endif #ifdef _WITH_SNMP_CHECKER_ install_keyword("enable_snmp_checker", &snmp_checker_handler); #endif #endif #ifdef _WITH_DBUS_ install_keyword("enable_dbus", &enable_dbus_handler); install_keyword("dbus_service_name", &dbus_service_name_handler); #endif install_keyword("script_user", &script_user_handler); install_keyword("enable_script_security", &script_security_handler); #ifdef _WITH_VRRP_ install_keyword("vrrp_netlink_cmd_rcv_bufs", &vrrp_netlink_cmd_rcv_bufs_handler); install_keyword("vrrp_netlink_cmd_rcv_bufs_force", &vrrp_netlink_cmd_rcv_bufs_force_handler); install_keyword("vrrp_netlink_monitor_rcv_bufs", &vrrp_netlink_monitor_rcv_bufs_handler); install_keyword("vrrp_netlink_monitor_rcv_bufs_force", &vrrp_netlink_monitor_rcv_bufs_force_handler); #endif #ifdef _WITH_LVS_ install_keyword("lvs_netlink_cmd_rcv_bufs", &lvs_netlink_cmd_rcv_bufs_handler); install_keyword("lvs_netlink_cmd_rcv_bufs_force", &lvs_netlink_cmd_rcv_bufs_force_handler); install_keyword("lvs_netlink_monitor_rcv_bufs", &lvs_netlink_monitor_rcv_bufs_handler); install_keyword("lvs_netlink_monitor_rcv_bufs_force", &lvs_netlink_monitor_rcv_bufs_force_handler); #endif #ifdef _WITH_LVS_ install_keyword("rs_init_notifies", &rs_init_notifies_handler); install_keyword("no_checker_emails", &no_checker_emails_handler); #endif #ifdef _WITH_VRRP_ install_keyword("vrrp_rx_bufs_policy", &vrrp_rx_bufs_policy_handler); install_keyword("vrrp_rx_bufs_multiplier", &vrrp_rx_bufs_multiplier_handler); #endif } Commit Message: Add command line and configuration option to set umask Issue #1048 identified that files created by keepalived are created with mode 0666. This commit changes the default to 0644, and also allows the umask to be specified in the configuration or as a command line option. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: const char* Tags::SimpleTag::GetTagString() const { return m_tag_string; } Commit Message: Fix ParseElementHeader to support 0 payload elements Cherry-pick'ing Change 5c83bbec9a5f6f00a349674ddad85b753d2ea219 from upstream. This fixes regression in some edge cases for mkv playback. BUG=26499283 Change-Id: I88de03219a3d941b6b2f251d384e29c36bdd4d9b 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 Downmix_Command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { downmix_module_t *pDwmModule = (downmix_module_t *) self; downmix_object_t *pDownmixer; int retsize; if (pDwmModule == NULL || pDwmModule->context.state == DOWNMIX_STATE_UNINITIALIZED) { return -EINVAL; } pDownmixer = (downmix_object_t*) &pDwmModule->context; ALOGV("Downmix_Command command %" PRIu32 " cmdSize %" PRIu32, cmdCode, cmdSize); switch (cmdCode) { case EFFECT_CMD_INIT: if (pReplyData == NULL || *replySize != sizeof(int)) { return -EINVAL; } *(int *) pReplyData = Downmix_Init(pDwmModule); break; case EFFECT_CMD_SET_CONFIG: if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL || *replySize != sizeof(int)) { return -EINVAL; } *(int *) pReplyData = Downmix_Configure(pDwmModule, (effect_config_t *)pCmdData, false); break; case EFFECT_CMD_RESET: Downmix_Reset(pDownmixer, false); break; case EFFECT_CMD_GET_PARAM: ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM pCmdData %p, *replySize %" PRIu32 ", pReplyData: %p", pCmdData, *replySize, pReplyData); if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)) || pReplyData == NULL || *replySize < (int) sizeof(effect_param_t) + 2 * sizeof(int32_t)) { return -EINVAL; } effect_param_t *rep = (effect_param_t *) pReplyData; memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(int32_t)); ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM param %" PRId32 ", replySize %" PRIu32, *(int32_t *)rep->data, rep->vsize); rep->status = Downmix_getParameter(pDownmixer, *(int32_t *)rep->data, &rep->vsize, rep->data + sizeof(int32_t)); *replySize = sizeof(effect_param_t) + sizeof(int32_t) + rep->vsize; break; case EFFECT_CMD_SET_PARAM: ALOGV("Downmix_Command EFFECT_CMD_SET_PARAM cmdSize %d pCmdData %p, *replySize %" PRIu32 ", pReplyData %p", cmdSize, pCmdData, *replySize, pReplyData); if (pCmdData == NULL || (cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t))) || pReplyData == NULL || *replySize != (int)sizeof(int32_t)) { return -EINVAL; } effect_param_t *cmd = (effect_param_t *) pCmdData; *(int *)pReplyData = Downmix_setParameter(pDownmixer, *(int32_t *)cmd->data, cmd->vsize, cmd->data + sizeof(int32_t)); break; case EFFECT_CMD_SET_PARAM_DEFERRED: ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_DEFERRED not supported, FIXME"); break; case EFFECT_CMD_SET_PARAM_COMMIT: ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_COMMIT not supported, FIXME"); break; case EFFECT_CMD_ENABLE: if (pReplyData == NULL || *replySize != sizeof(int)) { return -EINVAL; } if (pDownmixer->state != DOWNMIX_STATE_INITIALIZED) { return -ENOSYS; } pDownmixer->state = DOWNMIX_STATE_ACTIVE; ALOGV("EFFECT_CMD_ENABLE() OK"); *(int *)pReplyData = 0; break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)) { return -EINVAL; } if (pDownmixer->state != DOWNMIX_STATE_ACTIVE) { return -ENOSYS; } pDownmixer->state = DOWNMIX_STATE_INITIALIZED; ALOGV("EFFECT_CMD_DISABLE() OK"); *(int *)pReplyData = 0; break; case EFFECT_CMD_SET_DEVICE: if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) { return -EINVAL; } ALOGV("Downmix_Command EFFECT_CMD_SET_DEVICE: 0x%08" PRIx32, *(uint32_t *)pCmdData); break; case EFFECT_CMD_SET_VOLUME: { if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t) * 2) { return -EINVAL; } ALOGW("Downmix_Command command EFFECT_CMD_SET_VOLUME not supported, FIXME"); float left = (float)(*(uint32_t *)pCmdData) / (1 << 24); float right = (float)(*((uint32_t *)pCmdData + 1)) / (1 << 24); ALOGV("Downmix_Command EFFECT_CMD_SET_VOLUME: left %f, right %f ", left, right); break; } case EFFECT_CMD_SET_AUDIO_MODE: if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) { return -EINVAL; } ALOGV("Downmix_Command EFFECT_CMD_SET_AUDIO_MODE: %" PRIu32, *(uint32_t *)pCmdData); break; case EFFECT_CMD_SET_CONFIG_REVERSE: case EFFECT_CMD_SET_INPUT_DEVICE: break; default: ALOGW("Downmix_Command invalid command %" PRIu32, cmdCode); return -EINVAL; } return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) 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 crypto_report_acomp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_acomp racomp; strlcpy(racomp.type, "acomp", sizeof(racomp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_ACOMP, sizeof(struct crypto_report_acomp), &racomp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Commit Message: crypto: user - fix leaking uninitialized memory to userspace All bytes of the NETLINK_CRYPTO report structures must be initialized, since they are copied to userspace. The change from strncpy() to strlcpy() broke this. As a minimal fix, change it back. Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion") Cc: <[email protected]> # v4.12+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: Target: 1 Example 2: Code: static void pdf_run_sc_color(fz_context *ctx, pdf_processor *proc, int n, float *color) { pdf_run_processor *pr = (pdf_run_processor *)proc; pr->dev->flags &= ~FZ_DEVFLAG_FILLCOLOR_UNDEFINED; pdf_set_color(ctx, pr, PDF_FILL, color); } 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: void PageInfoBubbleView::WebContentsDestroyed() { weak_factory_.InvalidateWeakPtrs(); } Commit Message: Desktop Page Info/Harmony: Show close button for internal pages. The Harmony version of Page Info for internal Chrome pages (chrome://, chrome-extension:// and view-source:// pages) show a close button. Update the code to match this. This patch also adds TestBrowserDialog tests for the latter two cases described above (internal extension and view source pages). See screenshot - https://drive.google.com/file/d/18RZnMiHCu-rCX9N6DLUpu4mkFWguh1xm/view?usp=sharing Bug: 535074 Change-Id: I55e5f1aa682fd4ec85f7b65ac88f5a4f5906fe53 Reviewed-on: https://chromium-review.googlesource.com/759624 Commit-Queue: Patti <[email protected]> Reviewed-by: Trent Apted <[email protected]> Cr-Commit-Position: refs/heads/master@{#516624} CWE ID: CWE-704 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static char *print_string_ptr( const char *str ) { const char *ptr; char *ptr2, *out; int len = 0; unsigned char token; if ( ! str ) return cJSON_strdup( "" ); ptr = str; while ( ( token = *ptr ) && ++len ) { if ( strchr( "\"\\\b\f\n\r\t", token ) ) ++len; else if ( token < 32 ) len += 5; ++ptr; } if ( ! ( out = (char*) cJSON_malloc( len + 3 ) ) ) return 0; ptr2 = out; ptr = str; *ptr2++ = '\"'; while ( *ptr ) { if ( (unsigned char) *ptr > 31 && *ptr != '\"' && *ptr != '\\' ) *ptr2++ = *ptr++; else { *ptr2++ = '\\'; switch ( token = *ptr++ ) { case '\\': *ptr2++ = '\\'; break; case '\"': *ptr2++ = '\"'; break; case '\b': *ptr2++ = 'b'; break; case '\f': *ptr2++ = 'f'; break; case '\n': *ptr2++ = 'n'; break; case '\r': *ptr2++ = 'r'; break; case '\t': *ptr2++ = 't'; break; default: /* Escape and print. */ sprintf( ptr2, "u%04x", token ); ptr2 += 5; break; } } } *ptr2++ = '\"'; *ptr2++ = 0; return out; } 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 CCPrepare gen_prepare_eflags_o(DisasContext *s, TCGv reg) { switch (s->cc_op) { case CC_OP_ADOX: case CC_OP_ADCOX: return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src2, .mask = -1, .no_setcond = true }; case CC_OP_CLR: case CC_OP_POPCNT: return (CCPrepare) { .cond = TCG_COND_NEVER, .mask = -1 }; default: gen_compute_eflags(s); return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src, .mask = CC_O }; } } Commit Message: tcg/i386: Check the size of instruction being translated This fixes the bug: 'user-to-root privesc inside VM via bad translation caching' reported by Jann Horn here: https://bugs.chromium.org/p/project-zero/issues/detail?id=1122 Reviewed-by: Richard Henderson <[email protected]> CC: Peter Maydell <[email protected]> CC: Paolo Bonzini <[email protected]> Reported-by: Jann Horn <[email protected]> Signed-off-by: Pranith Kumar <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-94 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 ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { Stream_SetPosition(s, fields->BufferOffset); Stream_Write(s, fields->Buffer, fields->Len); } } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. 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: getword(f, word, newlinep, filename) FILE *f; char *word; int *newlinep; char *filename; { int c, len, escape; int quoted, comment; int value, digit, got, n; #define isoctal(c) ((c) >= '0' && (c) < '8') *newlinep = 0; len = 0; escape = 0; comment = 0; quoted = 0; /* * First skip white-space and comments. */ for (;;) { c = getc(f); if (c == EOF) break; /* * A newline means the end of a comment; backslash-newline * is ignored. Note that we cannot have escape && comment. */ if (c == '\n') { if (!escape) { *newlinep = 1; comment = 0; } else escape = 0; continue; } /* * Ignore characters other than newline in a comment. */ if (comment) continue; /* * If this character is escaped, we have a word start. */ if (escape) break; /* * If this is the escape character, look at the next character. */ if (c == '\\') { escape = 1; continue; } /* * If this is the start of a comment, ignore the rest of the line. */ if (c == '#') { comment = 1; continue; } /* * A non-whitespace character is the start of a word. */ if (!isspace(c)) break; } /* * Process characters until the end of the word. */ while (c != EOF) { if (escape) { /* * This character is escaped: backslash-newline is ignored, * various other characters indicate particular values * as for C backslash-escapes. */ escape = 0; if (c == '\n') { c = getc(f); continue; } got = 0; switch (c) { case 'a': value = '\a'; break; case 'b': value = '\b'; break; case 'f': value = '\f'; break; case 'n': value = '\n'; break; case 'r': value = '\r'; break; case 's': value = ' '; break; case 't': value = '\t'; break; default: if (isoctal(c)) { /* * \ddd octal sequence */ value = 0; for (n = 0; n < 3 && isoctal(c); ++n) { value = (value << 3) + (c & 07); c = getc(f); } got = 1; break; } if (c == 'x') { /* * \x<hex_string> sequence */ value = 0; c = getc(f); for (n = 0; n < 2 && isxdigit(c); ++n) { digit = toupper(c) - '0'; if (digit > 10) digit += '0' + 10 - 'A'; value = (value << 4) + digit; c = getc (f); } got = 1; break; } /* * Otherwise the character stands for itself. */ value = c; break; } /* * Store the resulting character for the escape sequence. */ if (len < MAXWORDLEN-1) word[len] = value; ++len; if (!got) c = getc(f); continue; } /* * Backslash starts a new escape sequence. */ if (c == '\\') { escape = 1; c = getc(f); continue; } /* * Not escaped: check for the start or end of a quoted * section and see if we've reached the end of the word. */ if (quoted) { if (c == quoted) { quoted = 0; c = getc(f); continue; } } else if (c == '"' || c == '\'') { quoted = c; c = getc(f); continue; } else if (isspace(c) || c == '#') { ungetc (c, f); break; } /* * An ordinary character: store it in the word and get another. */ if (len < MAXWORDLEN-1) word[len] = c; ++len; c = getc(f); } /* * End of the word: check for errors. */ if (c == EOF) { if (ferror(f)) { if (errno == 0) errno = EIO; option_error("Error reading %s: %m", filename); die(1); } /* * If len is zero, then we didn't find a word before the * end of the file. */ if (len == 0) return 0; if (quoted) option_error("warning: quoted word runs to end of file (%.20s...)", filename, word); } /* * Warn if the word was too long, and append a terminating null. */ if (len >= MAXWORDLEN) { option_error("warning: word in file %s too long (%.20s...)", filename, word); len = MAXWORDLEN - 1; } word[len] = 0; return 1; #undef isoctal } Commit Message: pppd: Eliminate potential integer overflow in option parsing When we are reading in a word from an options file, we maintain a count of the length we have seen so far in 'len', which is an int. When len exceeds MAXWORDLEN - 1 (i.e. 1023) we cease storing characters in the buffer but we continue to increment len. Since len is an int, it will wrap around to -2147483648 after it reaches 2147483647. At that point our test of (len < MAXWORDLEN-1) will succeed and we will start writing characters to memory again. This may enable an attacker to overwrite the heap and thereby corrupt security-relevant variables. For this reason it has been assigned a CVE identifier, CVE-2014-3158. This fixes the bug by ceasing to increment len once it reaches MAXWORDLEN. Reported-by: Lee Campbell <[email protected]> Signed-off-by: Paul Mackerras <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: unlock_encryption_data_ref (UnlockEncryptionData *data) { data->refcount++; return data; } Commit Message: 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 __init sco_init(void) { int err; err = proto_register(&sco_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_SCO, &sco_sock_family_ops); if (err < 0) { BT_ERR("SCO socket registration failed"); goto error; } err = bt_procfs_init(&init_net, "sco", &sco_sk_list, NULL); if (err < 0) { BT_ERR("Failed to create SCO proc file"); bt_sock_unregister(BTPROTO_SCO); goto error; } BT_INFO("SCO socket layer initialized"); if (IS_ERR_OR_NULL(bt_debugfs)) return 0; sco_debugfs = debugfs_create_file("sco", 0444, bt_debugfs, NULL, &sco_debugfs_fops); return 0; error: proto_unregister(&sco_proto); return err; } 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: static u32 svc_rdma_get_inv_rkey(struct rpcrdma_msg *rdma_argp, struct rpcrdma_write_array *wr_ary, struct rpcrdma_write_array *rp_ary) { struct rpcrdma_read_chunk *rd_ary; struct rpcrdma_segment *arg_ch; rd_ary = (struct rpcrdma_read_chunk *)&rdma_argp->rm_body.rm_chunks[0]; if (rd_ary->rc_discrim != xdr_zero) return be32_to_cpu(rd_ary->rc_target.rs_handle); if (wr_ary && be32_to_cpu(wr_ary->wc_nchunks)) { arg_ch = &wr_ary->wc_array[0].wc_target; return be32_to_cpu(arg_ch->rs_handle); } if (rp_ary && be32_to_cpu(rp_ary->wc_nchunks)) { arg_ch = &rp_ary->wc_array[0].wc_target; return be32_to_cpu(arg_ch->rs_handle); } return 0; } 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: static bool update_sd_pick_busiest(struct lb_env *env, struct sd_lb_stats *sds, struct sched_group *sg, struct sg_lb_stats *sgs) { struct sg_lb_stats *busiest = &sds->busiest_stat; /* * Don't try to pull misfit tasks we can't help. * We can use max_capacity here as reduction in capacity on some * CPUs in the group should either be possible to resolve * internally or be covered by avg_load imbalance (eventually). */ if (sgs->group_type == group_misfit_task && (!group_smaller_max_cpu_capacity(sg, sds->local) || !group_has_capacity(env, &sds->local_stat))) return false; if (sgs->group_type > busiest->group_type) return true; if (sgs->group_type < busiest->group_type) return false; if (sgs->avg_load <= busiest->avg_load) return false; if (!(env->sd->flags & SD_ASYM_CPUCAPACITY)) goto asym_packing; /* * Candidate sg has no more than one task per CPU and * has higher per-CPU capacity. Migrating tasks to less * capable CPUs may harm throughput. Maximize throughput, * power/energy consequences are not considered. */ if (sgs->sum_nr_running <= sgs->group_weight && group_smaller_min_cpu_capacity(sds->local, sg)) return false; /* * If we have more than one misfit sg go with the biggest misfit. */ if (sgs->group_type == group_misfit_task && sgs->group_misfit_task_load < busiest->group_misfit_task_load) return false; asym_packing: /* This is the busiest node in its class. */ if (!(env->sd->flags & SD_ASYM_PACKING)) return true; /* No ASYM_PACKING if target CPU is already busy */ if (env->idle == CPU_NOT_IDLE) return true; /* * ASYM_PACKING needs to move all the work to the highest * prority CPUs in the group, therefore mark all groups * of lower priority than ourself as busy. */ if (sgs->sum_nr_running && sched_asym_prefer(env->dst_cpu, sg->asym_prefer_cpu)) { if (!sds->busiest) return true; /* Prefer to move from lowest priority CPU's work */ if (sched_asym_prefer(sds->busiest->asym_prefer_cpu, sg->asym_prefer_cpu)) return true; } return false; } Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <[email protected]> Analyzed-by: Vincent Guittot <[email protected]> Reported-by: Zhipeng Xie <[email protected]> Reported-by: Sargun Dhillon <[email protected]> Reported-by: Xie XiuQi <[email protected]> Tested-by: Zhipeng Xie <[email protected]> Tested-by: Sargun Dhillon <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Acked-by: Vincent Guittot <[email protected]> Cc: <[email protected]> # v4.13+ Cc: Bin Li <[email protected]> Cc: Mike Galbraith <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Tejun Heo <[email protected]> Cc: Thomas Gleixner <[email protected]> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-400 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_fast32_t pgx_getword(jas_stream_t *in, bool bigendian, int prec) { uint_fast32_t val; int i; int j; int c; int wordsize; wordsize = (prec + 7) / 8; if (prec > 32) { goto error; } val = 0; for (i = 0; i < wordsize; ++i) { if ((c = jas_stream_getc(in)) == EOF) { goto error; } j = bigendian ? (wordsize - 1 - i) : i; val = val | ((c & 0xff) << (8 * j)); } val &= (1 << prec) - 1; return val; error: return -1; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Output:
0