instruction
stringclasses
1 value
input
stringlengths
56
241k
output
int64
0
1
__index_level_0__
int64
0
175k
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: command_set_status_text (Fep *fep, FepControlMessage *request) { FepAttribute attr; if (_fep_control_message_read_attribute_arg (request, 1, &attr) == 0) _fep_output_status_text (fep, request->args[0].str, &attr); } Commit Message: Don't use abstract Unix domain sockets CWE ID: CWE-264
0
36,955
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: poolStoreString(STRING_POOL *pool, const ENCODING *enc, const char *ptr, const char *end) { if (! poolAppend(pool, enc, ptr, end)) return NULL; if (pool->ptr == pool->end && ! poolGrow(pool)) return NULL; *(pool->ptr)++ = 0; return pool->start; } Commit Message: xmlparse.c: Deny internal entities closing the doctype CWE ID: CWE-611
0
88,300
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void FrameView::updateAnnotatedRegions() { Document* document = m_frame->document(); if (!document->hasAnnotatedRegions()) return; Vector<AnnotatedRegionValue> newRegions; document->renderBox()->collectAnnotatedRegions(newRegions); if (newRegions == document->annotatedRegions()) return; document->setAnnotatedRegions(newRegions); if (Page* page = m_frame->page()) page->chrome().client().annotatedRegionsChanged(); } 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 R=vollick@chromium.org 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
0
119,944
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: hook_process_run (struct t_hook *hook_process) { int pipe_stdout[2], pipe_stderr[2], timeout, max_calls; long interval; pid_t pid; /* create pipe for child process (stdout) */ if (pipe (pipe_stdout) < 0) { (void) (HOOK_PROCESS(hook_process, callback)) (hook_process->callback_data, HOOK_PROCESS(hook_process, command), WEECHAT_HOOK_PROCESS_ERROR, NULL, NULL); unhook (hook_process); return; } if (pipe (pipe_stderr) < 0) { close (pipe_stdout[0]); close (pipe_stdout[1]); (void) (HOOK_PROCESS(hook_process, callback)) (hook_process->callback_data, HOOK_PROCESS(hook_process, command), WEECHAT_HOOK_PROCESS_ERROR, NULL, NULL); unhook (hook_process); return; } HOOK_PROCESS(hook_process, child_read[HOOK_PROCESS_STDOUT]) = pipe_stdout[0]; HOOK_PROCESS(hook_process, child_write[HOOK_PROCESS_STDOUT]) = pipe_stdout[1]; HOOK_PROCESS(hook_process, child_read[HOOK_PROCESS_STDERR]) = pipe_stderr[0]; HOOK_PROCESS(hook_process, child_write[HOOK_PROCESS_STDERR]) = pipe_stderr[1]; switch (pid = fork ()) { /* fork failed */ case -1: (void) (HOOK_PROCESS(hook_process, callback)) (hook_process->callback_data, HOOK_PROCESS(hook_process, command), WEECHAT_HOOK_PROCESS_ERROR, NULL, NULL); unhook (hook_process); return; /* child process */ case 0: setuid (getuid ()); hook_process_child (hook_process); /* never executed */ _exit (EXIT_SUCCESS); break; } /* parent process */ HOOK_PROCESS(hook_process, child_pid) = pid; close (HOOK_PROCESS(hook_process, child_write[HOOK_PROCESS_STDOUT])); HOOK_PROCESS(hook_process, child_write[HOOK_PROCESS_STDOUT]) = -1; close (HOOK_PROCESS(hook_process, child_write[HOOK_PROCESS_STDERR])); HOOK_PROCESS(hook_process, child_write[HOOK_PROCESS_STDERR]) = -1; HOOK_PROCESS(hook_process, hook_fd[HOOK_PROCESS_STDOUT]) = hook_fd (hook_process->plugin, HOOK_PROCESS(hook_process, child_read[HOOK_PROCESS_STDOUT]), 1, 0, 0, &hook_process_child_read_stdout_cb, hook_process); HOOK_PROCESS(hook_process, hook_fd[HOOK_PROCESS_STDERR]) = hook_fd (hook_process->plugin, HOOK_PROCESS(hook_process, child_read[HOOK_PROCESS_STDERR]), 1, 0, 0, &hook_process_child_read_stderr_cb, hook_process); timeout = HOOK_PROCESS(hook_process, timeout); interval = 100; max_calls = 0; if (timeout > 0) { if (timeout <= 100) { interval = timeout; max_calls = 1; } else { interval = 100; max_calls = timeout / 100; if (timeout % 100 == 0) max_calls++; } } HOOK_PROCESS(hook_process, hook_timer) = hook_timer (hook_process->plugin, interval, 0, max_calls, &hook_process_timer_cb, hook_process); } Commit Message: CWE ID: CWE-20
0
3,433
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: views::Widget* GetCalloutWidgetForPanel(aura::Window* panel) { PanelLayoutManager* manager = PanelLayoutManager::Get(panel); DCHECK(manager); PanelLayoutManager::PanelList::iterator found = std::find( manager->panel_windows_.begin(), manager->panel_windows_.end(), panel); DCHECK(found != manager->panel_windows_.end()); DCHECK(found->callout_widget); return found->CalloutWidget(); } Commit Message: cros: Enable some tests in //ash/wm in ash_unittests --mash For the ones that fail, disable them via filter file instead of in the code, per our disablement policy. Bug: 698085, 695556, 698878, 698888, 698093, 698894 Test: ash_unittests --mash Change-Id: Ic145ab6a95508968d6884d14fac2a3ca08888d26 Reviewed-on: https://chromium-review.googlesource.com/752423 Commit-Queue: James Cook <jamescook@chromium.org> Reviewed-by: Steven Bennetts <stevenjb@chromium.org> Cr-Commit-Position: refs/heads/master@{#513836} CWE ID: CWE-119
0
133,240
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void handle_satn_stop(ESPState *s) { if (s->dma && !s->dma_enabled) { s->dma_cb = handle_satn_stop; return; } s->cmdlen = get_cmd(s, s->cmdbuf, sizeof(s->cmdbuf)); if (s->cmdlen) { trace_esp_handle_satn_stop(s->cmdlen); s->do_cmd = 1; s->rregs[ESP_RSTAT] = STAT_TC | STAT_CD; s->rregs[ESP_RINTR] = INTR_BS | INTR_FC; s->rregs[ESP_RSEQ] = SEQ_CD; esp_raise_irq(s); } } Commit Message: CWE ID: CWE-787
0
9,324
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: DoCreatePbuffer(ClientPtr client, int screenNum, XID fbconfigId, int width, int height, XID glxDrawableId) { __GLXconfig *config; __GLXscreen *pGlxScreen; PixmapPtr pPixmap; int err; LEGAL_NEW_RESOURCE(glxDrawableId, client); if (!validGlxScreen(client, screenNum, &pGlxScreen, &err)) return err; if (!validGlxFBConfig(client, pGlxScreen, fbconfigId, &config, &err)) return err; __glXenterServer(GL_FALSE); pPixmap = (*pGlxScreen->pScreen->CreatePixmap) (pGlxScreen->pScreen, width, height, config->rgbBits, 0); __glXleaveServer(GL_FALSE); /* Assign the pixmap the same id as the pbuffer and add it as a * resource so it and the DRI2 drawable will be reclaimed when the * pbuffer is destroyed. */ pPixmap->drawable.id = glxDrawableId; if (!AddResource(pPixmap->drawable.id, RT_PIXMAP, pPixmap)) return BadAlloc; return DoCreateGLXDrawable(client, pGlxScreen, config, &pPixmap->drawable, glxDrawableId, glxDrawableId, GLX_DRAWABLE_PBUFFER); } Commit Message: CWE ID: CWE-20
0
14,131
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void addrconf_verify_rtnl(void) { unsigned long now, next, next_sec, next_sched; struct inet6_ifaddr *ifp; int i; ASSERT_RTNL(); rcu_read_lock_bh(); now = jiffies; next = round_jiffies_up(now + ADDR_CHECK_FREQUENCY); cancel_delayed_work(&addr_chk_work); for (i = 0; i < IN6_ADDR_HSIZE; i++) { restart: hlist_for_each_entry_rcu_bh(ifp, &inet6_addr_lst[i], addr_lst) { unsigned long age; /* When setting preferred_lft to a value not zero or * infinity, while valid_lft is infinity * IFA_F_PERMANENT has a non-infinity life time. */ if ((ifp->flags & IFA_F_PERMANENT) && (ifp->prefered_lft == INFINITY_LIFE_TIME)) continue; spin_lock(&ifp->lock); /* We try to batch several events at once. */ age = (now - ifp->tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ; if (ifp->valid_lft != INFINITY_LIFE_TIME && age >= ifp->valid_lft) { spin_unlock(&ifp->lock); in6_ifa_hold(ifp); ipv6_del_addr(ifp); goto restart; } else if (ifp->prefered_lft == INFINITY_LIFE_TIME) { spin_unlock(&ifp->lock); continue; } else if (age >= ifp->prefered_lft) { /* jiffies - ifp->tstamp > age >= ifp->prefered_lft */ int deprecate = 0; if (!(ifp->flags&IFA_F_DEPRECATED)) { deprecate = 1; ifp->flags |= IFA_F_DEPRECATED; } if ((ifp->valid_lft != INFINITY_LIFE_TIME) && (time_before(ifp->tstamp + ifp->valid_lft * HZ, next))) next = ifp->tstamp + ifp->valid_lft * HZ; spin_unlock(&ifp->lock); if (deprecate) { in6_ifa_hold(ifp); ipv6_ifa_notify(0, ifp); in6_ifa_put(ifp); goto restart; } } else if ((ifp->flags&IFA_F_TEMPORARY) && !(ifp->flags&IFA_F_TENTATIVE)) { unsigned long regen_advance = ifp->idev->cnf.regen_max_retry * ifp->idev->cnf.dad_transmits * NEIGH_VAR(ifp->idev->nd_parms, RETRANS_TIME) / HZ; if (age >= ifp->prefered_lft - regen_advance) { struct inet6_ifaddr *ifpub = ifp->ifpub; if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next)) next = ifp->tstamp + ifp->prefered_lft * HZ; if (!ifp->regen_count && ifpub) { ifp->regen_count++; in6_ifa_hold(ifp); in6_ifa_hold(ifpub); spin_unlock(&ifp->lock); spin_lock(&ifpub->lock); ifpub->regen_count = 0; spin_unlock(&ifpub->lock); ipv6_create_tempaddr(ifpub, ifp); in6_ifa_put(ifpub); in6_ifa_put(ifp); goto restart; } } else if (time_before(ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ, next)) next = ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ; spin_unlock(&ifp->lock); } else { /* ifp->prefered_lft <= ifp->valid_lft */ if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next)) next = ifp->tstamp + ifp->prefered_lft * HZ; spin_unlock(&ifp->lock); } } } next_sec = round_jiffies_up(next); next_sched = next; /* If rounded timeout is accurate enough, accept it. */ if (time_before(next_sec, next + ADDRCONF_TIMER_FUZZ)) next_sched = next_sec; /* And minimum interval is ADDRCONF_TIMER_FUZZ_MAX. */ if (time_before(next_sched, jiffies + ADDRCONF_TIMER_FUZZ_MAX)) next_sched = jiffies + ADDRCONF_TIMER_FUZZ_MAX; ADBG(KERN_DEBUG "now = %lu, schedule = %lu, rounded schedule = %lu => %lu\n", now, next, next_sec, next_sched); mod_delayed_work(addrconf_wq, &addr_chk_work, next_sched - now); rcu_read_unlock_bh(); } Commit Message: ipv6: addrconf: validate new MTU before applying it Currently we don't check if the new MTU is valid or not and this allows one to configure a smaller than minimum allowed by RFCs or even bigger than interface own MTU, which is a problem as it may lead to packet drops. If you have a daemon like NetworkManager running, this may be exploited by remote attackers by forging RA packets with an invalid MTU, possibly leading to a DoS. (NetworkManager currently only validates for values too small, but not for too big ones.) The fix is just to make sure the new value is valid. That is, between IPV6_MIN_MTU and interface's MTU. Note that similar check is already performed at ndisc_router_discovery(), for when kernel itself parses the RA. Signed-off-by: Marcelo Ricardo Leitner <mleitner@redhat.com> Signed-off-by: Sabrina Dubroca <sd@queasysnail.net> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
41,805
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: coolkey_v1_get_attribute_data(const u8 *attr, size_t buf_len, sc_cardctl_coolkey_attribute_t *attr_out) { int r; size_t len; coolkey_attribute_header_t *attribute_head = (coolkey_attribute_header_t *)attr; if (buf_len < sizeof(coolkey_attribute_header_t)) { return SC_ERROR_CORRUPTED_DATA; } /* we must have type V1. Process according to data type */ switch (attribute_head->attribute_data_type) { /* ULONG has implied length of 4 */ case COOLKEY_ATTR_TYPE_INTEGER: if (buf_len < (sizeof(coolkey_attribute_header_t) + 4)) { return SC_ERROR_CORRUPTED_DATA; } attr_out->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_ULONG; attr_out->attribute_length = 4; attr_out->attribute_value = attr + sizeof(coolkey_attribute_header_t); return SC_SUCCESS; /* BOOL_FALSE and BOOL_TRUE have implied length and data */ /* return type STRING for BOOLS */ case COOLKEY_ATTR_TYPE_BOOL_FALSE: attr_out->attribute_length = 1; attr_out->attribute_value = &coolkey_static_false; return SC_SUCCESS; case COOLKEY_ATTR_TYPE_BOOL_TRUE: attr_out->attribute_length = 1; attr_out->attribute_value = &coolkey_static_true; return SC_SUCCESS; /* string type has encoded length */ case COOLKEY_ATTR_TYPE_STRING: r = coolkey_v1_get_attribute_len(attr, buf_len, &len, 0); if (r < SC_SUCCESS) { return r; } if (buf_len < (len + sizeof(coolkey_attribute_header_t) + 2)) { return SC_ERROR_CORRUPTED_DATA; } attr_out->attribute_value = attr+sizeof(coolkey_attribute_header_t)+2; attr_out->attribute_length = len; return SC_SUCCESS; default: break; } return SC_ERROR_CORRUPTED_DATA; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
0
78,323
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int index_reuc_insert( git_index *index, git_index_reuc_entry *reuc) { int res; assert(index && reuc && reuc->path != NULL); assert(git_vector_is_sorted(&index->reuc)); res = git_vector_insert_sorted(&index->reuc, reuc, &index_reuc_on_dup); return res == GIT_EEXISTS ? 0 : res; } Commit Message: index: convert `read_entry` to return entry size via an out-param The function `read_entry` does not conform to our usual coding style of returning stuff via the out parameter and to use the return value for reporting errors. Due to most of our code conforming to that pattern, it has become quite natural for us to actually return `-1` in case there is any error, which has also slipped in with commit 5625d86b9 (index: support index v4, 2016-05-17). As the function returns an `size_t` only, though, the return value is wrapped around, causing the caller of `read_tree` to continue with an invalid index entry. Ultimately, this can lead to a double-free. Improve code and fix the bug by converting the function to return the index entry size via an out parameter and only using the return value to indicate errors. Reported-by: Krishna Ram Prakash R <krp@gtux.in> Reported-by: Vivek Parikh <viv0411.parikh@gmail.com> CWE ID: CWE-415
0
83,748
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool exist_trim_candidates(struct f2fs_sb_info *sbi, struct cp_control *cpc) { __u64 trim_start = cpc->trim_start; bool has_candidate = false; mutex_lock(&SIT_I(sbi)->sentry_lock); for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++) { if (add_discard_addrs(sbi, cpc, true)) { has_candidate = true; break; } } mutex_unlock(&SIT_I(sbi)->sentry_lock); cpc->trim_start = trim_start; return has_candidate; } Commit Message: f2fs: fix a panic caused by NULL flush_cmd_control Mount fs with option noflush_merge, boot failed for illegal address fcc in function f2fs_issue_flush: if (!test_opt(sbi, FLUSH_MERGE)) { ret = submit_flush_wait(sbi); atomic_inc(&fcc->issued_flush); -> Here, fcc illegal return ret; } Signed-off-by: Yunlei He <heyunlei@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID: CWE-476
0
85,383
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int vb2_ioctl_qbuf(struct file *file, void *priv, struct v4l2_buffer *p) { struct video_device *vdev = video_devdata(file); if (vb2_queue_is_busy(vdev, file)) return -EBUSY; return vb2_qbuf(vdev->queue, p); } Commit Message: [media] videobuf2-v4l2: Verify planes array in buffer dequeueing When a buffer is being dequeued using VIDIOC_DQBUF IOCTL, the exact buffer which will be dequeued is not known until the buffer has been removed from the queue. The number of planes is specific to a buffer, not to the queue. This does lead to the situation where multi-plane buffers may be requested and queued with n planes, but VIDIOC_DQBUF IOCTL may be passed an argument struct with fewer planes. __fill_v4l2_buffer() however uses the number of planes from the dequeued videobuf2 buffer, overwriting kernel memory (the m.planes array allocated in video_usercopy() in v4l2-ioctl.c) if the user provided fewer planes than the dequeued buffer had. Oops! Fixes: b0e0e1f83de3 ("[media] media: videobuf2: Prepare to divide videobuf2") Signed-off-by: Sakari Ailus <sakari.ailus@linux.intel.com> Acked-by: Hans Verkuil <hans.verkuil@cisco.com> Cc: stable@vger.kernel.org # for v4.4 and later Signed-off-by: Mauro Carvalho Chehab <mchehab@osg.samsung.com> CWE ID: CWE-119
0
52,762
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static boolean is_alpha_underscore( const char *cur ) { return (*cur >= 'a' && *cur <= 'z') || (*cur >= 'A' && *cur <= 'Z') || *cur == '_'; } Commit Message: CWE ID: CWE-119
0
9,139
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool IsVoiceInputEnabled() { return !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableVoiceInput); } Commit Message: Move smart deploy to tristate. BUG= Review URL: https://codereview.chromium.org/1149383006 Cr-Commit-Position: refs/heads/master@{#333058} CWE ID: CWE-399
0
123,336
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void muscle_load_dir_acls(sc_file_t* file, mscfs_file_t *file_data) { muscle_load_single_acl(file, SC_AC_OP_SELECT, 0); muscle_load_single_acl(file, SC_AC_OP_LIST_FILES, 0); muscle_load_single_acl(file, SC_AC_OP_LOCK, 0xFFFF); muscle_load_single_acl(file, SC_AC_OP_DELETE, file_data->delete); muscle_load_single_acl(file, SC_AC_OP_CREATE, file_data->write); } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
0
78,760
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg, struct sockcm_cookie *sockc) { u32 tsflags; switch (cmsg->cmsg_type) { case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) return -EPERM; if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) return -EINVAL; sockc->mark = *(u32 *)CMSG_DATA(cmsg); break; case SO_TIMESTAMPING: if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32))) return -EINVAL; tsflags = *(u32 *)CMSG_DATA(cmsg); if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK) return -EINVAL; sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK; sockc->tsflags |= tsflags; break; /* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */ case SCM_RIGHTS: case SCM_CREDENTIALS: break; default: return -EINVAL; } return 0; } Commit Message: net: avoid signed overflows for SO_{SND|RCV}BUFFORCE CAP_NET_ADMIN users should not be allowed to set negative sk_sndbuf or sk_rcvbuf values, as it can lead to various memory corruptions, crashes, OOM... Note that before commit 82981930125a ("net: cleanups in sock_setsockopt()"), the bug was even more serious, since SO_SNDBUF and SO_RCVBUF were vulnerable. This needs to be backported to all known linux kernels. Again, many thanks to syzkaller team for discovering this gem. Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-119
0
47,858
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void perf_prepare_sample(struct perf_event_header *header, struct perf_sample_data *data, struct perf_event *event, struct pt_regs *regs) { u64 sample_type = event->attr.sample_type; header->type = PERF_RECORD_SAMPLE; header->size = sizeof(*header) + event->header_size; header->misc = 0; header->misc |= perf_misc_flags(regs); __perf_event_header__init_id(header, data, event); if (sample_type & PERF_SAMPLE_IP) data->ip = perf_instruction_pointer(regs); if (sample_type & PERF_SAMPLE_CALLCHAIN) { int size = 1; data->callchain = perf_callchain(event, regs); if (data->callchain) size += data->callchain->nr; header->size += size * sizeof(u64); } if (sample_type & PERF_SAMPLE_RAW) { struct perf_raw_record *raw = data->raw; int size; if (raw) { struct perf_raw_frag *frag = &raw->frag; u32 sum = 0; do { sum += frag->size; if (perf_raw_frag_last(frag)) break; frag = frag->next; } while (1); size = round_up(sum + sizeof(u32), sizeof(u64)); raw->size = size - sizeof(u32); frag->pad = raw->size - sum; } else { size = sizeof(u64); } header->size += size; } if (sample_type & PERF_SAMPLE_BRANCH_STACK) { int size = sizeof(u64); /* nr */ if (data->br_stack) { size += data->br_stack->nr * sizeof(struct perf_branch_entry); } header->size += size; } if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER)) perf_sample_regs_user(&data->regs_user, regs, &data->regs_user_copy); if (sample_type & PERF_SAMPLE_REGS_USER) { /* regs dump ABI info */ int size = sizeof(u64); if (data->regs_user.regs) { u64 mask = event->attr.sample_regs_user; size += hweight64(mask) * sizeof(u64); } header->size += size; } if (sample_type & PERF_SAMPLE_STACK_USER) { /* * Either we need PERF_SAMPLE_STACK_USER bit to be allways * processed as the last one or have additional check added * in case new sample type is added, because we could eat * up the rest of the sample size. */ u16 stack_size = event->attr.sample_stack_user; u16 size = sizeof(u64); stack_size = perf_sample_ustack_size(stack_size, header->size, data->regs_user.regs); /* * If there is something to dump, add space for the dump * itself and for the field that tells the dynamic size, * which is how many have been actually dumped. */ if (stack_size) size += sizeof(u64) + stack_size; data->stack_user_size = stack_size; header->size += size; } if (sample_type & PERF_SAMPLE_REGS_INTR) { /* regs dump ABI info */ int size = sizeof(u64); perf_sample_regs_intr(&data->regs_intr, regs); if (data->regs_intr.regs) { u64 mask = event->attr.sample_regs_intr; size += hweight64(mask) * sizeof(u64); } header->size += size; } } Commit Message: perf/core: Fix concurrent sys_perf_event_open() vs. 'move_group' race Di Shen reported a race between two concurrent sys_perf_event_open() calls where both try and move the same pre-existing software group into a hardware context. The problem is exactly that described in commit: f63a8daa5812 ("perf: Fix event->ctx locking") ... where, while we wait for a ctx->mutex acquisition, the event->ctx relation can have changed under us. That very same commit failed to recognise sys_perf_event_context() as an external access vector to the events and thereby didn't apply the established locking rules correctly. So while one sys_perf_event_open() call is stuck waiting on mutex_lock_double(), the other (which owns said locks) moves the group about. So by the time the former sys_perf_event_open() acquires the locks, the context we've acquired is stale (and possibly dead). Apply the established locking rules as per perf_event_ctx_lock_nested() to the mutex_lock_double() for the 'move_group' case. This obviously means we need to validate state after we acquire the locks. Reported-by: Di Shen (Keen Lab) Tested-by: John Dias <joaodias@google.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Cc: Alexander Shishkin <alexander.shishkin@linux.intel.com> Cc: Arnaldo Carvalho de Melo <acme@kernel.org> Cc: Arnaldo Carvalho de Melo <acme@redhat.com> Cc: Jiri Olsa <jolsa@redhat.com> Cc: Kees Cook <keescook@chromium.org> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Min Chong <mchong@google.com> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Stephane Eranian <eranian@google.com> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Vince Weaver <vincent.weaver@maine.edu> Fixes: f63a8daa5812 ("perf: Fix event->ctx locking") Link: http://lkml.kernel.org/r/20170106131444.GZ3174@twins.programming.kicks-ass.net Signed-off-by: Ingo Molnar <mingo@kernel.org> CWE ID: CWE-362
0
68,405
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath) { socks_request_t *socks = conn->socks_request; const or_options_t *options = get_options(); connection_t *base_conn = ENTRY_TO_CONN(conn); time_t now = time(NULL); rewrite_result_t rr; /* First we'll do the rewrite part. Let's see if we get a reasonable * answer. */ memset(&rr, 0, sizeof(rr)); connection_ap_handshake_rewrite(conn,&rr); if (rr.should_close) { /* connection_ap_handshake_rewrite told us to close the connection: * either because it sent back an answer, or because it sent back an * error */ connection_mark_unattached_ap(conn, rr.end_reason); if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK)) return 0; else return -1; } const time_t map_expires = rr.map_expires; const int automap = rr.automap; const addressmap_entry_source_t exit_source = rr.exit_source; /* Now, we parse the address to see if it's an .onion or .exit or * other special address. */ const hostname_type_t addresstype = parse_extended_hostname(socks->address); /* Now see whether the hostname is bogus. This could happen because of an * onion hostname whose format we don't recognize. */ if (addresstype == BAD_HOSTNAME) { control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s", escaped(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL); return -1; } /* If this is a .exit hostname, strip off the .name.exit part, and * see whether we're willing to connect there, and and otherwise handle the * .exit address. * * We'll set chosen_exit_name and/or close the connection as appropriate. */ if (addresstype == EXIT_HOSTNAME) { /* If StrictNodes is not set, then .exit overrides ExcludeNodes but * not ExcludeExitNodes. */ routerset_t *excludeset = options->StrictNodes ? options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes; const node_t *node = NULL; /* If this .exit was added by an AUTOMAP, then it came straight from * a user. Make sure that options->AllowDotExit permits that! */ if (exit_source == ADDRMAPSRC_AUTOMAP && !options->AllowDotExit) { /* Whoops; this one is stale. It must have gotten added earlier, * when AllowDotExit was on. */ log_warn(LD_APP,"Stale automapped address for '%s.exit', with " "AllowDotExit disabled. Refusing.", safe_str_client(socks->address)); control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s", escaped(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL); return -1; } /* Double-check to make sure there are no .exits coming from * impossible/weird sources. */ if (exit_source == ADDRMAPSRC_DNS || (exit_source == ADDRMAPSRC_NONE && !options->AllowDotExit)) { /* It shouldn't be possible to get a .exit address from any of these * sources. */ log_warn(LD_BUG,"Address '%s.exit', with impossible source for the " ".exit part. Refusing.", safe_str_client(socks->address)); control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s", escaped(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL); return -1; } tor_assert(!automap); /* Now, find the character before the .(name) part. * (The ".exit" part got stripped off by "parse_extended_hostname"). * * We're going to put the exit name into conn->chosen_exit_name, and * look up a node correspondingly. */ char *s = strrchr(socks->address,'.'); if (s) { /* The address was of the form "(stuff).(name).exit */ if (s[1] != '\0') { /* Looks like a real .exit one. */ conn->chosen_exit_name = tor_strdup(s+1); node = node_get_by_nickname(conn->chosen_exit_name, 1); if (exit_source == ADDRMAPSRC_TRACKEXIT) { /* We 5 tries before it expires the addressmap */ conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES; } *s = 0; } else { /* Oops, the address was (stuff)..exit. That's not okay. */ log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.", safe_str_client(socks->address)); control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s", escaped(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL); return -1; } } else { /* It looks like they just asked for "foo.exit". That's a special * form that means (foo's address).foo.exit. */ conn->chosen_exit_name = tor_strdup(socks->address); node = node_get_by_nickname(conn->chosen_exit_name, 1); if (node) { *socks->address = 0; node_get_address_string(node, socks->address, sizeof(socks->address)); } } /* Now make sure that the chosen exit exists... */ if (!node) { log_warn(LD_APP, "Unrecognized relay in exit address '%s.exit'. Refusing.", safe_str_client(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL); return -1; } /* ...and make sure that it isn't excluded. */ if (routerset_contains_node(excludeset, node)) { log_warn(LD_APP, "Excluded relay in exit address '%s.exit'. Refusing.", safe_str_client(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL); return -1; } /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and Bar is not listed in it? I say yes, but our revised manpage branch implies no. */ } /* Now, we handle everything that isn't a .onion address. */ if (addresstype != ONION_HOSTNAME) { /* Not a hidden-service request. It's either a hostname or an IP, * possibly with a .exit that we stripped off. We're going to check * if we're allowed to connect/resolve there, and then launch the * appropriate request. */ /* Check for funny characters in the address. */ if (address_is_invalid_destination(socks->address, 1)) { control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s", escaped(socks->address)); log_warn(LD_APP, "Destination '%s' seems to be an invalid hostname. Failing.", safe_str_client(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL); return -1; } #ifdef ENABLE_TOR2WEB_MODE /* If we're running in Tor2webMode, we don't allow anything BUT .onion * addresses. */ if (options->Tor2webMode) { log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname " "or IP address %s because tor2web mode is enabled.", safe_str_client(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY); return -1; } #endif /* socks->address is a non-onion hostname or IP address. * If we can't do any non-onion requests, refuse the connection. * If we have a hostname but can't do DNS, refuse the connection. * If we have an IP address, but we can't use that address family, * refuse the connection. * * If we can do DNS requests, and we can use at least one address family, * then we have to resolve the address first. Then we'll know if it * resolves to a usable address family. */ /* First, check if all non-onion traffic is disabled */ if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) { log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname " "or IP address %s because Port has OnionTrafficOnly set (or " "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).", safe_str_client(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY); return -1; } /* Then check if we have a hostname or IP address, and whether DNS or * the IP address family are permitted. Reject if not. */ tor_addr_t dummy_addr; int socks_family = tor_addr_parse(&dummy_addr, socks->address); /* family will be -1 for a non-onion hostname that's not an IP */ if (socks_family == -1) { if (!conn->entry_cfg.dns_request) { log_warn(LD_APP, "Refusing to connect to hostname %s " "because Port has NoDNSRequest set.", safe_str_client(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY); return -1; } } else if (socks_family == AF_INET) { if (!conn->entry_cfg.ipv4_traffic) { log_warn(LD_APP, "Refusing to connect to IPv4 address %s because " "Port has NoIPv4Traffic set.", safe_str_client(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY); return -1; } } else if (socks_family == AF_INET6) { if (!conn->entry_cfg.ipv6_traffic) { log_warn(LD_APP, "Refusing to connect to IPv6 address %s because " "Port has NoIPv6Traffic set.", safe_str_client(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY); return -1; } } else { tor_assert_nonfatal_unreached_once(); } /* See if this is a hostname lookup that we can answer immediately. * (For example, an attempt to look up the IP address for an IP address.) */ if (socks->command == SOCKS_COMMAND_RESOLVE) { tor_addr_t answer; /* Reply to resolves immediately if we can. */ if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */ /* remember _what_ is supposed to have been resolved. */ strlcpy(socks->address, rr.orig_address, sizeof(socks->address)); connection_ap_handshake_socks_resolved_addr(conn, &answer, -1, map_expires); connection_mark_unattached_ap(conn, END_STREAM_REASON_DONE | END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED); return 0; } tor_assert(!automap); rep_hist_note_used_resolve(now); /* help predict this next time */ } else if (socks->command == SOCKS_COMMAND_CONNECT) { /* Now see if this is a connect request that we can reject immediately */ tor_assert(!automap); /* Don't allow connections to port 0. */ if (socks->port == 0) { log_notice(LD_APP,"Application asked to connect to port 0. Refusing."); connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL); return -1; } /* You can't make connections to internal addresses, by default. * Exceptions are begindir requests (where the address is meaningless), * or cases where you've hand-configured a particular exit, thereby * making the local address meaningful. */ if (options->ClientRejectInternalAddresses && !conn->use_begindir && !conn->chosen_exit_name && !circ) { /* If we reach this point then we don't want to allow internal * addresses. Check if we got one. */ tor_addr_t addr; if (tor_addr_hostname_is_local(socks->address) || (tor_addr_parse(&addr, socks->address) >= 0 && tor_addr_is_internal(&addr, 0))) { /* If this is an explicit private address with no chosen exit node, * then we really don't want to try to connect to it. That's * probably an error. */ if (conn->is_transparent_ap) { #define WARN_INTRVL_LOOP 300 static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP); char *m; if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) { log_warn(LD_NET, "Rejecting request for anonymous connection to private " "address %s on a TransPort or NATDPort. Possible loop " "in your NAT rules?%s", safe_str_client(socks->address), m); tor_free(m); } } else { #define WARN_INTRVL_PRIV 300 static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV); char *m; if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) { log_warn(LD_NET, "Rejecting SOCKS request for anonymous connection to " "private address %s.%s", safe_str_client(socks->address),m); tor_free(m); } } connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR); return -1; } } /* end "if we should check for internal addresses" */ /* Okay. We're still doing a CONNECT, and it wasn't a private * address. Here we do special handling for literal IP addresses, * to see if we should reject this preemptively, and to set up * fields in conn->entry_cfg to tell the exit what AF we want. */ { tor_addr_t addr; /* XXX Duplicate call to tor_addr_parse. */ if (tor_addr_parse(&addr, socks->address) >= 0) { /* If we reach this point, it's an IPv4 or an IPv6 address. */ sa_family_t family = tor_addr_family(&addr); if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) || (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) { /* You can't do an IPv4 address on a v6-only socks listener, * or vice versa. */ log_warn(LD_NET, "Rejecting SOCKS request for an IP address " "family that this listener does not support."); connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY); return -1; } else if (family == AF_INET6 && socks->socks_version == 4) { /* You can't make a socks4 request to an IPv6 address. Socks4 * doesn't support that. */ log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address."); connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY); return -1; } else if (socks->socks_version == 4 && !conn->entry_cfg.ipv4_traffic) { /* You can't do any kind of Socks4 request when IPv4 is forbidden. * * XXX raise this check outside the enclosing block? */ log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with " "no IPv4 traffic supported."); connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY); return -1; } else if (family == AF_INET6) { /* Tell the exit: we won't accept any ipv4 connection to an IPv6 * address. */ conn->entry_cfg.ipv4_traffic = 0; } else if (family == AF_INET) { /* Tell the exit: we won't accept any ipv6 connection to an IPv4 * address. */ conn->entry_cfg.ipv6_traffic = 0; } } } /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */ if (socks->socks_version == 4) conn->entry_cfg.ipv6_traffic = 0; /* Still handling CONNECT. Now, check for exit enclaves. (Which we * don't do on BEGINDIR, or when there is a chosen exit.) * * TODO: Should we remove this? Exit enclaves are nutty and don't * work very well */ if (!conn->use_begindir && !conn->chosen_exit_name && !circ) { /* see if we can find a suitable enclave exit */ const node_t *r = router_find_exact_exit_enclave(socks->address, socks->port); if (r) { log_info(LD_APP, "Redirecting address %s to exit at enclave router %s", safe_str_client(socks->address), node_describe(r)); /* use the hex digest, not nickname, in case there are two routers with this nickname */ conn->chosen_exit_name = tor_strdup(hex_str(r->identity, DIGEST_LEN)); conn->chosen_exit_optional = 1; } } /* Still handling CONNECT: warn or reject if it's using a dangerous * port. */ if (!conn->use_begindir && !conn->chosen_exit_name && !circ) if (consider_plaintext_ports(conn, socks->port) < 0) return -1; /* Remember the port so that we will predict that more requests there will happen in the future. */ if (!conn->use_begindir) { /* help predict this next time */ rep_hist_note_used_port(now, socks->port); } } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) { rep_hist_note_used_resolve(now); /* help predict this next time */ /* no extra processing needed */ } else { /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */ tor_fragile_assert(); } /* Okay. At this point we've set chosen_exit_name if needed, rewritten the * address, and decided not to reject it for any number of reasons. Now * mark the connection as waiting for a circuit, and try to attach it! */ base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT; /* If we were given a circuit to attach to, try to attach. Otherwise, * try to find a good one and attach to that. */ int rv; if (circ) { rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath); } else { /* We'll try to attach it at the next event loop, or whenever * we call connection_ap_attach_pending() */ connection_ap_mark_as_pending_circuit(conn); rv = 0; } /* If the above function returned 0 then we're waiting for a circuit. * if it returned 1, we're attached. Both are okay. But if it returned * -1, there was an error, so make sure the connection is marked, and * return -1. */ if (rv < 0) { if (!base_conn->marked_for_close) connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH); return -1; } return 0; } else { /* If we get here, it's a request for a .onion address! */ tor_assert(!automap); /* If .onion address requests are disabled, refuse the request */ if (!conn->entry_cfg.onion_traffic) { log_warn(LD_APP, "Onion address %s requested from a port with .onion " "disabled", safe_str_client(socks->address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY); return -1; } /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those * for hidden service addresses. */ if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) { /* if it's a resolve request, fail it right now, rather than * building all the circuits and then realizing it won't work. */ log_warn(LD_APP, "Resolve requests to hidden services not allowed. Failing."); connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR, 0,NULL,-1,TIME_MAX); connection_mark_unattached_ap(conn, END_STREAM_REASON_SOCKSPROTOCOL | END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED); return -1; } /* If we were passed a circuit, then we need to fail. .onion addresses * only work when we launch our own circuits for now. */ if (circ) { log_warn(LD_CONTROL, "Attachstream to a circuit is not " "supported for .onion addresses currently. Failing."); connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL); return -1; } /* Look up if we have client authorization configured for this hidden * service. If we do, associate it with the rend_data. */ rend_service_authorization_t *client_auth = rend_client_lookup_service_authorization(socks->address); const uint8_t *cookie = NULL; rend_auth_type_t auth_type = REND_NO_AUTH; if (client_auth) { log_info(LD_REND, "Using previously configured client authorization " "for hidden service request."); auth_type = client_auth->auth_type; cookie = client_auth->descriptor_cookie; } /* Fill in the rend_data field so we can start doing a connection to * a hidden service. */ rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data = rend_data_client_create(socks->address, NULL, (char *) cookie, auth_type); if (rend_data == NULL) { return -1; } const char *onion_address = rend_data_get_address(rend_data); log_info(LD_REND,"Got a hidden service request for ID '%s'", safe_str_client(onion_address)); /* Lookup the given onion address. If invalid, stop right now. * Otherwise, we might have it in the cache or not. */ unsigned int refetch_desc = 0; rend_cache_entry_t *entry = NULL; const int rend_cache_lookup_result = rend_cache_lookup_entry(onion_address, -1, &entry); if (rend_cache_lookup_result < 0) { switch (-rend_cache_lookup_result) { case EINVAL: /* We should already have rejected this address! */ log_warn(LD_BUG,"Invalid service name '%s'", safe_str_client(onion_address)); connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL); return -1; case ENOENT: /* We didn't have this; we should look it up. */ refetch_desc = 1; break; default: log_warn(LD_BUG, "Unknown cache lookup error %d", rend_cache_lookup_result); return -1; } } /* Help predict that we'll want to do hidden service circuits in the * future. We're not sure if it will need a stable circuit yet, but * we know we'll need *something*. */ rep_hist_note_used_internal(now, 0, 1); /* Now we have a descriptor but is it usable or not? If not, refetch. * Also, a fetch could have been requested if the onion address was not * found in the cache previously. */ if (refetch_desc || !rend_client_any_intro_points_usable(entry)) { connection_ap_mark_as_non_pending_circuit(conn); base_conn->state = AP_CONN_STATE_RENDDESC_WAIT; log_info(LD_REND, "Unknown descriptor %s. Fetching.", safe_str_client(onion_address)); rend_client_refetch_v2_renddesc(rend_data); return 0; } /* We have the descriptor! So launch a connection to the HS. */ base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT; log_info(LD_REND, "Descriptor is here. Great."); /* We'll try to attach it at the next event loop, or whenever * we call connection_ap_attach_pending() */ connection_ap_mark_as_pending_circuit(conn); return 0; } return 0; /* unreached but keeps the compiler happy */ } Commit Message: TROVE-2017-004: Fix assertion failure in relay_send_end_cell_from_edge_ This fixes an assertion failure in relay_send_end_cell_from_edge_() when an origin circuit and a cpath_layer = NULL were passed. A service rendezvous circuit could do such a thing when a malformed BEGIN cell is received but shouldn't in the first place because the service needs to send an END cell on the circuit for which it can not do without a cpath_layer. Fixes #22493 Reported-by: Roger Dingledine <arma@torproject.org> Signed-off-by: David Goulet <dgoulet@torproject.org> CWE ID: CWE-617
0
69,894
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: process_mouse(int btn, int x, int y) { int delta_x, delta_y, i; static int press_btn = MOUSE_BTN_RESET, press_x, press_y; TabBuffer *t; int ny = -1; if (nTab > 1 || mouse_action.menu_str) ny = LastTab->y + 1; if (btn == MOUSE_BTN_UP) { switch (press_btn) { case MOUSE_BTN1_DOWN: if (press_y == y && press_x == x) do_mouse_action(press_btn, x, y); else if (ny > 0 && y < ny) { if (press_y < ny) { moveTab(posTab(press_x, press_y), posTab(x, y), (press_y == y) ? (press_x < x) : (press_y < y)); return; } else if (press_x >= Currentbuf->rootX) { Buffer *buf = Currentbuf; int cx = Currentbuf->cursorX, cy = Currentbuf->cursorY; t = posTab(x, y); if (t == NULL) return; if (t == NO_TABBUFFER) t = NULL; /* open new tab */ cursorXY(Currentbuf, press_x - Currentbuf->rootX, press_y - Currentbuf->rootY); if (Currentbuf->cursorY == press_y - Currentbuf->rootY && (Currentbuf->cursorX == press_x - Currentbuf->rootX #ifdef USE_M17N || (WcOption.use_wide && Currentbuf->currentLine != NULL && (CharType(Currentbuf->currentLine-> propBuf[Currentbuf->pos]) == PC_KANJI1) && Currentbuf->cursorX == press_x - Currentbuf->rootX - 1) #endif )) { displayBuffer(Currentbuf, B_NORMAL); followTab(t); } if (buf == Currentbuf) cursorXY(Currentbuf, cx, cy); } return; } else { delta_x = x - press_x; delta_y = y - press_y; if (abs(delta_x) < abs(delta_y) / 3) delta_x = 0; if (abs(delta_y) < abs(delta_x) / 3) delta_y = 0; if (reverse_mouse) { delta_y = -delta_y; delta_x = -delta_x; } if (delta_y > 0) { prec_num = delta_y; ldown1(); } else if (delta_y < 0) { prec_num = -delta_y; lup1(); } if (delta_x > 0) { prec_num = delta_x; col1L(); } else if (delta_x < 0) { prec_num = -delta_x; col1R(); } } break; case MOUSE_BTN2_DOWN: case MOUSE_BTN3_DOWN: if (press_y == y && press_x == x) do_mouse_action(press_btn, x, y); break; case MOUSE_BTN4_DOWN_RXVT: for (i = 0; i < mouse_scroll_line(); i++) ldown1(); break; case MOUSE_BTN5_DOWN_RXVT: for (i = 0; i < mouse_scroll_line(); i++) lup1(); break; } } else if (btn == MOUSE_BTN4_DOWN_XTERM) { for (i = 0; i < mouse_scroll_line(); i++) ldown1(); } else if (btn == MOUSE_BTN5_DOWN_XTERM) { for (i = 0; i < mouse_scroll_line(); i++) lup1(); } if (btn != MOUSE_BTN4_DOWN_RXVT || press_btn == MOUSE_BTN_RESET) { press_btn = btn; press_x = x; press_y = y; } else { press_btn = MOUSE_BTN_RESET; } } Commit Message: Make temporary directory safely when ~/.w3m is unwritable CWE ID: CWE-59
0
84,528
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void get_tcp4_sock(struct sock *sk, struct seq_file *f, int i, int *len) { int timer_active; unsigned long timer_expires; struct tcp_sock *tp = tcp_sk(sk); const struct inet_connection_sock *icsk = inet_csk(sk); struct inet_sock *inet = inet_sk(sk); __be32 dest = inet->inet_daddr; __be32 src = inet->inet_rcv_saddr; __u16 destp = ntohs(inet->inet_dport); __u16 srcp = ntohs(inet->inet_sport); int rx_queue; if (icsk->icsk_pending == ICSK_TIME_RETRANS) { timer_active = 1; timer_expires = icsk->icsk_timeout; } else if (icsk->icsk_pending == ICSK_TIME_PROBE0) { timer_active = 4; timer_expires = icsk->icsk_timeout; } else if (timer_pending(&sk->sk_timer)) { timer_active = 2; timer_expires = sk->sk_timer.expires; } else { timer_active = 0; timer_expires = jiffies; } if (sk->sk_state == TCP_LISTEN) rx_queue = sk->sk_ack_backlog; else /* * because we dont lock socket, we might find a transient negative value */ rx_queue = max_t(int, tp->rcv_nxt - tp->copied_seq, 0); seq_printf(f, "%4d: %08X:%04X %08X:%04X %02X %08X:%08X %02X:%08lX " "%08X %5d %8d %lu %d %pK %lu %lu %u %u %d%n", i, src, srcp, dest, destp, sk->sk_state, tp->write_seq - tp->snd_una, rx_queue, timer_active, jiffies_to_clock_t(timer_expires - jiffies), icsk->icsk_retransmits, sock_i_uid(sk), icsk->icsk_probes_out, sock_i_ino(sk), atomic_read(&sk->sk_refcnt), sk, jiffies_to_clock_t(icsk->icsk_rto), jiffies_to_clock_t(icsk->icsk_ack.ato), (icsk->icsk_ack.quick << 1) | icsk->icsk_ack.pingpong, tp->snd_cwnd, tcp_in_initial_slowstart(tp) ? -1 : tp->snd_ssthresh, len); } 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 <dan@doxpara.com> Tested-by: Willy Tarreau <w@1wt.eu> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
25,193
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void SVGDocumentExtensions::serviceOnAnimationFrame(Document& document, double monotonicAnimationStartTime) { if (!document.svgExtensions()) return; document.accessSVGExtensions().serviceAnimations(monotonicAnimationStartTime); } Commit Message: SVG: Moving animating <svg> to other iframe should not crash. Moving SVGSVGElement with its SMILTimeContainer already started caused crash before this patch. |SVGDocumentExtentions::startAnimations()| calls begin() against all SMILTimeContainers in the document, but the SMILTimeContainer for <svg> moved from other document may be already started. BUG=369860 Review URL: https://codereview.chromium.org/290353002 git-svn-id: svn://svn.chromium.org/blink/trunk@174338 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
0
120,407
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool venc_dev::venc_set_inloop_filter(OMX_VIDEO_AVCLOOPFILTERTYPE loopfilter) { int rc; struct v4l2_control control; control.id=V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_MODE; if (loopfilter == OMX_VIDEO_AVCLoopFilterEnable) { control.value=V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_ENABLED; } else if (loopfilter == OMX_VIDEO_AVCLoopFilterDisable) { control.value=V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED; } else if (loopfilter == OMX_VIDEO_AVCLoopFilterDisableSliceBoundary) { control.value=V4L2_MPEG_VIDEO_H264_LOOP_FILTER_MODE_DISABLED_AT_SLICE_BOUNDARY; } DEBUG_PRINT_LOW("Calling IOCTL set control for id=%d, val=%d", control.id, control.value); rc = ioctl(m_nDriver_fd, VIDIOC_S_CTRL, &control); if (rc) { return false; } DEBUG_PRINT_LOW("Success IOCTL set control for id=%d, value=%d", control.id, control.value); dbkfilter.db_mode=control.value; control.id=V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_ALPHA; control.value=0; DEBUG_PRINT_LOW("Calling IOCTL set control for id=%d, val=%d", control.id, control.value); rc = ioctl(m_nDriver_fd, VIDIOC_S_CTRL, &control); if (rc) { return false; } DEBUG_PRINT_LOW("Success IOCTL set control for id=%d, value=%d", control.id, control.value); control.id=V4L2_CID_MPEG_VIDEO_H264_LOOP_FILTER_BETA; control.value=0; DEBUG_PRINT_LOW("Calling IOCTL set control for id=%d, val=%d", control.id, control.value); rc = ioctl(m_nDriver_fd, VIDIOC_S_CTRL, &control); if (rc) { return false; } DEBUG_PRINT_LOW("Success IOCTL set control for id=%d, value=%d", control.id, control.value); dbkfilter.slicealpha_offset = dbkfilter.slicebeta_offset = 0; return true; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 CWE ID: CWE-200
0
159,292
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int qemu_fdt_setprop_string(void *fdt, const char *node_path, const char *property, const char *string) { int r; r = fdt_setprop_string(fdt, findnode_nofail(fdt, node_path), property, string); if (r < 0) { error_report("%s: Couldn't set %s/%s = %s: %s", __func__, node_path, property, string, fdt_strerror(r)); exit(1); } return r; } Commit Message: CWE ID: CWE-119
0
13,109
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Splash::setOverprintMask(Guint overprintMask, GBool additive) { state->overprintMask = overprintMask; state->overprintAdditive = additive; } Commit Message: CWE ID:
0
4,145
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void stroke_user_creds(private_stroke_socket_t *this, stroke_msg_t *msg, FILE *out) { pop_string(msg, &msg->user_creds.name); pop_string(msg, &msg->user_creds.username); pop_string(msg, &msg->user_creds.password); DBG1(DBG_CFG, "received stroke: user-creds '%s'", msg->user_creds.name); this->config->set_user_credentials(this->config, msg, out); } Commit Message: CWE ID: CWE-787
0
12,227
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int vmx_cpu_uses_apicv(struct kvm_vcpu *vcpu) { return enable_apicv && lapic_in_kernel(vcpu); } Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered It was found that a guest can DoS a host by triggering an infinite stream of "alignment check" (#AC) exceptions. This causes the microcode to enter an infinite loop where the core never receives another interrupt. The host kernel panics pretty quickly due to the effects (CVE-2015-5307). Signed-off-by: Eric Northup <digitaleric@google.com> Cc: stable@vger.kernel.org Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-399
0
42,735
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: HeapVector<VRLayer> VRDisplay::getLayers() { HeapVector<VRLayer> layers; if (is_presenting_) { layers.push_back(layer_); } return layers; } Commit Message: WebVR: fix initial vsync Applications sometimes use window.rAF while not presenting, then switch to vrDisplay.rAF after presentation starts. Depending on the animation loop's timing, this can cause a race condition where presentation has been started but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync being processed after presentation starts so that a queued window.rAF can run and schedule a vrDisplay.rAF. BUG=711789 Review-Url: https://codereview.chromium.org/2848483003 Cr-Commit-Position: refs/heads/master@{#468167} CWE ID:
0
128,375
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void WebLocalFrameImpl::AddMessageToConsole(const WebConsoleMessage& message) { DCHECK(GetFrame()); MessageLevel web_core_message_level = kInfoMessageLevel; switch (message.level) { case WebConsoleMessage::kLevelVerbose: web_core_message_level = kVerboseMessageLevel; break; case WebConsoleMessage::kLevelInfo: web_core_message_level = kInfoMessageLevel; break; case WebConsoleMessage::kLevelWarning: web_core_message_level = kWarningMessageLevel; break; case WebConsoleMessage::kLevelError: web_core_message_level = kErrorMessageLevel; break; } MessageSource message_source = message.nodes.empty() ? kOtherMessageSource : kRecommendationMessageSource; Vector<DOMNodeId> nodes; for (const blink::WebNode& web_node : message.nodes) nodes.push_back(DOMNodeIds::IdForNode(&(*web_node))); ConsoleMessage* console_message = ConsoleMessage::Create( message_source, web_core_message_level, message.text, SourceLocation::Create(message.url, message.line_number, message.column_number, nullptr)); console_message->SetNodes(GetFrame(), std::move(nodes)); GetFrame()->GetDocument()->AddConsoleMessage(console_message); } Commit Message: Do not forward resource timing to parent frame after back-forward navigation LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to send timing info to parent except for the first navigation. This flag is cleared when the first timing is sent to parent, however this does not happen if iframe's first navigation was by back-forward navigation. For such iframes, we shouldn't send timings to parent at all. Bug: 876822 Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5 Reviewed-on: https://chromium-review.googlesource.com/1186215 Reviewed-by: Kinuko Yasuda <kinuko@chromium.org> Commit-Queue: Kunihiko Sakamoto <ksakamoto@chromium.org> Cr-Commit-Position: refs/heads/master@{#585736} CWE ID: CWE-200
0
145,687
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void GLES2DecoderImpl::DoGenerateMipmap(GLenum target) { TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget( &state_, target); if (!texture_ref || !texture_manager()->CanGenerateMipmaps(texture_ref)) { LOCAL_SET_GL_ERROR( GL_INVALID_OPERATION, "glGenerateMipmap", "Can not generate mips"); return; } Texture* tex = texture_ref->texture(); GLint base_level = tex->base_level(); if (target == GL_TEXTURE_CUBE_MAP) { for (int i = 0; i < 6; ++i) { GLenum face = GL_TEXTURE_CUBE_MAP_POSITIVE_X + i; if (!texture_manager()->ClearTextureLevel(this, texture_ref, face, base_level)) { LOCAL_SET_GL_ERROR( GL_OUT_OF_MEMORY, "glGenerateMipmap", "dimensions too big"); return; } } } else { if (!texture_manager()->ClearTextureLevel(this, texture_ref, target, base_level)) { LOCAL_SET_GL_ERROR( GL_OUT_OF_MEMORY, "glGenerateMipmap", "dimensions too big"); return; } } LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER("glGenerateMipmap"); bool texture_zero_level_set = false; GLenum type = 0; GLenum internal_format = 0; GLenum format = 0; if (workarounds().set_zero_level_before_generating_mipmap && target == GL_TEXTURE_2D) { if (base_level != 0 && !tex->GetLevelType(target, 0, &type, &internal_format) && tex->GetLevelType(target, tex->base_level(), &type, &internal_format)) { format = TextureManager::ExtractFormatFromStorageFormat(internal_format); ScopedPixelUnpackState reset_restore(&state_); api()->glTexImage2DFn(target, 0, internal_format, 1, 1, 0, format, type, nullptr); texture_zero_level_set = true; } } bool enable_srgb = 0; if (target == GL_TEXTURE_2D) { tex->GetLevelType(target, tex->base_level(), &type, &internal_format); enable_srgb = GLES2Util::GetColorEncodingFromInternalFormat( internal_format) == GL_SRGB; } if (enable_srgb && feature_info_->feature_flags().desktop_srgb_support) { state_.EnableDisableFramebufferSRGB(enable_srgb); } if (enable_srgb && workarounds().decode_encode_srgb_for_generatemipmap) { if (target == GL_TEXTURE_2D) { if (!InitializeSRGBConverter("generateMipmap")) { return; } srgb_converter_->GenerateMipmap(this, tex, target); } else { api()->glGenerateMipmapEXTFn(target); } } else { api()->glGenerateMipmapEXTFn(target); } if (texture_zero_level_set) { ScopedPixelUnpackState reset_restore(&state_); api()->glTexImage2DFn(target, 0, internal_format, 0, 0, 0, format, type, nullptr); } GLenum error = LOCAL_PEEK_GL_ERROR("glGenerateMipmap"); if (error == GL_NO_ERROR) { texture_manager()->MarkMipmapsGenerated(texture_ref); } } Commit Message: Implement immutable texture base/max level clamping It seems some drivers fail to handle that gracefully, so let's always clamp to be on the safe side. BUG=877874 TEST=test case in the bug, gpu_unittests R=kbr@chromium.org Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: I6d93cb9389ea70525df4604112223604577582a2 Reviewed-on: https://chromium-review.googlesource.com/1194994 Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#587264} CWE ID: CWE-119
0
145,872
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void StorageHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
1
172,774
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void sctp_hash(struct sock *sk) { /* STUB */ } Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS Building sctp may fail with: In function ‘copy_from_user’, inlined from ‘sctp_getsockopt_assoc_stats’ at net/sctp/socket.c:5656:20: arch/x86/include/asm/uaccess_32.h:211:26: error: call to ‘copy_from_user_overflow’ declared with attribute error: copy_from_user() buffer size is not provably correct if built with W=1 due to a missing parameter size validation before the call to copy_from_user. Signed-off-by: Guenter Roeck <linux@roeck-us.net> Acked-by: Vlad Yasevich <vyasevich@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
33,020
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: decode_labeled_vpn_clnp_prefix(netdissect_options *ndo, const u_char *pptr, char *buf, u_int buflen) { uint8_t addr[19]; u_int plen; ND_TCHECK(pptr[0]); plen = pptr[0]; /* get prefix length */ if ((24+64) > plen) return -1; plen-=(24+64); /* adjust prefixlen - labellength - RD len*/ if (152 < plen) return -1; memset(&addr, 0, sizeof(addr)); ND_TCHECK2(pptr[12], (plen + 7) / 8); memcpy(&addr, &pptr[12], (plen + 7) / 8); if (plen % 8) { addr[(plen + 7) / 8 - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } /* the label may get offsetted by 4 bits so lets shift it right */ snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s", bgp_vpn_rd_print(ndo, pptr+4), isonsap_string(ndo, addr,(plen + 7) / 8), plen, EXTRACT_24BITS(pptr+1)>>4, ((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" ); return 12 + (plen + 7) / 8; trunc: return -2; } Commit Message: CVE-2017-13053/BGP: fix VPN route target bounds checks decode_rt_routing_info() didn't check bounds before fetching 4 octets of the origin AS field and could over-read the input buffer, put it right. It also fetched the varying number of octets of the route target field from 4 octets lower than the correct offset, put it right. It also used the same temporary buffer explicitly through as_printf() and implicitly through bgp_vpn_rd_print() so the end result of snprintf() was not what was originally intended. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
0
62,258
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void BrowserEventRouter::TabInsertedAt(WebContents* contents, int index, bool active) { int tab_id = ExtensionTabUtil::GetTabId(contents); if (!GetTabEntry(contents)) { tab_entries_[tab_id] = TabEntry(); TabCreatedAt(contents, index, active); return; } scoped_ptr<ListValue> args(new ListValue()); args->Append(Value::CreateIntegerValue(tab_id)); DictionaryValue* object_args = new DictionaryValue(); object_args->Set(tab_keys::kNewWindowIdKey, Value::CreateIntegerValue( ExtensionTabUtil::GetWindowIdOfTab(contents))); object_args->Set(tab_keys::kNewPositionKey, Value::CreateIntegerValue( index)); args->Append(object_args); Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext()); DispatchEvent(profile, events::kOnTabAttached, args.Pass(), EventRouter::USER_GESTURE_UNKNOWN); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
116,028
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: decompression_init(struct archive_read *a, enum enctype encoding) { struct xar *xar; const char *detail; int r; xar = (struct xar *)(a->format->data); xar->rd_encoding = encoding; switch (encoding) { case NONE: break; case GZIP: if (xar->stream_valid) r = inflateReset(&(xar->stream)); else r = inflateInit(&(xar->stream)); if (r != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Couldn't initialize zlib stream."); return (ARCHIVE_FATAL); } xar->stream_valid = 1; xar->stream.total_in = 0; xar->stream.total_out = 0; break; #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR) case BZIP2: if (xar->bzstream_valid) { BZ2_bzDecompressEnd(&(xar->bzstream)); xar->bzstream_valid = 0; } r = BZ2_bzDecompressInit(&(xar->bzstream), 0, 0); if (r == BZ_MEM_ERROR) r = BZ2_bzDecompressInit(&(xar->bzstream), 0, 1); if (r != BZ_OK) { int err = ARCHIVE_ERRNO_MISC; detail = NULL; switch (r) { case BZ_PARAM_ERROR: detail = "invalid setup parameter"; break; case BZ_MEM_ERROR: err = ENOMEM; detail = "out of memory"; break; case BZ_CONFIG_ERROR: detail = "mis-compiled library"; break; } archive_set_error(&a->archive, err, "Internal error initializing decompressor: %s", detail == NULL ? "??" : detail); xar->bzstream_valid = 0; return (ARCHIVE_FATAL); } xar->bzstream_valid = 1; xar->bzstream.total_in_lo32 = 0; xar->bzstream.total_in_hi32 = 0; xar->bzstream.total_out_lo32 = 0; xar->bzstream.total_out_hi32 = 0; break; #endif #if defined(HAVE_LZMA_H) && defined(HAVE_LIBLZMA) #if LZMA_VERSION_MAJOR >= 5 /* Effectively disable the limiter. */ #define LZMA_MEMLIMIT UINT64_MAX #else /* NOTE: This needs to check memory size which running system has. */ #define LZMA_MEMLIMIT (1U << 30) #endif case XZ: case LZMA: if (xar->lzstream_valid) { lzma_end(&(xar->lzstream)); xar->lzstream_valid = 0; } if (xar->entry_encoding == XZ) r = lzma_stream_decoder(&(xar->lzstream), LZMA_MEMLIMIT,/* memlimit */ LZMA_CONCATENATED); else r = lzma_alone_decoder(&(xar->lzstream), LZMA_MEMLIMIT);/* memlimit */ if (r != LZMA_OK) { switch (r) { case LZMA_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Internal error initializing " "compression library: " "Cannot allocate memory"); break; case LZMA_OPTIONS_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal error initializing " "compression library: " "Invalid or unsupported options"); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal error initializing " "lzma library"); break; } return (ARCHIVE_FATAL); } xar->lzstream_valid = 1; xar->lzstream.total_in = 0; xar->lzstream.total_out = 0; break; #endif /* * Unsupported compression. */ default: #if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR) case BZIP2: #endif #if !defined(HAVE_LZMA_H) || !defined(HAVE_LIBLZMA) case LZMA: case XZ: #endif switch (xar->entry_encoding) { case BZIP2: detail = "bzip2"; break; case LZMA: detail = "lzma"; break; case XZ: detail = "xz"; break; default: detail = "??"; break; } archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "%s compression not supported on this platform", detail); return (ARCHIVE_FAILED); } return (ARCHIVE_OK); } Commit Message: Do something sensible for empty strings to make fuzzers happy. CWE ID: CWE-125
0
61,645
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void arcmsr_shutdown(struct pci_dev *pdev) { struct Scsi_Host *host = pci_get_drvdata(pdev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *)host->hostdata; del_timer_sync(&acb->eternal_timer); arcmsr_disable_outbound_ints(acb); arcmsr_free_irq(pdev, acb); flush_work(&acb->arcmsr_do_message_isr_bh); arcmsr_stop_adapter_bgrb(acb); arcmsr_flush_adapter_cache(acb); } Commit Message: scsi: arcmsr: Buffer overflow in arcmsr_iop_message_xfer() We need to put an upper bound on "user_len" so the memcpy() doesn't overflow. Cc: <stable@vger.kernel.org> Reported-by: Marco Grassi <marco.gra@gmail.com> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Reviewed-by: Tomas Henzl <thenzl@redhat.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com> CWE ID: CWE-119
0
49,831
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void manage_client_side_cookies(struct session *s, struct channel *req) { struct http_txn *txn = &s->txn; int preserve_hdr; int cur_idx, old_idx; char *hdr_beg, *hdr_end, *hdr_next, *del_from; char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next; /* Iterate through the headers, we start with the start line. */ old_idx = 0; hdr_next = req->buf->p + hdr_idx_first_pos(&txn->hdr_idx); while ((cur_idx = txn->hdr_idx.v[old_idx].next)) { struct hdr_idx_elem *cur_hdr; int val; cur_hdr = &txn->hdr_idx.v[cur_idx]; hdr_beg = hdr_next; hdr_end = hdr_beg + cur_hdr->len; hdr_next = hdr_end + cur_hdr->cr + 1; /* We have one full header between hdr_beg and hdr_end, and the * next header starts at hdr_next. We're only interested in * "Cookie:" headers. */ val = http_header_match2(hdr_beg, hdr_end, "Cookie", 6); if (!val) { old_idx = cur_idx; continue; } del_from = NULL; /* nothing to be deleted */ preserve_hdr = 0; /* assume we may kill the whole header */ /* Now look for cookies. Conforming to RFC2109, we have to support * attributes whose name begin with a '$', and associate them with * the right cookie, if we want to delete this cookie. * So there are 3 cases for each cookie read : * 1) it's a special attribute, beginning with a '$' : ignore it. * 2) it's a server id cookie that we *MAY* want to delete : save * some pointers on it (last semi-colon, beginning of cookie...) * 3) it's an application cookie : we *MAY* have to delete a previous * "special" cookie. * At the end of loop, if a "special" cookie remains, we may have to * remove it. If no application cookie persists in the header, we * *MUST* delete it. * * Note: RFC2965 is unclear about the processing of spaces around * the equal sign in the ATTR=VALUE form. A careful inspection of * the RFC explicitly allows spaces before it, and not within the * tokens (attrs or values). An inspection of RFC2109 allows that * too but section 10.1.3 lets one think that spaces may be allowed * after the equal sign too, resulting in some (rare) buggy * implementations trying to do that. So let's do what servers do. * Latest ietf draft forbids spaces all around. Also, earlier RFCs * allowed quoted strings in values, with any possible character * after a backslash, including control chars and delimitors, which * causes parsing to become ambiguous. Browsers also allow spaces * within values even without quotes. * * We have to keep multiple pointers in order to support cookie * removal at the beginning, middle or end of header without * corrupting the header. All of these headers are valid : * * Cookie:NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3\r\n * Cookie:NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3\r\n * Cookie: NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3\r\n * | | | | | | | | | * | | | | | | | | hdr_end <--+ * | | | | | | | +--> next * | | | | | | +----> val_end * | | | | | +-----------> val_beg * | | | | +--------------> equal * | | | +----------------> att_end * | | +---------------------> att_beg * | +--------------------------> prev * +--------------------------------> hdr_beg */ for (prev = hdr_beg + 6; prev < hdr_end; prev = next) { /* Iterate through all cookies on this line */ /* find att_beg */ att_beg = prev + 1; while (att_beg < hdr_end && http_is_spht[(unsigned char)*att_beg]) att_beg++; /* find att_end : this is the first character after the last non * space before the equal. It may be equal to hdr_end. */ equal = att_end = att_beg; while (equal < hdr_end) { if (*equal == '=' || *equal == ',' || *equal == ';') break; if (http_is_spht[(unsigned char)*equal++]) continue; att_end = equal; } /* here, <equal> points to '=', a delimitor or the end. <att_end> * is between <att_beg> and <equal>, both may be identical. */ /* look for end of cookie if there is an equal sign */ if (equal < hdr_end && *equal == '=') { /* look for the beginning of the value */ val_beg = equal + 1; while (val_beg < hdr_end && http_is_spht[(unsigned char)*val_beg]) val_beg++; /* find the end of the value, respecting quotes */ next = find_cookie_value_end(val_beg, hdr_end); /* make val_end point to the first white space or delimitor after the value */ val_end = next; while (val_end > val_beg && http_is_spht[(unsigned char)*(val_end - 1)]) val_end--; } else { val_beg = val_end = next = equal; } /* We have nothing to do with attributes beginning with '$'. However, * they will automatically be removed if a header before them is removed, * since they're supposed to be linked together. */ if (*att_beg == '$') continue; /* Ignore cookies with no equal sign */ if (equal == next) { /* This is not our cookie, so we must preserve it. But if we already * scheduled another cookie for removal, we cannot remove the * complete header, but we can remove the previous block itself. */ preserve_hdr = 1; if (del_from != NULL) { int delta = del_hdr_value(req->buf, &del_from, prev); val_end += delta; next += delta; hdr_end += delta; hdr_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->req, delta); prev = del_from; del_from = NULL; } continue; } /* if there are spaces around the equal sign, we need to * strip them otherwise we'll get trouble for cookie captures, * or even for rewrites. Since this happens extremely rarely, * it does not hurt performance. */ if (unlikely(att_end != equal || val_beg > equal + 1)) { int stripped_before = 0; int stripped_after = 0; if (att_end != equal) { stripped_before = buffer_replace2(req->buf, att_end, equal, NULL, 0); equal += stripped_before; val_beg += stripped_before; } if (val_beg > equal + 1) { stripped_after = buffer_replace2(req->buf, equal + 1, val_beg, NULL, 0); val_beg += stripped_after; stripped_before += stripped_after; } val_end += stripped_before; next += stripped_before; hdr_end += stripped_before; hdr_next += stripped_before; cur_hdr->len += stripped_before; http_msg_move_end(&txn->req, stripped_before); } /* now everything is as on the diagram above */ /* First, let's see if we want to capture this cookie. We check * that we don't already have a client side cookie, because we * can only capture one. Also as an optimisation, we ignore * cookies shorter than the declared name. */ if (s->fe->capture_name != NULL && txn->cli_cookie == NULL && (val_end - att_beg >= s->fe->capture_namelen) && memcmp(att_beg, s->fe->capture_name, s->fe->capture_namelen) == 0) { int log_len = val_end - att_beg; if ((txn->cli_cookie = pool_alloc2(pool2_capture)) == NULL) { Alert("HTTP logging : out of memory.\n"); } else { if (log_len > s->fe->capture_len) log_len = s->fe->capture_len; memcpy(txn->cli_cookie, att_beg, log_len); txn->cli_cookie[log_len] = 0; } } /* Persistence cookies in passive, rewrite or insert mode have the * following form : * * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]] * * For cookies in prefix mode, the form is : * * Cookie: NAME=SRV~VALUE */ if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) && (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) { struct server *srv = s->be->srv; char *delim; /* if we're in cookie prefix mode, we'll search the delimitor so that we * have the server ID between val_beg and delim, and the original cookie between * delim+1 and val_end. Otherwise, delim==val_end : * * Cookie: NAME=SRV; # in all but prefix modes * Cookie: NAME=SRV~OPAQUE ; # in prefix mode * | || || | |+-> next * | || || | +--> val_end * | || || +---------> delim * | || |+------------> val_beg * | || +-------------> att_end = equal * | |+-----------------> att_beg * | +------------------> prev * +-------------------------> hdr_beg */ if (s->be->ck_opts & PR_CK_PFX) { for (delim = val_beg; delim < val_end; delim++) if (*delim == COOKIE_DELIM) break; } else { char *vbar1; delim = val_end; /* Now check if the cookie contains a date field, which would * appear after a vertical bar ('|') just after the server name * and before the delimiter. */ vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg); if (vbar1) { /* OK, so left of the bar is the server's cookie and * right is the last seen date. It is a base64 encoded * 30-bit value representing the UNIX date since the * epoch in 4-second quantities. */ int val; delim = vbar1++; if (val_end - vbar1 >= 5) { val = b64tos30(vbar1); if (val > 0) txn->cookie_last_date = val << 2; } /* look for a second vertical bar */ vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1); if (vbar1 && (val_end - vbar1 > 5)) { val = b64tos30(vbar1 + 1); if (val > 0) txn->cookie_first_date = val << 2; } } } /* if the cookie has an expiration date and the proxy wants to check * it, then we do that now. We first check if the cookie is too old, * then only if it has expired. We detect strict overflow because the * time resolution here is not great (4 seconds). Cookies with dates * in the future are ignored if their offset is beyond one day. This * allows an admin to fix timezone issues without expiring everyone * and at the same time avoids keeping unwanted side effects for too * long. */ if (txn->cookie_first_date && s->be->cookie_maxlife && (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) || ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) { txn->flags &= ~TX_CK_MASK; txn->flags |= TX_CK_OLD; delim = val_beg; // let's pretend we have not found the cookie txn->cookie_first_date = 0; txn->cookie_last_date = 0; } else if (txn->cookie_last_date && s->be->cookie_maxidle && (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) || ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) { txn->flags &= ~TX_CK_MASK; txn->flags |= TX_CK_EXPIRED; delim = val_beg; // let's pretend we have not found the cookie txn->cookie_first_date = 0; txn->cookie_last_date = 0; } /* Here, we'll look for the first running server which supports the cookie. * This allows to share a same cookie between several servers, for example * to dedicate backup servers to specific servers only. * However, to prevent clients from sticking to cookie-less backup server * when they have incidentely learned an empty cookie, we simply ignore * empty cookies and mark them as invalid. * The same behaviour is applied when persistence must be ignored. */ if ((delim == val_beg) || (s->flags & (SN_IGNORE_PRST | SN_ASSIGNED))) srv = NULL; while (srv) { if (srv->cookie && (srv->cklen == delim - val_beg) && !memcmp(val_beg, srv->cookie, delim - val_beg)) { if ((srv->state != SRV_ST_STOPPED) || (s->be->options & PR_O_PERSIST) || (s->flags & SN_FORCE_PRST)) { /* we found the server and we can use it */ txn->flags &= ~TX_CK_MASK; txn->flags |= (srv->state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN; s->flags |= SN_DIRECT | SN_ASSIGNED; s->target = &srv->obj_type; break; } else { /* we found a server, but it's down, * mark it as such and go on in case * another one is available. */ txn->flags &= ~TX_CK_MASK; txn->flags |= TX_CK_DOWN; } } srv = srv->next; } if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) { /* no server matched this cookie or we deliberately skipped it */ txn->flags &= ~TX_CK_MASK; if ((s->flags & (SN_IGNORE_PRST | SN_ASSIGNED))) txn->flags |= TX_CK_UNUSED; else txn->flags |= TX_CK_INVALID; } /* depending on the cookie mode, we may have to either : * - delete the complete cookie if we're in insert+indirect mode, so that * the server never sees it ; * - remove the server id from the cookie value, and tag the cookie as an * application cookie so that it does not get accidentely removed later, * if we're in cookie prefix mode */ if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) { int delta; /* negative */ delta = buffer_replace2(req->buf, val_beg, delim + 1, NULL, 0); val_end += delta; next += delta; hdr_end += delta; hdr_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->req, delta); del_from = NULL; preserve_hdr = 1; /* we want to keep this cookie */ } else if (del_from == NULL && (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) { del_from = prev; } } else { /* This is not our cookie, so we must preserve it. But if we already * scheduled another cookie for removal, we cannot remove the * complete header, but we can remove the previous block itself. */ preserve_hdr = 1; if (del_from != NULL) { int delta = del_hdr_value(req->buf, &del_from, prev); if (att_beg >= del_from) att_beg += delta; if (att_end >= del_from) att_end += delta; val_beg += delta; val_end += delta; next += delta; hdr_end += delta; hdr_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->req, delta); prev = del_from; del_from = NULL; } } /* Look for the appsession cookie unless persistence must be ignored */ if (!(s->flags & SN_IGNORE_PRST) && (s->be->appsession_name != NULL)) { int cmp_len, value_len; char *value_begin; if (s->be->options2 & PR_O2_AS_PFX) { cmp_len = MIN(val_end - att_beg, s->be->appsession_name_len); value_begin = att_beg + s->be->appsession_name_len; value_len = val_end - att_beg - s->be->appsession_name_len; } else { cmp_len = att_end - att_beg; value_begin = val_beg; value_len = val_end - val_beg; } /* let's see if the cookie is our appcookie */ if (cmp_len == s->be->appsession_name_len && memcmp(att_beg, s->be->appsession_name, cmp_len) == 0) { manage_client_side_appsession(s, value_begin, value_len); } } /* continue with next cookie on this header line */ att_beg = next; } /* for each cookie */ /* There are no more cookies on this line. * We may still have one (or several) marked for deletion at the * end of the line. We must do this now in two ways : * - if some cookies must be preserved, we only delete from the * mark to the end of line ; * - if nothing needs to be preserved, simply delete the whole header */ if (del_from) { int delta; if (preserve_hdr) { delta = del_hdr_value(req->buf, &del_from, hdr_end); hdr_end = del_from; cur_hdr->len += delta; } else { delta = buffer_replace2(req->buf, hdr_beg, hdr_next, NULL, 0); /* FIXME: this should be a separate function */ txn->hdr_idx.v[old_idx].next = cur_hdr->next; txn->hdr_idx.used--; cur_hdr->len = 0; cur_idx = old_idx; } hdr_next += delta; http_msg_move_end(&txn->req, delta); } /* check next header */ old_idx = cur_idx; } } Commit Message: CWE ID: CWE-189
0
9,826
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: GpuChannelHost* BrowserGpuChannelHostFactory::EstablishGpuChannelSync( CauseForGpuLaunch cause_for_gpu_launch) { if (gpu_channel_.get()) { if (gpu_channel_->state() == GpuChannelHost::kLost) gpu_channel_ = NULL; else return gpu_channel_.get(); } GpuDataManagerImpl::GetInstance(); EstablishRequest request; GetIOLoopProxy()->PostTask( FROM_HERE, base::Bind( &BrowserGpuChannelHostFactory::EstablishGpuChannelOnIO, base::Unretained(this), &request, cause_for_gpu_launch)); request.event.Wait(); if (request.channel_handle.name.empty() || request.gpu_process_handle == base::kNullProcessHandle) return NULL; base::ProcessHandle browser_process_for_gpu; #if defined(OS_WIN) DuplicateHandle(base::GetCurrentProcessHandle(), base::GetCurrentProcessHandle(), request.gpu_process_handle, &browser_process_for_gpu, PROCESS_DUP_HANDLE, FALSE, 0); #else browser_process_for_gpu = base::GetCurrentProcessHandle(); #endif gpu_channel_ = new GpuChannelHost(this, gpu_host_id_, gpu_client_id_); gpu_channel_->set_gpu_info(request.gpu_info); content::GetContentClient()->SetGpuInfo(request.gpu_info); gpu_channel_->Connect(request.channel_handle, browser_process_for_gpu); return gpu_channel_.get(); } 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:
1
170,917
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: JSValue toJS(ExecState* exec, JSDOMGlobalObject* globalObject, DataView* object) { return wrap<JSDataView>(exec, globalObject, object); } 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
0
101,028
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: status_t Parcel::readChar(char16_t *pArg) const { int32_t tmp; status_t ret = readInt32(&tmp); *pArg = char16_t(tmp); return ret; } Commit Message: Add bound checks to utf16_to_utf8 Bug: 29250543 Change-Id: I518e7b2fe10aaa3f1c1987586a09b1110aff7e1a (cherry picked from commit 7e93b2ddcb49b5365fbe1dab134ffb38e6f1c719) CWE ID: CWE-119
0
163,569
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int proc_resetep(struct usb_dev_state *ps, void __user *arg) { unsigned int ep; int ret; if (get_user(ep, (unsigned int __user *)arg)) return -EFAULT; ret = findintfep(ps->dev, ep); if (ret < 0) return ret; ret = checkintf(ps, ret); if (ret) return ret; check_reset_of_active_ep(ps->dev, ep, "RESETEP"); usb_reset_endpoint(ps->dev, ep); return 0; } 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 <kjlu@gatech.edu> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-200
0
53,238
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void CSoundFile::SetTempo(TEMPO param, bool setFromUI) { const CModSpecifications &specs = GetModSpecifications(); const TEMPO minTempo = (GetType() == MOD_TYPE_MDL) ? TEMPO(1, 0) : TEMPO(32, 0); if(setFromUI) { m_PlayState.m_nMusicTempo = Clamp(param, specs.GetTempoMin(), specs.GetTempoMax()); } else if(param >= minTempo && m_SongFlags[SONG_FIRSTTICK] == !m_playBehaviour[kMODTempoOnSecondTick]) { m_PlayState.m_nMusicTempo = std::min(param, specs.GetTempoMax()); } else if(param < minTempo && !m_SongFlags[SONG_FIRSTTICK]) { TEMPO tempDiff(param.GetInt() & 0x0F, 0); if((param.GetInt() & 0xF0) == 0x10) m_PlayState.m_nMusicTempo += tempDiff; else m_PlayState.m_nMusicTempo -= tempDiff; TEMPO tempoMin = specs.GetTempoMin(), tempoMax = specs.GetTempoMax(); if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode { tempoMax.Set(255); } Limit(m_PlayState.m_nMusicTempo, tempoMin, tempoMax); } } Commit Message: [Fix] Possible out-of-bounds read when computing length of some IT files with pattern loops (OpenMPT: formats that are converted to IT, libopenmpt: IT/ITP/MO3), caught with afl-fuzz. git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@10027 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-125
0
83,339
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int orinoco_ioctl_getpreamble(struct net_device *dev, struct iw_request_info *info, void *wrqu, char *extra) { struct orinoco_private *priv = ndev_priv(dev); int *val = (int *) extra; if (!priv->has_preamble) return -EOPNOTSUPP; *val = priv->preamble; return 0; } Commit Message: orinoco: fix TKIP countermeasure behaviour Enable the port when disabling countermeasures, and disable it on enabling countermeasures. This bug causes the response of the system to certain attacks to be ineffective. It also prevents wpa_supplicant from getting scan results, as wpa_supplicant disables countermeasures on startup - preventing the hardware from scanning. wpa_supplicant works with ap_mode=2 despite this bug because the commit handler re-enables the port. The log tends to look like: State: DISCONNECTED -> SCANNING Starting AP scan for wildcard SSID Scan requested (ret=0) - scan timeout 5 seconds EAPOL: disable timer tick EAPOL: Supplicant port status: Unauthorized Scan timeout - try to get results Failed to get scan results Failed to get scan results - try scanning again Setting scan request: 1 sec 0 usec Starting AP scan for wildcard SSID Scan requested (ret=-1) - scan timeout 5 seconds Failed to initiate AP scan. Reported by: Giacomo Comes <comes@naic.edu> Signed-off by: David Kilroy <kilroyd@googlemail.com> Cc: stable@kernel.org Signed-off-by: John W. Linville <linville@tuxdriver.com> CWE ID:
0
27,927
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: BlobDataHandle::BlobDataHandle(PassOwnPtr<BlobData> data, long long size) { UNUSED_PARAM(size); m_internalURL = BlobURL::createInternalURL(); ThreadableBlobRegistry::registerBlobURL(m_internalURL, data); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
1
170,694
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void OneClickSigninSyncStarter::OnPolicyFetchComplete(bool success) { DLOG_IF(ERROR, !success) << "Error fetching policy for user"; DVLOG_IF(1, success) << "Policy fetch successful - completing signin"; SigninManagerFactory::GetForProfile(profile_)->CompletePendingSignin(); } Commit Message: Display confirmation dialog for untrusted signins BUG=252062 Review URL: https://chromiumcodereview.appspot.com/17482002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
0
112,619
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static bt_status_t btif_in_get_remote_device_properties(bt_bdaddr_t *bd_addr) { bt_property_t remote_properties[8]; uint32_t num_props = 0; bt_bdname_t name, alias; uint32_t cod, devtype; bt_uuid_t remote_uuids[BT_MAX_NUM_UUIDS]; memset(remote_properties, 0, sizeof(remote_properties)); BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_BDNAME, sizeof(name), &name); btif_storage_get_remote_device_property(bd_addr, &remote_properties[num_props]); num_props++; BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_REMOTE_FRIENDLY_NAME, sizeof(alias), &alias); btif_storage_get_remote_device_property(bd_addr, &remote_properties[num_props]); num_props++; BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_CLASS_OF_DEVICE, sizeof(cod), &cod); btif_storage_get_remote_device_property(bd_addr, &remote_properties[num_props]); num_props++; BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_TYPE_OF_DEVICE, sizeof(devtype), &devtype); btif_storage_get_remote_device_property(bd_addr, &remote_properties[num_props]); num_props++; BTIF_STORAGE_FILL_PROPERTY(&remote_properties[num_props], BT_PROPERTY_UUIDS, sizeof(remote_uuids), remote_uuids); btif_storage_get_remote_device_property(bd_addr, &remote_properties[num_props]); num_props++; HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb, BT_STATUS_SUCCESS, bd_addr, num_props, remote_properties); return BT_STATUS_SUCCESS; } 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
0
158,545
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: isoent_setup_directory_location(struct iso9660 *iso9660, int location, struct vdd *vdd) { struct isoent *np; int depth; vdd->total_dir_block = 0; depth = 0; np = vdd->rootent; do { int block; np->dir_block = calculate_directory_descriptors( iso9660, vdd, np, depth); vdd->total_dir_block += np->dir_block; np->dir_location = location; location += np->dir_block; block = extra_setup_location(np, location); vdd->total_dir_block += block; location += block; if (np->subdirs.first != NULL && depth + 1 < vdd->max_depth) { /* Enter to sub directories. */ np = np->subdirs.first; depth++; continue; } while (np != np->parent) { if (np->drnext == NULL) { /* Return to the parent directory. */ np = np->parent; depth--; } else { np = np->drnext; break; } } } while (np != np->parent); } Commit Message: Issue 711: Be more careful about verifying filename lengths when writing ISO9660 archives * Don't cast size_t to int, since this can lead to overflow on machines where sizeof(int) < sizeof(size_t) * Check a + b > limit by writing it as a > limit || b > limit || a + b > limit to avoid problems when a + b wraps around. CWE ID: CWE-190
0
50,843
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int asn1_decode_path(sc_context_t *ctx, const u8 *in, size_t len, sc_path_t *path, int depth) { int idx, count, r; struct sc_asn1_entry asn1_path_ext[3], asn1_path[5]; unsigned char path_value[SC_MAX_PATH_SIZE], aid_value[SC_MAX_AID_SIZE]; size_t path_len = sizeof(path_value), aid_len = sizeof(aid_value); memset(path, 0, sizeof(struct sc_path)); sc_copy_asn1_entry(c_asn1_path_ext, asn1_path_ext); sc_copy_asn1_entry(c_asn1_path, asn1_path); sc_format_asn1_entry(asn1_path_ext + 0, aid_value, &aid_len, 0); sc_format_asn1_entry(asn1_path_ext + 1, path_value, &path_len, 0); sc_format_asn1_entry(asn1_path + 0, path_value, &path_len, 0); sc_format_asn1_entry(asn1_path + 1, &idx, NULL, 0); sc_format_asn1_entry(asn1_path + 2, &count, NULL, 0); sc_format_asn1_entry(asn1_path + 3, asn1_path_ext, NULL, 0); r = asn1_decode(ctx, asn1_path, in, len, NULL, NULL, 0, depth + 1); if (r) return r; if (asn1_path[3].flags & SC_ASN1_PRESENT) { /* extended path present: set 'path' and 'aid' */ memcpy(path->aid.value, aid_value, aid_len); path->aid.len = aid_len; memcpy(path->value, path_value, path_len); path->len = path_len; } else if (asn1_path[0].flags & SC_ASN1_PRESENT) { /* path present: set 'path' */ memcpy(path->value, path_value, path_len); path->len = path_len; } else { /* failed if both 'path' and 'pathExtended' are absent */ return SC_ERROR_ASN1_OBJECT_NOT_FOUND; } if (path->len == 2) path->type = SC_PATH_TYPE_FILE_ID; else if (path->aid.len && path->len > 2) path->type = SC_PATH_TYPE_FROM_CURRENT; else path->type = SC_PATH_TYPE_PATH; if ((asn1_path[1].flags & SC_ASN1_PRESENT) && (asn1_path[2].flags & SC_ASN1_PRESENT)) { path->index = idx; path->count = count; } else { path->index = 0; path->count = -1; } return SC_SUCCESS; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
0
78,103
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int megasas_dcmd_ld_get_list(MegasasState *s, MegasasCmd *cmd) { struct mfi_ld_list info; size_t dcmd_size = sizeof(info), resid; uint32_t num_ld_disks = 0, max_ld_disks; uint64_t ld_size; BusChild *kid; memset(&info, 0, dcmd_size); if (cmd->iov_size > dcmd_size) { trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, dcmd_size); return MFI_STAT_INVALID_PARAMETER; } max_ld_disks = (cmd->iov_size - 8) / 16; if (megasas_is_jbod(s)) { max_ld_disks = 0; } if (max_ld_disks > MFI_MAX_LD) { max_ld_disks = MFI_MAX_LD; } QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = SCSI_DEVICE(kid->child); if (num_ld_disks >= max_ld_disks) { break; } /* Logical device size is in blocks */ blk_get_geometry(sdev->conf.blk, &ld_size); info.ld_list[num_ld_disks].ld.v.target_id = sdev->id; info.ld_list[num_ld_disks].state = MFI_LD_STATE_OPTIMAL; info.ld_list[num_ld_disks].size = cpu_to_le64(ld_size); num_ld_disks++; } info.ld_count = cpu_to_le32(num_ld_disks); trace_megasas_dcmd_ld_get_list(cmd->index, num_ld_disks, max_ld_disks); resid = dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg); cmd->iov_size = dcmd_size - resid; return MFI_STAT_OK; } Commit Message: CWE ID: CWE-200
0
10,427
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int sched_feat_show(struct seq_file *m, void *v) { int i; for (i = 0; sched_feat_names[i]; i++) { if (!(sysctl_sched_features & (1UL << i))) seq_puts(m, "NO_"); seq_printf(m, "%s ", sched_feat_names[i]); } seq_puts(m, "\n"); return 0; } Commit Message: Sched: fix skip_clock_update optimization idle_balance() drops/retakes rq->lock, leaving the previous task vulnerable to set_tsk_need_resched(). Clear it after we return from balancing instead, and in setup_thread_stack() as well, so no successfully descheduled or never scheduled task has it set. Need resched confused the skip_clock_update logic, which assumes that the next call to update_rq_clock() will come nearly immediately after being set. Make the optimization robust against the waking a sleeper before it sucessfully deschedules case by checking that the current task has not been dequeued before setting the flag, since it is that useless clock update we're trying to save, and clear unconditionally in schedule() proper instead of conditionally in put_prev_task(). Signed-off-by: Mike Galbraith <efault@gmx.de> Reported-by: Bjoern B. Brandenburg <bbb.lst@gmail.com> Tested-by: Yong Zhang <yong.zhang0@gmail.com> Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: stable@kernel.org LKML-Reference: <1291802742.1417.9.camel@marge.simson.net> Signed-off-by: Ingo Molnar <mingo@elte.hu> CWE ID:
0
22,542
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void Instance::DocumentSizeUpdated(const pp::Size& size) { document_size_ = size; OnGeometryChanged(zoom_, device_scale_); } Commit Message: Let PDFium handle event when there is not yet a visible page. Speculative fix for 415307. CF will confirm. The stack trace for that bug indicates an attempt to index by -1, which is consistent with no visible page. BUG=415307 Review URL: https://codereview.chromium.org/560133004 Cr-Commit-Position: refs/heads/master@{#295421} CWE ID: CWE-119
0
120,140
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void tcp_v6_send_reset(struct sock *sk, struct sk_buff *skb) { struct tcphdr *th = tcp_hdr(skb); u32 seq = 0, ack_seq = 0; struct tcp_md5sig_key *key = NULL; if (th->rst) return; if (!ipv6_unicast_destination(skb)) return; #ifdef CONFIG_TCP_MD5SIG if (sk) key = tcp_v6_md5_do_lookup(sk, &ipv6_hdr(skb)->daddr); #endif if (th->ack) seq = ntohl(th->ack_seq); else ack_seq = ntohl(th->seq) + th->syn + th->fin + skb->len - (th->doff << 2); tcp_v6_send_response(skb, seq, ack_seq, 0, 0, key, 1); } 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 <eric.dumazet@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-362
0
19,155
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int apparmor_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot, unsigned long prot) { return common_mmap(OP_FMPROT, vma->vm_file, prot, !(vma->vm_flags & VM_SHARED) ? MAP_PRIVATE : 0); } Commit Message: AppArmor: fix oops in apparmor_setprocattr When invalid parameters are passed to apparmor_setprocattr a NULL deref oops occurs when it tries to record an audit message. This is because it is passing NULL for the profile parameter for aa_audit. But aa_audit now requires that the profile passed is not NULL. Fix this by passing the current profile on the task that is trying to setprocattr. Signed-off-by: Kees Cook <kees@ubuntu.com> Signed-off-by: John Johansen <john.johansen@canonical.com> Cc: stable@kernel.org Signed-off-by: James Morris <jmorris@namei.org> CWE ID: CWE-20
0
34,790
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) { asn1_write_enumerated(data, result->resultcode); asn1_write_OctetString(data, result->dn, (result->dn) ? strlen(result->dn) : 0); asn1_write_OctetString(data, result->errormessage, (result->errormessage) ? strlen(result->errormessage) : 0); if (result->referral) { asn1_push_tag(data, ASN1_CONTEXT(3)); asn1_write_OctetString(data, result->referral, strlen(result->referral)); asn1_pop_tag(data); } } Commit Message: CWE ID: CWE-399
1
164,593
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void gdImageAALine (gdImagePtr im, int x1, int y1, int x2, int y2, int col) { /* keep them as 32bits */ long x, y, inc, frac; long dx, dy,tmp; int w, wid, wstart; int thick = im->thick; if (!im->trueColor) { /* TBB: don't crash when the image is of the wrong type */ gdImageLine(im, x1, y1, x2, y2, col); return; } /* TBB: use the clipping rectangle */ if (clip_1d (&x1, &y1, &x2, &y2, im->cx1, im->cx2) == 0) return; if (clip_1d (&y1, &x1, &y2, &x2, im->cy1, im->cy2) == 0) return; dx = x2 - x1; dy = y2 - y1; if (dx == 0 && dy == 0) { /* TBB: allow setting points */ gdImageSetAAPixelColor(im, x1, y1, col, 0xFF); return; } else { double ag; /* Cast the long to an int to avoid compiler warnings about truncation. * This isn't a problem as computed dy/dx values came from ints above. */ ag = fabs(abs((int)dy) < abs((int)dx) ? cos(atan2(dy, dx)) : sin(atan2(dy, dx))); if (ag != 0) { wid = thick / ag; } else { wid = 1; } if (wid == 0) { wid = 1; } } /* Axis aligned lines */ if (dx == 0) { gdImageVLine(im, x1, y1, y2, col); return; } else if (dy == 0) { gdImageHLine(im, y1, x1, x2, col); return; } if (abs((int)dx) > abs((int)dy)) { if (dx < 0) { tmp = x1; x1 = x2; x2 = tmp; tmp = y1; y1 = y2; y2 = tmp; dx = x2 - x1; dy = y2 - y1; } y = y1; inc = (dy * 65536) / dx; frac = 0; /* TBB: set the last pixel for consistency (<=) */ for (x = x1 ; x <= x2 ; x++) { wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetAAPixelColor(im, x , w , col , (frac >> 8) & 0xFF); gdImageSetAAPixelColor(im, x , w + 1 , col, (~frac >> 8) & 0xFF); } frac += inc; if (frac >= 65536) { frac -= 65536; y++; } else if (frac < 0) { frac += 65536; y--; } } } else { if (dy < 0) { tmp = x1; x1 = x2; x2 = tmp; tmp = y1; y1 = y2; y2 = tmp; dx = x2 - x1; dy = y2 - y1; } x = x1; inc = (dx * 65536) / dy; frac = 0; /* TBB: set the last pixel for consistency (<=) */ for (y = y1 ; y <= y2 ; y++) { wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetAAPixelColor(im, w , y , col, (frac >> 8) & 0xFF); gdImageSetAAPixelColor(im, w + 1, y, col, (~frac >> 8) & 0xFF); } frac += inc; if (frac >= 65536) { frac -= 65536; x++; } else if (frac < 0) { frac += 65536; x--; } } } } Commit Message: fix #215 gdImageFillToBorder stack-overflow when invalid color is used CWE ID: CWE-119
0
96,150
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void _ht_node_free_kv(HtKv *kv) { free (kv->key); free (kv); } Commit Message: Fix #7698 - UAF in r_config_set when loading a dex CWE ID: CWE-416
0
64,465
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static const char *cache_id(const char *id) { static char clean[SHORT_STRING]; mutt_str_strfcpy(clean, id, sizeof(clean)); mutt_file_sanitize_filename(clean, true); return clean; } Commit Message: Ensure UID in fetch_uidl CWE ID: CWE-824
0
79,624
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void InputType::SetValueAsDecimal(const Decimal& new_value, TextFieldEventBehavior event_behavior, ExceptionState&) const { GetElement().setValue(Serialize(new_value), event_behavior); } 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 <mblsha@yandex-team.ru> Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID:
0
126,238
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool ChromeClientImpl::canRunBeforeUnloadConfirmPanel() { return !!m_webView->client(); } Commit Message: Delete apparently unused geolocation declarations and include. BUG=336263 Review URL: https://codereview.chromium.org/139743014 git-svn-id: svn://svn.chromium.org/blink/trunk@165601 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
0
118,588
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: sctp_disposition_t sctp_sf_do_prm_asconf(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk)); sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(chunk)); return SCTP_DISPOSITION_CONSUME; } Commit Message: sctp: Use correct sideffect command in duplicate cookie handling When SCTP is done processing a duplicate cookie chunk, it tries to delete a newly created association. For that, it has to set the right association for the side-effect processing to work. However, when it uses the SCTP_CMD_NEW_ASOC command, that performs more work then really needed (like hashing the associationa and assigning it an id) and there is no point to do that only to delete the association as a next step. In fact, it also creates an impossible condition where an association may be found by the getsockopt() call, and that association is empty. This causes a crash in some sctp getsockopts. The solution is rather simple. We simply use SCTP_CMD_SET_ASOC command that doesn't have all the overhead and does exactly what we need. Reported-by: Karl Heiss <kheiss@gmail.com> Tested-by: Karl Heiss <kheiss@gmail.com> CC: Neil Horman <nhorman@tuxdriver.com> Signed-off-by: Vlad Yasevich <vyasevich@gmail.com> Acked-by: Neil Horman <nhorman@tuxdriver.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
0
31,608
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void OmniboxViewViews::OnPaste() { const base::string16 text(GetClipboardText()); if (!text.empty()) { OnBeforePossibleChange(); model()->OnPaste(); state_before_change_.text.clear(); InsertOrReplaceText(text); OnAfterPossibleChange(true); } } Commit Message: Strip JavaScript schemas on Linux text drop When dropping text onto the Omnibox, any leading JavaScript schemes should be stripped to avoid a "self-XSS" attack. This stripping already occurs in all cases except when plaintext is dropped on Linux. This CL corrects that oversight. Bug: 768910 Change-Id: I43af24ace4a13cf61d15a32eb9382dcdd498a062 Reviewed-on: https://chromium-review.googlesource.com/685638 Reviewed-by: Justin Donnelly <jdonnelly@chromium.org> Commit-Queue: Eric Lawrence <elawrence@chromium.org> Cr-Commit-Position: refs/heads/master@{#504695} CWE ID: CWE-79
0
150,640
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: GuestViewBase* ExtensionViewGuest::Create(WebContents* owner_web_contents) { return new ExtensionViewGuest(owner_web_contents); } Commit Message: Make extensions use a correct same-origin check. GURL::GetOrigin does not do the right thing for all types of URLs. BUG=573317 Review URL: https://codereview.chromium.org/1658913002 Cr-Commit-Position: refs/heads/master@{#373381} CWE ID: CWE-284
0
132,990
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: PlatformFontSkia::~PlatformFontSkia() {} Commit Message: Take default system font size from PlatformFont The default font returned by Skia should take the initial size from the default value kDefaultBaseFontSize specified in PlatformFont. R=robliao@chromium.org, asvitkine@chromium.org CC=benck@google.com Bug: 944227 Change-Id: I6b230b80c349abbe5968edb3cebdd6e89db4c4a6 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1642738 Reviewed-by: Robert Liao <robliao@chromium.org> Reviewed-by: Alexei Svitkine <asvitkine@chromium.org> Commit-Queue: Etienne Bergeron <etienneb@chromium.org> Cr-Commit-Position: refs/heads/master@{#666299} CWE ID: CWE-862
0
155,363
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void config__init_reload(struct mosquitto_db *db, struct mosquitto__config *config) { int i; /* Set defaults */ for(i=0; i<config->listener_count; i++){ mosquitto__free(config->listeners[i].security_options.acl_file); config->listeners[i].security_options.acl_file = NULL; mosquitto__free(config->listeners[i].security_options.password_file); config->listeners[i].security_options.password_file = NULL; mosquitto__free(config->listeners[i].security_options.psk_file); config->listeners[i].security_options.psk_file = NULL; config->listeners[i].security_options.allow_anonymous = -1; config->listeners[i].security_options.allow_zero_length_clientid = true; config->listeners[i].security_options.auto_id_prefix = NULL; config->listeners[i].security_options.auto_id_prefix_len = 0; } config->allow_duplicate_messages = false; mosquitto__free(config->security_options.acl_file); config->security_options.acl_file = NULL; config->security_options.allow_anonymous = -1; config->security_options.allow_zero_length_clientid = true; config->security_options.auto_id_prefix = NULL; config->security_options.auto_id_prefix_len = 0; mosquitto__free(config->security_options.password_file); config->security_options.password_file = NULL; mosquitto__free(config->security_options.psk_file); config->security_options.psk_file = NULL; config->autosave_interval = 1800; config->autosave_on_changes = false; mosquitto__free(config->clientid_prefixes); config->connection_messages = true; config->clientid_prefixes = NULL; config->per_listener_settings = false; if(config->log_fptr){ fclose(config->log_fptr); config->log_fptr = NULL; } mosquitto__free(config->log_file); config->log_file = NULL; #if defined(WIN32) || defined(__CYGWIN__) if(service_handle){ /* This is running as a Windows service. Default to no logging. Using * stdout/stderr is forbidden because the first clients to connect will * get log information sent to them for some reason. */ config->log_dest = MQTT3_LOG_NONE; }else{ config->log_dest = MQTT3_LOG_STDERR; } #else config->log_facility = LOG_DAEMON; config->log_dest = MQTT3_LOG_STDERR; if(db->verbose){ config->log_type = INT_MAX; }else{ config->log_type = MOSQ_LOG_ERR | MOSQ_LOG_WARNING | MOSQ_LOG_NOTICE | MOSQ_LOG_INFO; } #endif config->log_timestamp = true; config->persistence = false; mosquitto__free(config->persistence_location); config->persistence_location = NULL; mosquitto__free(config->persistence_file); config->persistence_file = NULL; config->persistent_client_expiration = 0; config->queue_qos0_messages = false; config->set_tcp_nodelay = false; config->sys_interval = 10; config->upgrade_outgoing_qos = false; config__cleanup_plugins(config); } 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:
0
75,605
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, X509 *recip, unsigned int flags) { CMS_RecipientInfo *ri = NULL; CMS_EnvelopedData *env; EVP_PKEY *pk = NULL; env = cms_get0_enveloped(cms); if (!env) goto err; /* Initialize recipient info */ ri = M_ASN1_new_of(CMS_RecipientInfo); if (!ri) goto merr; pk = X509_get0_pubkey(recip); if (!pk) { CMSerr(CMS_F_CMS_ADD1_RECIPIENT_CERT, CMS_R_ERROR_GETTING_PUBLIC_KEY); goto err; } switch (cms_pkey_get_ri_type(pk)) { case CMS_RECIPINFO_TRANS: if (!cms_RecipientInfo_ktri_init(ri, recip, pk, flags)) goto err; break; case CMS_RECIPINFO_AGREE: if (!cms_RecipientInfo_kari_init(ri, recip, pk, flags)) goto err; break; default: CMSerr(CMS_F_CMS_ADD1_RECIPIENT_CERT, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); goto err; } if (!sk_CMS_RecipientInfo_push(env->recipientInfos, ri)) goto merr; return ri; merr: CMSerr(CMS_F_CMS_ADD1_RECIPIENT_CERT, ERR_R_MALLOC_FAILURE); err: M_ASN1_free_of(ri, CMS_RecipientInfo); return NULL; } Commit Message: CWE ID: CWE-311
0
11,916
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: sys_auth_passwd(Authctxt *authctxt, const char *password) { struct passwd *pw = authctxt->pw; char *encrypted_password, *salt = NULL; /* Just use the supplied fake password if authctxt is invalid */ char *pw_password = authctxt->valid ? shadow_pw(pw) : pw->pw_passwd; /* Check for users with no password. */ if (strcmp(pw_password, "") == 0 && strcmp(password, "") == 0) return (1); /* * Encrypt the candidate password using the proper salt, or pass a * NULL and let xcrypt pick one. */ if (authctxt->valid && pw_password[0] && pw_password[1]) salt = pw_password; encrypted_password = xcrypt(password, salt); /* * Authentication is accepted if the encrypted passwords * are identical. */ return encrypted_password != NULL && strcmp(encrypted_password, pw_password) == 0; } Commit Message: upstream commit Skip passwords longer than 1k in length so clients can't easily DoS sshd by sending very long passwords, causing it to spend CPU hashing them. feedback djm@, ok markus@. Brought to our attention by tomas.kuthan at oracle.com, shilei-c at 360.cn and coredump at autistici.org Upstream-ID: d0af7d4a2190b63ba1d38eec502bc4be0be9e333 CWE ID: CWE-20
0
50,591
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void RenderView::OnViewContextSwapBuffersPosted() { RenderWidget::OnSwapBuffersPosted(); } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
0
98,970
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: IV_API_CALL_STATUS_T impeg2d_api_get_version(iv_obj_t *ps_dechdl, void *pv_api_ip, void *pv_api_op) { char au1_version_string[512]; impeg2d_ctl_getversioninfo_ip_t *ps_ip; impeg2d_ctl_getversioninfo_op_t *ps_op; UNUSED(ps_dechdl); ps_ip = (impeg2d_ctl_getversioninfo_ip_t *)pv_api_ip; ps_op = (impeg2d_ctl_getversioninfo_op_t *)pv_api_op; ps_op->s_ivd_ctl_getversioninfo_op_t.u4_error_code = IV_SUCCESS; VERSION(au1_version_string, CODEC_NAME, CODEC_RELEASE_TYPE, CODEC_RELEASE_VER, CODEC_VENDOR); if((WORD32)ps_ip->s_ivd_ctl_getversioninfo_ip_t.u4_version_buffer_size <= 0) { ps_op->s_ivd_ctl_getversioninfo_op_t.u4_error_code = IV_FAIL; return (IV_FAIL); } if(ps_ip->s_ivd_ctl_getversioninfo_ip_t.u4_version_buffer_size >= (strlen(au1_version_string) + 1)) { memcpy(ps_ip->s_ivd_ctl_getversioninfo_ip_t.pv_version_buffer, au1_version_string, (strlen(au1_version_string) + 1)); ps_op->s_ivd_ctl_getversioninfo_op_t.u4_error_code = IV_SUCCESS; } else { ps_op->s_ivd_ctl_getversioninfo_op_t.u4_error_code = IV_FAIL; } return (IV_SUCCESS); } Commit Message: Fix in handling header decode errors If header decode was unsuccessful, do not try decoding a frame Also, initialize pic_wd, pic_ht for reinitialization when decoder is created with smaller dimensions Bug: 28886651 Bug: 35219737 Change-Id: I8c06d9052910e47fce2e6fe25ad318d4c83d2c50 (cherry picked from commit 2b9fa9ace2dbedfbac026fc9b6ab6cdac7f68c27) (cherry picked from commit c2395cd7cc0c286a66de674032dd2ed26500aef4) CWE ID: CWE-119
0
162,589
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: IPAttributesGetterMac::GetNetworkInterfaceType(const ifaddrs* if_addr) { if (!IsInitialized()) return NetworkChangeNotifier::CONNECTION_UNKNOWN; struct ifmediareq ifmr = {}; strncpy(ifmr.ifm_name, if_addr->ifa_name, sizeof(ifmr.ifm_name) - 1); if (ioctl(ioctl_socket_, SIOCGIFMEDIA, &ifmr) != -1) { if (ifmr.ifm_current & IFM_IEEE80211) { return NetworkChangeNotifier::CONNECTION_WIFI; } if (ifmr.ifm_current & IFM_ETHER) { return NetworkChangeNotifier::CONNECTION_ETHERNET; } } return NetworkChangeNotifier::CONNECTION_UNKNOWN; } Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <jbroman@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Bence Béky <bnc@chromium.org> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311
0
156,300
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static bool always_dump_vma(struct vm_area_struct *vma) { /* Any vsyscall mappings? */ if (vma == get_gate_vma(vma->vm_mm)) return true; /* * Assume that all vmas with a .name op should always be dumped. * If this changes, a new vm_ops field can easily be added. */ if (vma->vm_ops && vma->vm_ops->name && vma->vm_ops->name(vma)) return true; /* * arch_vma_name() returns non-NULL for special architecture mappings, * such as vDSO sections. */ if (arch_vma_name(vma)) return true; return false; } Commit Message: x86, mm/ASLR: Fix stack randomization on 64-bit systems The issue is that the stack for processes is not properly randomized on 64 bit architectures due to an integer overflow. The affected function is randomize_stack_top() in file "fs/binfmt_elf.c": static unsigned long randomize_stack_top(unsigned long stack_top) { unsigned int random_variable = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { random_variable = get_random_int() & STACK_RND_MASK; random_variable <<= PAGE_SHIFT; } return PAGE_ALIGN(stack_top) + random_variable; return PAGE_ALIGN(stack_top) - random_variable; } Note that, it declares the "random_variable" variable as "unsigned int". Since the result of the shifting operation between STACK_RND_MASK (which is 0x3fffff on x86_64, 22 bits) and PAGE_SHIFT (which is 12 on x86_64): random_variable <<= PAGE_SHIFT; then the two leftmost bits are dropped when storing the result in the "random_variable". This variable shall be at least 34 bits long to hold the (22+12) result. These two dropped bits have an impact on the entropy of process stack. Concretely, the total stack entropy is reduced by four: from 2^28 to 2^30 (One fourth of expected entropy). This patch restores back the entropy by correcting the types involved in the operations in the functions randomize_stack_top() and stack_maxrandom_size(). The successful fix can be tested with: $ for i in `seq 1 10`; do cat /proc/self/maps | grep stack; done 7ffeda566000-7ffeda587000 rw-p 00000000 00:00 0 [stack] 7fff5a332000-7fff5a353000 rw-p 00000000 00:00 0 [stack] 7ffcdb7a1000-7ffcdb7c2000 rw-p 00000000 00:00 0 [stack] 7ffd5e2c4000-7ffd5e2e5000 rw-p 00000000 00:00 0 [stack] ... Once corrected, the leading bytes should be between 7ffc and 7fff, rather than always being 7fff. Signed-off-by: Hector Marco-Gisbert <hecmargi@upv.es> Signed-off-by: Ismael Ripoll <iripoll@upv.es> [ Rebased, fixed 80 char bugs, cleaned up commit message, added test example and CVE ] Signed-off-by: Kees Cook <keescook@chromium.org> Cc: <stable@vger.kernel.org> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Al Viro <viro@zeniv.linux.org.uk> Fixes: CVE-2015-1593 Link: http://lkml.kernel.org/r/20150214173350.GA18393@www.outflux.net Signed-off-by: Borislav Petkov <bp@suse.de> CWE ID: CWE-264
0
44,276
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int irias_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) seq_puts(seq, "LM-IAS Objects:\n"); else { struct ias_object *obj = v; struct ias_attrib *attrib; IRDA_ASSERT(obj->magic == IAS_OBJECT_MAGIC, return -EINVAL;); seq_printf(seq, "name: %s, id=%d\n", obj->name, obj->id); /* Careful for priority inversions here ! * All other uses of attrib spinlock are independent of * the object spinlock, so we are safe. Jean II */ spin_lock(&obj->attribs->hb_spinlock); /* List all attributes for this object */ for (attrib = (struct ias_attrib *) hashbin_get_first(obj->attribs); attrib != NULL; attrib = (struct ias_attrib *) hashbin_get_next(obj->attribs)) { IRDA_ASSERT(attrib->magic == IAS_ATTRIB_MAGIC, goto outloop; ); seq_printf(seq, " - Attribute name: \"%s\", ", attrib->name); seq_printf(seq, "value[%s]: ", ias_value_types[attrib->value->type]); switch (attrib->value->type) { case IAS_INTEGER: seq_printf(seq, "%d\n", attrib->value->t.integer); break; case IAS_STRING: seq_printf(seq, "\"%s\"\n", attrib->value->t.string); break; case IAS_OCT_SEQ: seq_printf(seq, "octet sequence (%d bytes)\n", attrib->value->len); break; case IAS_MISSING: seq_puts(seq, "missing\n"); break; default: seq_printf(seq, "type %d?\n", attrib->value->type); } seq_putc(seq, '\n'); } IRDA_ASSERT_LABEL(outloop:) spin_unlock(&obj->attribs->hb_spinlock); } return 0; } Commit Message: irda: validate peer name and attribute lengths Length fields provided by a peer for names and attributes may be longer than the destination array sizes. Validate lengths to prevent stack buffer overflows. Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com> Cc: stable@kernel.org Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-119
0
35,219
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: struct file *get_empty_filp(void) { const struct cred *cred = current_cred(); static long old_max; struct file *f; int error; /* * Privileged users can go above max_files */ if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) { /* * percpu_counters are inaccurate. Do an expensive check before * we go and fail. */ if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files) goto over; } f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL); if (unlikely(!f)) return ERR_PTR(-ENOMEM); percpu_counter_inc(&nr_files); f->f_cred = get_cred(cred); error = security_file_alloc(f); if (unlikely(error)) { file_free(f); return ERR_PTR(error); } INIT_LIST_HEAD(&f->f_u.fu_list); atomic_long_set(&f->f_count, 1); rwlock_init(&f->f_owner.lock); spin_lock_init(&f->f_lock); eventpoll_init_file(f); /* f->f_version: 0 */ return f; over: /* Ran out of filps - report that */ if (get_nr_files() > old_max) { pr_info("VFS: file-max limit %lu reached\n", get_max_files()); old_max = get_nr_files(); } return ERR_PTR(-ENFILE); } 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 <viro@zeniv.linux.org.uk> CWE ID: CWE-17
1
166,802
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static enum virtio_device_endian virtio_current_cpu_endian(void) { CPUClass *cc = CPU_GET_CLASS(current_cpu); if (cc->virtio_is_big_endian(current_cpu)) { return VIRTIO_DEVICE_ENDIAN_BIG; } else { return VIRTIO_DEVICE_ENDIAN_LITTLE; } } Commit Message: CWE ID: CWE-20
0
9,193
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void PDFiumEngine::OnGetPasswordComplete(int32_t result, const pp::Var& password) { getting_password_ = false; std::string password_text; if (result == PP_OK && password.is_string()) password_text = password.AsString(); ContinueLoadingDocument(password_text); } Commit Message: [pdf] Defer page unloading in JS callback. One of the callbacks from PDFium JavaScript into the embedder is to get the current page number. In Chromium, this will trigger a call to CalculateMostVisiblePage that method will determine the visible pages and unload any non-visible pages. But, if the originating JS is on a non-visible page we'll delete the page and annotations associated with that page. This will cause issues as we are currently working with those objects when the JavaScript returns. This Cl defers the page unloading triggered by getting the most visible page until the next event is handled by the Chromium embedder. BUG=chromium:653090 Review-Url: https://codereview.chromium.org/2418533002 Cr-Commit-Position: refs/heads/master@{#424781} CWE ID: CWE-416
0
140,380
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int sco_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *ch; long timeo; int err = 0; lock_sock(sk); timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } ch = bt_accept_dequeue(sk, newsock); if (ch) break; if (!timeo) { err = -EAGAIN; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", ch); done: release_sock(sk); return err; } Commit Message: Bluetooth: SCO - Fix missing msg_namelen update in sco_sock_recvmsg() If the socket is in state BT_CONNECT2 and BT_SK_DEFER_SETUP is set in the flags, sco_sock_recvmsg() returns early with 0 without updating the possibly set msg_namelen member. This, in turn, leads to a 128 byte kernel stack leak in net/socket.c. Fix this by updating msg_namelen in this case. For all other cases it will be handled in bt_sock_recvmsg(). Cc: Marcel Holtmann <marcel@holtmann.org> Cc: Gustavo Padovan <gustavo@padovan.org> Cc: Johan Hedberg <johan.hedberg@gmail.com> Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
0
30,711
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void GKI_disable(void) { pthread_mutex_lock(&gki_cb.lock); } 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
0
158,918
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: InProcessBrowserTest::InProcessBrowserTest() : browser_(NULL), exit_when_last_browser_closes_(true), multi_desktop_test_(false) #if defined(OS_MACOSX) , autorelease_pool_(NULL) #endif // OS_MACOSX { #if defined(OS_MACOSX) base::FilePath chrome_path; CHECK(PathService::Get(base::FILE_EXE, &chrome_path)); chrome_path = chrome_path.DirName(); chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath); CHECK(PathService::Override(base::FILE_EXE, chrome_path)); #endif // defined(OS_MACOSX) CreateTestServer(base::FilePath(FILE_PATH_LITERAL("chrome/test/data"))); base::FilePath src_dir; CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &src_dir)); base::FilePath test_data_dir = src_dir.AppendASCII("chrome/test/data"); embedded_test_server()->ServeFilesFromDirectory(test_data_dir); CHECK(PathService::Override(chrome::DIR_TEST_DATA, test_data_dir)); } 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
1
171,151
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static RBinElfSymbol* Elf_(_r_bin_elf_get_symbols_imports)(ELFOBJ *bin, int type) { ut32 shdr_size; int tsize, nsym, ret_ctr = 0, i, j, r, k, newsize; ut64 toffset; ut32 size = 0; RBinElfSymbol *ret = NULL; Elf_(Shdr) *strtab_section = NULL; Elf_(Sym) *sym = NULL; ut8 s[sizeof (Elf_(Sym))] = { 0 }; char *strtab = NULL; if (!bin || !bin->shdr || !bin->ehdr.e_shnum || bin->ehdr.e_shnum == 0xffff) { return (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); } if (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) { return false; } if (shdr_size + 8 > bin->size) { return false; } for (i = 0; i < bin->ehdr.e_shnum; i++) { if ((type == R_BIN_ELF_IMPORTS && bin->shdr[i].sh_type == (bin->ehdr.e_type == ET_REL ? SHT_SYMTAB : SHT_DYNSYM)) || (type == R_BIN_ELF_SYMBOLS && bin->shdr[i].sh_type == (Elf_(r_bin_elf_get_stripped) (bin) ? SHT_DYNSYM : SHT_SYMTAB))) { if (bin->shdr[i].sh_link < 1) { /* oops. fix out of range pointers */ continue; } if ((bin->shdr[i].sh_link * sizeof(Elf_(Shdr))) >= shdr_size) { /* oops. fix out of range pointers */ continue; } strtab_section = &bin->shdr[bin->shdr[i].sh_link]; if (strtab_section->sh_size > ST32_MAX || strtab_section->sh_size+8 > bin->size) { bprintf ("size (syms strtab)"); free (ret); free (strtab); return NULL; } if (!strtab) { if (!(strtab = (char *)calloc (1, 8 + strtab_section->sh_size))) { bprintf ("malloc (syms strtab)"); goto beach; } if (strtab_section->sh_offset > bin->size || strtab_section->sh_offset + strtab_section->sh_size > bin->size) { goto beach; } if (r_buf_read_at (bin->b, strtab_section->sh_offset, (ut8*)strtab, strtab_section->sh_size) == -1) { bprintf ("Warning: read (syms strtab)\n"); goto beach; } } newsize = 1 + bin->shdr[i].sh_size; if (newsize < 0 || newsize > bin->size) { bprintf ("invalid shdr %d size\n", i); goto beach; } nsym = (int)(bin->shdr[i].sh_size / sizeof (Elf_(Sym))); if (nsym < 0) { goto beach; } if (!(sym = (Elf_(Sym) *)calloc (nsym, sizeof (Elf_(Sym))))) { bprintf ("calloc (syms)"); goto beach; } if (!UT32_MUL (&size, nsym, sizeof (Elf_(Sym)))) { goto beach; } if (size < 1 || size > bin->size) { goto beach; } if (bin->shdr[i].sh_offset > bin->size) { goto beach; } if (bin->shdr[i].sh_offset + size > bin->size) { goto beach; } for (j = 0; j < nsym; j++) { int k = 0; r = r_buf_read_at (bin->b, bin->shdr[i].sh_offset + j * sizeof (Elf_(Sym)), s, sizeof (Elf_(Sym))); if (r < 1) { bprintf ("Warning: read (sym)\n"); goto beach; } #if R_BIN_ELF64 sym[j].st_name = READ32 (s, k) sym[j].st_info = READ8 (s, k) sym[j].st_other = READ8 (s, k) sym[j].st_shndx = READ16 (s, k) sym[j].st_value = READ64 (s, k) sym[j].st_size = READ64 (s, k) #else sym[j].st_name = READ32 (s, k) sym[j].st_value = READ32 (s, k) sym[j].st_size = READ32 (s, k) sym[j].st_info = READ8 (s, k) sym[j].st_other = READ8 (s, k) sym[j].st_shndx = READ16 (s, k) #endif } free (ret); ret = calloc (nsym, sizeof (RBinElfSymbol)); if (!ret) { bprintf ("Cannot allocate %d symbols\n", nsym); goto beach; } for (k = 1, ret_ctr = 0; k < nsym; k++) { if (type == R_BIN_ELF_IMPORTS && sym[k].st_shndx == STN_UNDEF) { if (sym[k].st_value) { toffset = sym[k].st_value; } else if ((toffset = get_import_addr (bin, k)) == -1){ toffset = 0; } tsize = 16; } else if (type == R_BIN_ELF_SYMBOLS && sym[k].st_shndx != STN_UNDEF && ELF_ST_TYPE (sym[k].st_info) != STT_SECTION && ELF_ST_TYPE (sym[k].st_info) != STT_FILE) { tsize = sym[k].st_size; toffset = (ut64)sym[k].st_value; } else { continue; } if (bin->ehdr.e_type == ET_REL) { if (sym[k].st_shndx < bin->ehdr.e_shnum) ret[ret_ctr].offset = sym[k].st_value + bin->shdr[sym[k].st_shndx].sh_offset; } else { ret[ret_ctr].offset = Elf_(r_bin_elf_v2p) (bin, toffset); } ret[ret_ctr].size = tsize; if (sym[k].st_name + 2 > strtab_section->sh_size) { bprintf ("Warning: index out of strtab range\n"); goto beach; } { int rest = ELF_STRING_LENGTH - 1; int st_name = sym[k].st_name; int maxsize = R_MIN (bin->b->length, strtab_section->sh_size); if (st_name < 0 || st_name >= maxsize) { ret[ret_ctr].name[0] = 0; } else { const size_t len = __strnlen (strtab + sym[k].st_name, rest); memcpy (ret[ret_ctr].name, &strtab[sym[k].st_name], len); } } ret[ret_ctr].ordinal = k; ret[ret_ctr].name[ELF_STRING_LENGTH - 2] = '\0'; fill_symbol_bind_and_type (&ret[ret_ctr], &sym[k]); ret[ret_ctr].last = 0; ret_ctr++; } ret[ret_ctr].last = 1; // ugly dirty hack :D R_FREE (strtab); R_FREE (sym); } } if (!ret) { return (type == R_BIN_ELF_SYMBOLS) ? Elf_(r_bin_elf_get_phdr_symbols) (bin) : Elf_(r_bin_elf_get_phdr_imports) (bin); } int max = -1; RBinElfSymbol *aux = NULL; nsym = Elf_(fix_symbols) (bin, ret_ctr, type, &ret); if (nsym == -1) { goto beach; } aux = ret; while (!aux->last) { if ((int)aux->ordinal > max) { max = aux->ordinal; } aux++; } nsym = max; if (type == R_BIN_ELF_IMPORTS) { R_FREE (bin->imports_by_ord); bin->imports_by_ord_size = nsym + 1; bin->imports_by_ord = (RBinImport**)calloc (R_MAX (1, nsym + 1), sizeof (RBinImport*)); } else if (type == R_BIN_ELF_SYMBOLS) { R_FREE (bin->symbols_by_ord); bin->symbols_by_ord_size = nsym + 1; bin->symbols_by_ord = (RBinSymbol**)calloc (R_MAX (1, nsym + 1), sizeof (RBinSymbol*)); } return ret; beach: free (ret); free (sym); free (strtab); return NULL; } Commit Message: Fix #8764 - huge vd_aux caused pointer wraparound CWE ID: CWE-476
0
60,029
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool GLES2DecoderImpl::DoBindOrCopyTexImageIfNeeded(Texture* texture, GLenum textarget, GLuint texture_unit) { if (texture && !texture->IsAttachedToFramebuffer()) { Texture::ImageState image_state; gl::GLImage* image = texture->GetLevelImage(textarget, 0, &image_state); if (image && image_state == Texture::UNBOUND) { ScopedGLErrorSuppressor suppressor( "GLES2DecoderImpl::DoBindOrCopyTexImageIfNeeded", error_state_.get()); if (texture_unit) api()->glActiveTextureFn(texture_unit); api()->glBindTextureFn(textarget, texture->service_id()); if (image->ShouldBindOrCopy() == gl::GLImage::BIND) { bool rv = image->BindTexImage(textarget); DCHECK(rv) << "BindTexImage() failed"; image_state = Texture::BOUND; } else { DoCopyTexImage(texture, textarget, image); } if (!texture_unit) { RestoreCurrentTextureBindings(&state_, textarget, state_.active_texture_unit); return false; } return true; } } return false; } 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 <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
0
141,264
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void md_cluster_stop(struct mddev *mddev) { if (!md_cluster_ops) return; md_cluster_ops->leave(mddev); module_put(md_cluster_mod); } Commit Message: md: use kzalloc() when bitmap is disabled In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a mdu_bitmap_file_t called "file". 5769 file = kmalloc(sizeof(*file), GFP_NOIO); 5770 if (!file) 5771 return -ENOMEM; This structure is copied to user space at the end of the function. 5786 if (err == 0 && 5787 copy_to_user(arg, file, sizeof(*file))) 5788 err = -EFAULT But if bitmap is disabled only the first byte of "file" is initialized with zero, so it's possible to read some bytes (up to 4095) of kernel space memory from user space. This is an information leak. 5775 /* bitmap disabled, zero the first byte and copy out */ 5776 if (!mddev->bitmap_info.file) 5777 file->pathname[0] = '\0'; Signed-off-by: Benjamin Randazzo <benjamin@randazzo.fr> Signed-off-by: NeilBrown <neilb@suse.com> CWE ID: CWE-200
0
42,421
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: brcmf_cfg80211_escan(struct wiphy *wiphy, struct brcmf_cfg80211_vif *vif, struct cfg80211_scan_request *request, struct cfg80211_ssid *this_ssid) { struct brcmf_if *ifp = vif->ifp; struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy); struct cfg80211_ssid *ssids; u32 passive_scan; bool escan_req; bool spec_scan; s32 err; struct brcmf_ssid_le ssid_le; u32 SSID_len; brcmf_dbg(SCAN, "START ESCAN\n"); if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) { brcmf_err("Scanning already: status (%lu)\n", cfg->scan_status); return -EAGAIN; } if (test_bit(BRCMF_SCAN_STATUS_ABORT, &cfg->scan_status)) { brcmf_err("Scanning being aborted: status (%lu)\n", cfg->scan_status); return -EAGAIN; } if (test_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status)) { brcmf_err("Scanning suppressed: status (%lu)\n", cfg->scan_status); return -EAGAIN; } if (test_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state)) { brcmf_err("Connecting: status (%lu)\n", ifp->vif->sme_state); return -EAGAIN; } /* If scan req comes for p2p0, send it over primary I/F */ if (vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif) vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif; escan_req = false; if (request) { /* scan bss */ ssids = request->ssids; escan_req = true; } else { /* scan in ibss */ /* we don't do escan in ibss */ ssids = this_ssid; } cfg->scan_request = request; set_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status); if (escan_req) { cfg->escan_info.run = brcmf_run_escan; err = brcmf_p2p_scan_prep(wiphy, request, vif); if (err) goto scan_out; err = brcmf_do_escan(cfg, wiphy, vif->ifp, request); if (err) goto scan_out; } else { brcmf_dbg(SCAN, "ssid \"%s\", ssid_len (%d)\n", ssids->ssid, ssids->ssid_len); memset(&ssid_le, 0, sizeof(ssid_le)); SSID_len = min_t(u8, sizeof(ssid_le.SSID), ssids->ssid_len); ssid_le.SSID_len = cpu_to_le32(0); spec_scan = false; if (SSID_len) { memcpy(ssid_le.SSID, ssids->ssid, SSID_len); ssid_le.SSID_len = cpu_to_le32(SSID_len); spec_scan = true; } else brcmf_dbg(SCAN, "Broadcast scan\n"); passive_scan = cfg->active_scan ? 0 : 1; err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PASSIVE_SCAN, passive_scan); if (err) { brcmf_err("WLC_SET_PASSIVE_SCAN error (%d)\n", err); goto scan_out; } brcmf_scan_config_mpc(ifp, 0); err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SCAN, &ssid_le, sizeof(ssid_le)); if (err) { if (err == -EBUSY) brcmf_dbg(INFO, "BUSY: scan for \"%s\" canceled\n", ssid_le.SSID); else brcmf_err("WLC_SCAN error (%d)\n", err); brcmf_scan_config_mpc(ifp, 1); goto scan_out; } } /* Arm scan timeout timer */ mod_timer(&cfg->escan_timeout, jiffies + BRCMF_ESCAN_TIMER_INTERVAL_MS * HZ / 1000); return 0; scan_out: clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status); cfg->scan_request = NULL; return err; } Commit Message: brcmfmac: avoid potential stack overflow in brcmf_cfg80211_start_ap() User-space can choose to omit NL80211_ATTR_SSID and only provide raw IE TLV data. When doing so it can provide SSID IE with length exceeding the allowed size. The driver further processes this IE copying it into a local variable without checking the length. Hence stack can be corrupted and used as exploit. Cc: stable@vger.kernel.org # v4.7 Reported-by: Daxing Guo <freener.gdx@gmail.com> Reviewed-by: Hante Meuleman <hante.meuleman@broadcom.com> Reviewed-by: Pieter-Paul Giesberts <pieter-paul.giesberts@broadcom.com> Reviewed-by: Franky Lin <franky.lin@broadcom.com> Signed-off-by: Arend van Spriel <arend.vanspriel@broadcom.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.org> CWE ID: CWE-119
0
49,014
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void phar_do_403(char *entry, int entry_len) /* {{{ */ { sapi_header_line ctr = {0}; ctr.response_code = 403; ctr.line_len = sizeof("HTTP/1.0 403 Access Denied")-1; ctr.line = "HTTP/1.0 403 Access Denied"; sapi_header_op(SAPI_HEADER_REPLACE, &ctr); sapi_send_headers(); PHPWRITE("<html>\n <head>\n <title>Access Denied</title>\n </head>\n <body>\n <h1>403 - File ", sizeof("<html>\n <head>\n <title>Access Denied</title>\n </head>\n <body>\n <h1>403 - File ") - 1); PHPWRITE(entry, entry_len); PHPWRITE(" Access Denied</h1>\n </body>\n</html>", sizeof(" Access Denied</h1>\n </body>\n</html>") - 1); } /* }}} */ Commit Message: CWE ID: CWE-20
0
11,179
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void InspectorNetworkAgent::DelayedRemoveReplayXHR(XMLHttpRequest* xhr) { if (!replay_xhrs_.Contains(xhr)) return; replay_xhrs_to_be_deleted_.insert(xhr); replay_xhrs_.erase(xhr); remove_finished_replay_xhr_timer_.StartOneShot(0, BLINK_FROM_HERE); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
0
138,474
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void rxrpc_kernel_data_delivered(struct sk_buff *skb) { struct rxrpc_skb_priv *sp = rxrpc_skb(skb); struct rxrpc_call *call = sp->call; ASSERTCMP(ntohl(sp->hdr.seq), >=, call->rx_data_recv); ASSERTCMP(ntohl(sp->hdr.seq), <=, call->rx_data_recv + 1); call->rx_data_recv = ntohl(sp->hdr.seq); ASSERTCMP(ntohl(sp->hdr.seq), >, call->rx_data_eaten); rxrpc_free_skb(skb); } 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 <davem@davemloft.net> Suggested-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
0
40,671
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, TestObj* impl) { return wrap<JSTestObj>(exec, globalObject, impl); } 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
0
101,374
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: dissect_common_control(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, int offset, struct fp_info *p_fp_info) { /* Common control frame type */ guint8 control_frame_type = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_fp_common_control_frame_type, tvb, offset, 1, ENC_BIG_ENDIAN); offset++; col_append_str(pinfo->cinfo, COL_INFO, val_to_str_const(control_frame_type, common_control_frame_type_vals, "Unknown")); /* Frame-type specific dissection */ switch (control_frame_type) { case COMMON_OUTER_LOOP_POWER_CONTROL: /*offset =*/ dissect_common_outer_loop_power_control(pinfo, tree, tvb, offset, p_fp_info); break; case COMMON_TIMING_ADJUSTMENT: /*offset =*/ dissect_common_timing_adjustment(pinfo, tree, tvb, offset, p_fp_info); break; case COMMON_DL_SYNCHRONISATION: /*offset =*/ dissect_common_dl_synchronisation(pinfo, tree, tvb, offset, p_fp_info); break; case COMMON_UL_SYNCHRONISATION: /*offset =*/ dissect_common_ul_synchronisation(pinfo, tree, tvb, offset, p_fp_info); break; case COMMON_DL_NODE_SYNCHRONISATION: /*offset =*/ dissect_common_dl_node_synchronisation(pinfo, tree, tvb, offset); break; case COMMON_UL_NODE_SYNCHRONISATION: /*offset =*/ dissect_common_ul_node_synchronisation(pinfo, tree, tvb, offset); break; case COMMON_DYNAMIC_PUSCH_ASSIGNMENT: /*offset =*/ dissect_common_dynamic_pusch_assignment(pinfo, tree, tvb, offset); break; case COMMON_TIMING_ADVANCE: /*offset =*/ dissect_common_timing_advance(pinfo, tree, tvb, offset); break; case COMMON_HS_DSCH_Capacity_Request: /*offset =*/ dissect_hsdpa_capacity_request(pinfo, tree, tvb, offset); break; case COMMON_HS_DSCH_Capacity_Allocation: /*offset =*/ dissect_hsdpa_capacity_allocation(pinfo, tree, tvb, offset, p_fp_info); break; case COMMON_HS_DSCH_Capacity_Allocation_Type_2: /*offset =*/ dissect_hsdpa_capacity_allocation_type_2(pinfo, tree, tvb, offset); break; default: break; } /* There is no Spare Extension nor payload crc in common control!? */ /* dissect_spare_extension_and_crc(tvb, pinfo, tree, 0, offset); */ } Commit Message: UMTS_FP: fix handling reserved C/T value The spec puts the reserved value at 0xf but our internal table has 'unknown' at 0; since all the other values seem to be offset-by-one, just take the modulus 0xf to avoid running off the end of the table. Bug: 12191 Change-Id: I83c8fb66797bbdee52a2246fb1eea6e37cbc7eb0 Reviewed-on: https://code.wireshark.org/review/15722 Reviewed-by: Evan Huus <eapache@gmail.com> Petri-Dish: Evan Huus <eapache@gmail.com> Tested-by: Petri Dish Buildbot <buildbot-no-reply@wireshark.org> Reviewed-by: Michael Mann <mmann78@netscape.net> CWE ID: CWE-20
0
51,841
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: grub_ext2_blockgroup (struct grub_ext2_data *data, int group, struct grub_ext2_block_group *blkgrp) { return grub_disk_read (data->disk, ((grub_le_to_cpu32 (data->sblock.first_data_block) + 1) << LOG2_EXT2_BLOCK_SIZE (data)), group * sizeof (struct grub_ext2_block_group), sizeof (struct grub_ext2_block_group), blkgrp); } Commit Message: Fix ext2 buffer overflow in r2_sbu_grub_memmove CWE ID: CWE-787
0
64,153
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: MirrorMockURLRequestJob(net::URLRequest* request, net::NetworkDelegate* network_delegate, const base::FilePath& file_path, ReportResponseHeadersOnUI report_on_ui) : net::URLRequestMockHTTPJob(request, network_delegate, file_path), report_on_ui_(report_on_ui) {} Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <jam@chromium.org> Reviewed-by: Ramin Halavati <rhalavati@chromium.org> Reviewed-by: Maks Orlovich <morlovich@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Cr-Commit-Position: refs/heads/master@{#607652} CWE ID:
1
172,578
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void BrowserWindowGtk::AddFindBar(FindBarGtk* findbar) { gtk_floating_container_add_floating( GTK_FLOATING_CONTAINER(render_area_floating_container_), findbar->widget()); } 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
0
117,895
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: brcmf_cfg80211_get_station_ibss(struct brcmf_if *ifp, struct station_info *sinfo) { struct brcmf_scb_val_le scbval; struct brcmf_pktcnt_le pktcnt; s32 err; u32 rate; u32 rssi; /* Get the current tx rate */ err = brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_RATE, &rate); if (err < 0) { brcmf_err("BRCMF_C_GET_RATE error (%d)\n", err); return err; } sinfo->filled |= BIT(NL80211_STA_INFO_TX_BITRATE); sinfo->txrate.legacy = rate * 5; memset(&scbval, 0, sizeof(scbval)); err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_RSSI, &scbval, sizeof(scbval)); if (err) { brcmf_err("BRCMF_C_GET_RSSI error (%d)\n", err); return err; } rssi = le32_to_cpu(scbval.val); sinfo->filled |= BIT(NL80211_STA_INFO_SIGNAL); sinfo->signal = rssi; err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_GET_PKTCNTS, &pktcnt, sizeof(pktcnt)); if (err) { brcmf_err("BRCMF_C_GET_GET_PKTCNTS error (%d)\n", err); return err; } sinfo->filled |= BIT(NL80211_STA_INFO_RX_PACKETS) | BIT(NL80211_STA_INFO_RX_DROP_MISC) | BIT(NL80211_STA_INFO_TX_PACKETS) | BIT(NL80211_STA_INFO_TX_FAILED); sinfo->rx_packets = le32_to_cpu(pktcnt.rx_good_pkt); sinfo->rx_dropped_misc = le32_to_cpu(pktcnt.rx_bad_pkt); sinfo->tx_packets = le32_to_cpu(pktcnt.tx_good_pkt); sinfo->tx_failed = le32_to_cpu(pktcnt.tx_bad_pkt); return 0; } Commit Message: brcmfmac: avoid potential stack overflow in brcmf_cfg80211_start_ap() User-space can choose to omit NL80211_ATTR_SSID and only provide raw IE TLV data. When doing so it can provide SSID IE with length exceeding the allowed size. The driver further processes this IE copying it into a local variable without checking the length. Hence stack can be corrupted and used as exploit. Cc: stable@vger.kernel.org # v4.7 Reported-by: Daxing Guo <freener.gdx@gmail.com> Reviewed-by: Hante Meuleman <hante.meuleman@broadcom.com> Reviewed-by: Pieter-Paul Giesberts <pieter-paul.giesberts@broadcom.com> Reviewed-by: Franky Lin <franky.lin@broadcom.com> Signed-off-by: Arend van Spriel <arend.vanspriel@broadcom.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.org> CWE ID: CWE-119
0
49,023
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void ExtensionSystemImpl::Shutdown() { extension_process_manager_.reset(); } Commit Message: Check prefs before allowing extension file access in the permissions API. R=mpcomplete@chromium.org BUG=169632 Review URL: https://chromiumcodereview.appspot.com/11884008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
0
115,932
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static struct bio *__bio_alloc(struct f2fs_sb_info *sbi, block_t blk_addr, int npages, bool is_read) { struct bio *bio; bio = f2fs_bio_alloc(npages); f2fs_target_device(sbi, blk_addr, bio); bio->bi_end_io = is_read ? f2fs_read_end_io : f2fs_write_end_io; bio->bi_private = is_read ? NULL : sbi; return bio; } Commit Message: f2fs: fix a dead loop in f2fs_fiemap() A dead loop can be triggered in f2fs_fiemap() using the test case as below: ... fd = open(); fallocate(fd, 0, 0, 4294967296); ioctl(fd, FS_IOC_FIEMAP, fiemap_buf); ... It's caused by an overflow in __get_data_block(): ... bh->b_size = map.m_len << inode->i_blkbits; ... map.m_len is an unsigned int, and bh->b_size is a size_t which is 64 bits on 64 bits archtecture, type conversion from an unsigned int to a size_t will result in an overflow. In the above-mentioned case, bh->b_size will be zero, and f2fs_fiemap() will call get_data_block() at block 0 again an again. Fix this by adding a force conversion before left shift. Signed-off-by: Wei Fang <fangwei1@huawei.com> Acked-by: Chao Yu <yuchao0@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID: CWE-190
0
85,151
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int32_t PPB_URLLoader_Impl::FollowRedirect( scoped_refptr<TrackedCallback> callback) { int32_t rv = ValidateCallback(callback); if (rv != PP_OK) return rv; SetDefersLoading(false); // Allow the redirect to continue. RegisterCallback(callback); return PP_OK_COMPLETIONPENDING; } Commit Message: Break path whereby AssociatedURLLoader::~AssociatedURLLoader() is re-entered on top of itself. BUG=159429 Review URL: https://chromiumcodereview.appspot.com/11359222 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168150 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
0
102,311
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: void vnc_disconnect_finish(VncState *vs) { int i; vnc_jobs_join(vs); /* Wait encoding jobs */ vnc_lock_output(vs); vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED); buffer_free(&vs->input); buffer_free(&vs->output); #ifdef CONFIG_VNC_WS buffer_free(&vs->ws_input); buffer_free(&vs->ws_output); #endif /* CONFIG_VNC_WS */ qapi_free_VncClientInfo(vs->info); vnc_zlib_clear(vs); vnc_tight_clear(vs); vnc_zrle_clear(vs); #ifdef CONFIG_VNC_TLS vnc_tls_client_cleanup(vs); #endif /* CONFIG_VNC_TLS */ #ifdef CONFIG_VNC_SASL vnc_sasl_client_cleanup(vs); #endif /* CONFIG_VNC_SASL */ audio_del(vs); vnc_release_modifiers(vs); if (vs->initialized) { QTAILQ_REMOVE(&vs->vd->clients, vs, next); qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier); } if (vs->vd->lock_key_sync) qemu_remove_led_event_handler(vs->led); vnc_unlock_output(vs); qemu_mutex_destroy(&vs->output_mutex); if (vs->bh != NULL) { qemu_bh_delete(vs->bh); } buffer_free(&vs->jobs_buffer); for (i = 0; i < VNC_STAT_ROWS; ++i) { g_free(vs->lossy_rect[i]); } g_free(vs->lossy_rect); g_free(vs); } Commit Message: CWE ID: CWE-264
0
8,012
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: MagickExport MagickBooleanType GetImageQuantizeError(Image *image) { CacheView *image_view; ExceptionInfo *exception; IndexPacket *indexes; MagickRealType alpha, area, beta, distance, gamma, maximum_error, mean_error, mean_error_per_pixel; size_t index; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception); (void) ResetMagickMemory(&image->error,0,sizeof(image->error)); if (image->storage_class == DirectClass) return(MagickTrue); alpha=1.0; beta=1.0; area=3.0*image->columns*image->rows; maximum_error=0.0; mean_error_per_pixel=0.0; mean_error=0.0; exception=(&image->exception); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { index=1UL*GetPixelIndex(indexes+x); if (image->matte != MagickFalse) { alpha=(MagickRealType) (QuantumScale*(GetPixelAlpha(p))); beta=(MagickRealType) (QuantumScale*(QuantumRange- image->colormap[index].opacity)); } distance=fabs((double) (alpha*GetPixelRed(p)-beta* image->colormap[index].red)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelGreen(p)-beta* image->colormap[index].green)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelBlue(p)-beta* image->colormap[index].blue)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; p++; } } image_view=DestroyCacheView(image_view); gamma=PerceptibleReciprocal(area); image->error.mean_error_per_pixel=gamma*mean_error_per_pixel; image->error.normalized_mean_error=gamma*QuantumScale*QuantumScale*mean_error; image->error.normalized_maximum_error=QuantumScale*maximum_error; return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/574 CWE ID: CWE-772
0
62,709
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: xmlBufGetInputBase(xmlBufPtr buf, xmlParserInputPtr input) { size_t base; if ((input == NULL) || (buf == NULL) || (buf->error)) return(-1); CHECK_COMPAT(buf) base = input->base - buf->content; /* * We could do some pointer arythmetic checks but that's probably * sufficient. */ if (base > buf->size) { xmlBufOverflowError(buf, "Input reference outside of the buffer"); base = 0; } return(base); } Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9 Removes a few patches fixed upstream: https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3 https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882 Stops using the NOXXE flag which was reverted upstream: https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d Changes the patch to uri.c to not add limits.h, which is included upstream. Bug: 722079 Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac Reviewed-on: https://chromium-review.googlesource.com/535233 Reviewed-by: Scott Graham <scottmg@chromium.org> Commit-Queue: Dominic Cooney <dominicc@chromium.org> Cr-Commit-Position: refs/heads/master@{#480755} CWE ID: CWE-787
0
150,861
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static void alloc_msn_index(struct ImapData *idata, size_t msn_count) { size_t new_size; if (msn_count <= idata->msn_index_size) return; /* This is a conservative check to protect against a malicious imap * server. Most likely size_t is bigger than an unsigned int, but * if msn_count is this big, we have a serious problem. */ if (msn_count >= (UINT_MAX / sizeof(struct Header *))) { mutt_error(_("Integer overflow -- can't allocate memory.")); mutt_exit(1); } /* Add a little padding, like mx_allloc_memory() */ new_size = msn_count + 25; if (!idata->msn_index) idata->msn_index = mutt_mem_calloc(new_size, sizeof(struct Header *)); else { mutt_mem_realloc(&idata->msn_index, sizeof(struct Header *) * new_size); memset(idata->msn_index + idata->msn_index_size, 0, sizeof(struct Header *) * (new_size - idata->msn_index_size)); } idata->msn_index_size = new_size; } Commit Message: Don't overflow stack buffer in msg_parse_fetch CWE ID: CWE-119
0
79,528
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int show_smap(struct seq_file *m, void *v, int is_pid) { struct vm_area_struct *vma = v; struct mem_size_stats mss; struct mm_walk smaps_walk = { .pmd_entry = smaps_pte_range, .mm = vma->vm_mm, .private = &mss, }; memset(&mss, 0, sizeof mss); /* mmap_sem is held in m_start */ walk_page_vma(vma, &smaps_walk); show_map_vma(m, vma, is_pid); seq_printf(m, "Size: %8lu kB\n" "Rss: %8lu kB\n" "Pss: %8lu kB\n" "Shared_Clean: %8lu kB\n" "Shared_Dirty: %8lu kB\n" "Private_Clean: %8lu kB\n" "Private_Dirty: %8lu kB\n" "Referenced: %8lu kB\n" "Anonymous: %8lu kB\n" "AnonHugePages: %8lu kB\n" "Swap: %8lu kB\n" "KernelPageSize: %8lu kB\n" "MMUPageSize: %8lu kB\n" "Locked: %8lu kB\n", (vma->vm_end - vma->vm_start) >> 10, mss.resident >> 10, (unsigned long)(mss.pss >> (10 + PSS_SHIFT)), mss.shared_clean >> 10, mss.shared_dirty >> 10, mss.private_clean >> 10, mss.private_dirty >> 10, mss.referenced >> 10, mss.anonymous >> 10, mss.anonymous_thp >> 10, mss.swap >> 10, vma_kernel_pagesize(vma) >> 10, vma_mmu_pagesize(vma) >> 10, (vma->vm_flags & VM_LOCKED) ? (unsigned long)(mss.pss >> (10 + PSS_SHIFT)) : 0); show_smap_vma_flags(m, vma); m_cache_vma(m, vma); return 0; } Commit Message: pagemap: do not leak physical addresses to non-privileged userspace As pointed by recent post[1] on exploiting DRAM physical imperfection, /proc/PID/pagemap exposes sensitive information which can be used to do attacks. This disallows anybody without CAP_SYS_ADMIN to read the pagemap. [1] http://googleprojectzero.blogspot.com/2015/03/exploiting-dram-rowhammer-bug-to-gain.html [ Eventually we might want to do anything more finegrained, but for now this is the simple model. - Linus ] Signed-off-by: Kirill A. Shutemov <kirill.shutemov@linux.intel.com> Acked-by: Konstantin Khlebnikov <khlebnikov@openvz.org> Acked-by: Andy Lutomirski <luto@amacapital.net> Cc: Pavel Emelyanov <xemul@parallels.com> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Mark Seaborn <mseaborn@chromium.org> Cc: stable@vger.kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-200
0
55,822
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: static int http_proxy_open(URLContext *h, const char *uri, int flags) { HTTPContext *s = h->priv_data; char hostname[1024], hoststr[1024]; char auth[1024], pathbuf[1024], *path; char lower_url[100]; int port, ret = 0, attempts = 0; HTTPAuthType cur_auth_type; char *authstr; int new_loc; if( s->seekable == 1 ) h->is_streamed = 0; else h->is_streamed = 1; av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port, pathbuf, sizeof(pathbuf), uri); ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL); path = pathbuf; if (*path == '/') path++; ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port, NULL); redo: ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE, &h->interrupt_callback, NULL, h->protocol_whitelist, h->protocol_blacklist, h); if (ret < 0) return ret; authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth, path, "CONNECT"); snprintf(s->buffer, sizeof(s->buffer), "CONNECT %s HTTP/1.1\r\n" "Host: %s\r\n" "Connection: close\r\n" "%s%s" "\r\n", path, hoststr, authstr ? "Proxy-" : "", authstr ? authstr : ""); av_freep(&authstr); if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0) goto fail; s->buf_ptr = s->buffer; s->buf_end = s->buffer; s->line_count = 0; s->filesize = -1; cur_auth_type = s->proxy_auth_state.auth_type; /* Note: This uses buffering, potentially reading more than the * HTTP header. If tunneling a protocol where the server starts * the conversation, we might buffer part of that here, too. * Reading that requires using the proper ffurl_read() function * on this URLContext, not using the fd directly (as the tls * protocol does). This shouldn't be an issue for tls though, * since the client starts the conversation there, so there * is no extra data that we might buffer up here. */ ret = http_read_header(h, &new_loc); if (ret < 0) goto fail; attempts++; if (s->http_code == 407 && (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) && s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) { ffurl_closep(&s->hd); goto redo; } if (s->http_code < 400) return 0; ret = ff_http_averror(s->http_code, AVERROR(EIO)); fail: http_proxy_close(h); return ret; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <paulcher@icloud.com>. CWE ID: CWE-119
1
168,499
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: int ipmi_si_add_smi(struct si_sm_io *io) { int rv = 0; struct smi_info *new_smi, *dup; if (!io->io_setup) { if (io->addr_type == IPMI_IO_ADDR_SPACE) { io->io_setup = ipmi_si_port_setup; } else if (io->addr_type == IPMI_MEM_ADDR_SPACE) { io->io_setup = ipmi_si_mem_setup; } else { return -EINVAL; } } new_smi = kzalloc(sizeof(*new_smi), GFP_KERNEL); if (!new_smi) return -ENOMEM; spin_lock_init(&new_smi->si_lock); new_smi->io = *io; mutex_lock(&smi_infos_lock); dup = find_dup_si(new_smi); if (dup) { if (new_smi->io.addr_source == SI_ACPI && dup->io.addr_source == SI_SMBIOS) { /* We prefer ACPI over SMBIOS. */ dev_info(dup->io.dev, "Removing SMBIOS-specified %s state machine in favor of ACPI\n", si_to_str[new_smi->io.si_type]); cleanup_one_si(dup); } else { dev_info(new_smi->io.dev, "%s-specified %s state machine: duplicate\n", ipmi_addr_src_to_str(new_smi->io.addr_source), si_to_str[new_smi->io.si_type]); rv = -EBUSY; kfree(new_smi); goto out_err; } } pr_info("Adding %s-specified %s state machine\n", ipmi_addr_src_to_str(new_smi->io.addr_source), si_to_str[new_smi->io.si_type]); list_add_tail(&new_smi->link, &smi_infos); if (initialized) rv = try_smi_init(new_smi); out_err: mutex_unlock(&smi_infos_lock); return rv; } Commit Message: ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: stable@vger.kernel.org Reported-by: NuoHan Qiao <qiaonuohan@huawei.com> Suggested-by: Corey Minyard <cminyard@mvista.com> Signed-off-by: Yang Yingliang <yangyingliang@huawei.com> Signed-off-by: Corey Minyard <cminyard@mvista.com> CWE ID: CWE-416
0
90,228
Analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'.
Code: bool AsyncPixelTransfersCompletedQuery::End( base::subtle::Atomic32 submit_count) { AsyncMemoryParams mem_params; Buffer buffer = manager()->decoder()->GetSharedMemoryBuffer(shm_id()); if (!buffer.shared_memory) return false; mem_params.shared_memory = buffer.shared_memory; mem_params.shm_size = buffer.size; mem_params.shm_data_offset = shm_offset(); mem_params.shm_data_size = sizeof(QuerySync); observer_ = new AsyncPixelTransferCompletionObserverImpl(submit_count); manager()->decoder()->GetAsyncPixelTransferManager() ->AsyncNotifyCompletion(mem_params, observer_); return AddToPendingTransferQueue(submit_count); } Commit Message: Add bounds validation to AsyncPixelTransfersCompletedQuery::End BUG=351852 R=jbauman@chromium.org, jorgelo@chromium.org Review URL: https://codereview.chromium.org/198253002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@256723 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
1
171,682