prompt
stringlengths 1.19k
236k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool AXNodeObject::isRequired() const {
Node* n = this->getNode();
if (n && (n->isElementNode() && toElement(n)->isFormControlElement()) &&
hasAttribute(requiredAttr))
return toHTMLFormControlElement(n)->isRequired();
if (equalIgnoringCase(getAttribute(aria_requiredAttr), "true"))
return true;
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
Target: 1
Example 2:
Code: void FrameLoader::setDefersLoading(bool defers)
{
if (m_documentLoader)
m_documentLoader->setDefersLoading(defers);
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->setDefersLoading(defers);
if (m_policyDocumentLoader)
m_policyDocumentLoader->setDefersLoading(defers);
history()->setDefersLoading(defers);
if (!defers) {
m_frame->navigationScheduler()->startTimer();
startCheckCompleteTimer();
}
}
Commit Message: Don't wait to notify client of spoof attempt if a modal dialog is created.
BUG=281256
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/23620020
git-svn-id: svn://svn.chromium.org/blink/trunk@157196 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: videobuf_vm_close(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
struct videobuf_queue *q = map->q;
int i;
dprintk(2,"vm_close %p [count=%d,vma=%08lx-%08lx]\n",map,
map->count,vma->vm_start,vma->vm_end);
map->count--;
if (0 == map->count) {
dprintk(1,"munmap %p q=%p\n",map,q);
mutex_lock(&q->lock);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
if (q->bufs[i]->map != map)
continue;
q->ops->buf_release(q,q->bufs[i]);
q->bufs[i]->map = NULL;
q->bufs[i]->baddr = 0;
}
mutex_unlock(&q->lock);
kfree(map);
}
return;
}
Commit Message: V4L/DVB (6751): V4L: Memory leak! Fix count in videobuf-vmalloc mmap
This is pretty serious bug. map->count is never initialized after the
call to kmalloc making the count start at some random trash value. The
end result is leaking videobufs.
Also, fix up the debug statements to print unsigned values.
Pushed to http://ifup.org/hg/v4l-dvb too
Signed-off-by: Brandon Philips <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = state->regs;
int off, i, slot, spi;
if (regs[regno].type != PTR_TO_STACK) {
/* Allow zero-byte read from NULL, regardless of pointer type */
if (zero_size_allowed && access_size == 0 &&
register_is_null(regs[regno]))
return 0;
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[regs[regno].type],
reg_type_str[PTR_TO_STACK]);
return -EACCES;
}
/* Only allow fixed-offset stack reads */
if (!tnum_is_const(regs[regno].var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off);
verbose(env, "invalid variable stack read R%d var_off=%s\n",
regno, tn_buf);
}
off = regs[regno].off + regs[regno].var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
regno, off, access_size);
return -EACCES;
}
if (env->prog->aux->stack_depth < -off)
env->prog->aux->stack_depth = -off;
if (meta && meta->raw_mode) {
meta->access_size = access_size;
meta->regno = regno;
return 0;
}
for (i = 0; i < access_size; i++) {
slot = -(off + i) - 1;
spi = slot / BPF_REG_SIZE;
if (state->allocated_stack <= slot ||
state->stack[spi].slot_type[slot % BPF_REG_SIZE] !=
STACK_MISC) {
verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
off, i, access_size);
return -EACCES;
}
}
return 0;
}
Commit Message: bpf: fix missing error return in check_stack_boundary()
Prevent indirect stack accesses at non-constant addresses, which would
permit reading and corrupting spilled pointers.
Fixes: f1174f77b50c ("bpf/verifier: rework value tracking")
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static struct mddev *mddev_find(dev_t unit)
{
struct mddev *mddev, *new = NULL;
if (unit && MAJOR(unit) != MD_MAJOR)
unit &= ~((1<<MdpMinorShift)-1);
retry:
spin_lock(&all_mddevs_lock);
if (unit) {
list_for_each_entry(mddev, &all_mddevs, all_mddevs)
if (mddev->unit == unit) {
mddev_get(mddev);
spin_unlock(&all_mddevs_lock);
kfree(new);
return mddev;
}
if (new) {
list_add(&new->all_mddevs, &all_mddevs);
spin_unlock(&all_mddevs_lock);
new->hold_active = UNTIL_IOCTL;
return new;
}
} else if (new) {
/* find an unused unit number */
static int next_minor = 512;
int start = next_minor;
int is_free = 0;
int dev = 0;
while (!is_free) {
dev = MKDEV(MD_MAJOR, next_minor);
next_minor++;
if (next_minor > MINORMASK)
next_minor = 0;
if (next_minor == start) {
/* Oh dear, all in use. */
spin_unlock(&all_mddevs_lock);
kfree(new);
return NULL;
}
is_free = 1;
list_for_each_entry(mddev, &all_mddevs, all_mddevs)
if (mddev->unit == dev) {
is_free = 0;
break;
}
}
new->unit = dev;
new->md_minor = MINOR(dev);
new->hold_active = UNTIL_STOP;
list_add(&new->all_mddevs, &all_mddevs);
spin_unlock(&all_mddevs_lock);
return new;
}
spin_unlock(&all_mddevs_lock);
new = kzalloc(sizeof(*new), GFP_KERNEL);
if (!new)
return NULL;
new->unit = unit;
if (MAJOR(unit) == MD_MAJOR)
new->md_minor = MINOR(unit);
else
new->md_minor = MINOR(unit) >> MdpMinorShift;
mddev_init(new);
goto retry;
}
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 <[email protected]>
Signed-off-by: NeilBrown <[email protected]>
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: error::Error GLES2DecoderPassthroughImpl::DoGetProgramInterfaceiv(
GLuint program,
GLenum program_interface,
GLenum pname,
GLsizei bufsize,
GLsizei* length,
GLint* params) {
if (bufsize < 1) {
return error::kOutOfBounds;
}
*length = 1;
api()->glGetProgramInterfaceivFn(GetProgramServiceID(program, resources_),
program_interface, pname, params);
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int svc_rdma_recvfrom(struct svc_rqst *rqstp)
{
struct svc_xprt *xprt = rqstp->rq_xprt;
struct svcxprt_rdma *rdma_xprt =
container_of(xprt, struct svcxprt_rdma, sc_xprt);
struct svc_rdma_op_ctxt *ctxt = NULL;
struct rpcrdma_msg *rmsgp;
int ret = 0;
dprintk("svcrdma: rqstp=%p\n", rqstp);
spin_lock(&rdma_xprt->sc_rq_dto_lock);
if (!list_empty(&rdma_xprt->sc_read_complete_q)) {
ctxt = list_first_entry(&rdma_xprt->sc_read_complete_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
spin_unlock(&rdma_xprt->sc_rq_dto_lock);
rdma_read_complete(rqstp, ctxt);
goto complete;
} else if (!list_empty(&rdma_xprt->sc_rq_dto_q)) {
ctxt = list_first_entry(&rdma_xprt->sc_rq_dto_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
} else {
atomic_inc(&rdma_stat_rq_starve);
clear_bit(XPT_DATA, &xprt->xpt_flags);
ctxt = NULL;
}
spin_unlock(&rdma_xprt->sc_rq_dto_lock);
if (!ctxt) {
/* This is the EAGAIN path. The svc_recv routine will
* return -EAGAIN, the nfsd thread will go to call into
* svc_recv again and we shouldn't be on the active
* transport list
*/
if (test_bit(XPT_CLOSE, &xprt->xpt_flags))
goto defer;
goto out;
}
dprintk("svcrdma: processing ctxt=%p on xprt=%p, rqstp=%p\n",
ctxt, rdma_xprt, rqstp);
atomic_inc(&rdma_stat_recv);
/* Build up the XDR from the receive buffers. */
rdma_build_arg_xdr(rqstp, ctxt, ctxt->byte_len);
/* Decode the RDMA header. */
rmsgp = (struct rpcrdma_msg *)rqstp->rq_arg.head[0].iov_base;
ret = svc_rdma_xdr_decode_req(&rqstp->rq_arg);
if (ret < 0)
goto out_err;
if (ret == 0)
goto out_drop;
rqstp->rq_xprt_hlen = ret;
if (svc_rdma_is_backchannel_reply(xprt, rmsgp)) {
ret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt, rmsgp,
&rqstp->rq_arg);
svc_rdma_put_context(ctxt, 0);
if (ret)
goto repost;
return ret;
}
/* Read read-list data. */
ret = rdma_read_chunks(rdma_xprt, rmsgp, rqstp, ctxt);
if (ret > 0) {
/* read-list posted, defer until data received from client. */
goto defer;
} else if (ret < 0) {
/* Post of read-list failed, free context. */
svc_rdma_put_context(ctxt, 1);
return 0;
}
complete:
ret = rqstp->rq_arg.head[0].iov_len
+ rqstp->rq_arg.page_len
+ rqstp->rq_arg.tail[0].iov_len;
svc_rdma_put_context(ctxt, 0);
out:
dprintk("svcrdma: ret=%d, rq_arg.len=%u, "
"rq_arg.head[0].iov_base=%p, rq_arg.head[0].iov_len=%zd\n",
ret, rqstp->rq_arg.len,
rqstp->rq_arg.head[0].iov_base,
rqstp->rq_arg.head[0].iov_len);
rqstp->rq_prot = IPPROTO_MAX;
svc_xprt_copy_addrs(rqstp, xprt);
return ret;
out_err:
svc_rdma_send_error(rdma_xprt, rmsgp, ret);
svc_rdma_put_context(ctxt, 0);
return 0;
defer:
return 0;
out_drop:
svc_rdma_put_context(ctxt, 1);
repost:
return svc_rdma_repost_recv(rdma_xprt, GFP_KERNEL);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
Target: 1
Example 2:
Code: static void arcmsr_write_ioctldata2iop_in_DWORD(struct AdapterControlBlock *acb)
{
uint8_t *pQbuffer;
struct QBUFFER __iomem *pwbuffer;
uint8_t *buf1 = NULL;
uint32_t __iomem *iop_data;
uint32_t allxfer_len = 0, data_len, *buf2 = NULL, data;
if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_READED) {
buf1 = kmalloc(128, GFP_ATOMIC);
buf2 = (uint32_t *)buf1;
if (buf1 == NULL)
return;
acb->acb_flags &= (~ACB_F_MESSAGE_WQBUFFER_READED);
pwbuffer = arcmsr_get_iop_wqbuffer(acb);
iop_data = (uint32_t __iomem *)pwbuffer->data;
while ((acb->wqbuf_getIndex != acb->wqbuf_putIndex)
&& (allxfer_len < 124)) {
pQbuffer = &acb->wqbuffer[acb->wqbuf_getIndex];
*buf1 = *pQbuffer;
acb->wqbuf_getIndex++;
acb->wqbuf_getIndex %= ARCMSR_MAX_QBUFFER;
buf1++;
allxfer_len++;
}
data_len = allxfer_len;
buf1 = (uint8_t *)buf2;
while (data_len >= 4) {
data = *buf2++;
writel(data, iop_data);
iop_data++;
data_len -= 4;
}
if (data_len) {
data = *buf2;
writel(data, iop_data);
}
writel(allxfer_len, &pwbuffer->data_len);
kfree(buf1);
arcmsr_iop_message_wrote(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: <[email protected]>
Reported-by: Marco Grassi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: Tomas Henzl <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static const char *perf_etc_perfconfig(void)
{
static const char *system_wide;
if (!system_wide)
system_wide = system_path(ETC_PERFCONFIG);
return system_wide;
}
Commit Message: perf tools: do not look at ./config for configuration
In addition to /etc/perfconfig and $HOME/.perfconfig, perf looks for
configuration in the file ./config, imitating git which looks at
$GIT_DIR/config. If ./config is not a perf configuration file, it
fails, or worse, treats it as a configuration file and changes behavior
in some unexpected way.
"config" is not an unusual name for a file to be lying around and perf
does not have a private directory dedicated for its own use, so let's
just stop looking for configuration in the cwd. Callers needing
context-sensitive configuration can use the PERF_CONFIG environment
variable.
Requested-by: Christian Ohm <[email protected]>
Cc: [email protected]
Cc: Ben Hutchings <[email protected]>
Cc: Christian Ohm <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Paul Mackerras <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Jonathan Nieder <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void dump_mm(const struct mm_struct *mm)
{
pr_emerg("mm %px mmap %px seqnum %d task_size %lu\n"
#ifdef CONFIG_MMU
"get_unmapped_area %px\n"
#endif
"mmap_base %lu mmap_legacy_base %lu highest_vm_end %lu\n"
"pgd %px mm_users %d mm_count %d pgtables_bytes %lu map_count %d\n"
"hiwater_rss %lx hiwater_vm %lx total_vm %lx locked_vm %lx\n"
"pinned_vm %lx data_vm %lx exec_vm %lx stack_vm %lx\n"
"start_code %lx end_code %lx start_data %lx end_data %lx\n"
"start_brk %lx brk %lx start_stack %lx\n"
"arg_start %lx arg_end %lx env_start %lx env_end %lx\n"
"binfmt %px flags %lx core_state %px\n"
#ifdef CONFIG_AIO
"ioctx_table %px\n"
#endif
#ifdef CONFIG_MEMCG
"owner %px "
#endif
"exe_file %px\n"
#ifdef CONFIG_MMU_NOTIFIER
"mmu_notifier_mm %px\n"
#endif
#ifdef CONFIG_NUMA_BALANCING
"numa_next_scan %lu numa_scan_offset %lu numa_scan_seq %d\n"
#endif
"tlb_flush_pending %d\n"
"def_flags: %#lx(%pGv)\n",
mm, mm->mmap, mm->vmacache_seqnum, mm->task_size,
#ifdef CONFIG_MMU
mm->get_unmapped_area,
#endif
mm->mmap_base, mm->mmap_legacy_base, mm->highest_vm_end,
mm->pgd, atomic_read(&mm->mm_users),
atomic_read(&mm->mm_count),
mm_pgtables_bytes(mm),
mm->map_count,
mm->hiwater_rss, mm->hiwater_vm, mm->total_vm, mm->locked_vm,
mm->pinned_vm, mm->data_vm, mm->exec_vm, mm->stack_vm,
mm->start_code, mm->end_code, mm->start_data, mm->end_data,
mm->start_brk, mm->brk, mm->start_stack,
mm->arg_start, mm->arg_end, mm->env_start, mm->env_end,
mm->binfmt, mm->flags, mm->core_state,
#ifdef CONFIG_AIO
mm->ioctx_table,
#endif
#ifdef CONFIG_MEMCG
mm->owner,
#endif
mm->exe_file,
#ifdef CONFIG_MMU_NOTIFIER
mm->mmu_notifier_mm,
#endif
#ifdef CONFIG_NUMA_BALANCING
mm->numa_next_scan, mm->numa_scan_offset, mm->numa_scan_seq,
#endif
atomic_read(&mm->tlb_flush_pending),
mm->def_flags, &mm->def_flags
);
}
Commit Message: mm: get rid of vmacache_flush_all() entirely
Jann Horn points out that the vmacache_flush_all() function is not only
potentially expensive, it's buggy too. It also happens to be entirely
unnecessary, because the sequence number overflow case can be avoided by
simply making the sequence number be 64-bit. That doesn't even grow the
data structures in question, because the other adjacent fields are
already 64-bit.
So simplify the whole thing by just making the sequence number overflow
case go away entirely, which gets rid of all the complications and makes
the code faster too. Win-win.
[ Oleg Nesterov points out that the VMACACHE_FULL_FLUSHES statistics
also just goes away entirely with this ]
Reported-by: Jann Horn <[email protected]>
Suggested-by: Will Deacon <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: void Document::AddConsoleMessage(ConsoleMessage* console_message) {
if (!IsContextThread()) {
PostCrossThreadTask(
*GetTaskRunner(TaskType::kInternalInspector), FROM_HERE,
CrossThreadBind(&RunAddConsoleMessageTask, console_message->Source(),
console_message->Level(), console_message->Message(),
WrapCrossThreadPersistent(this)));
return;
}
if (!frame_)
return;
if (console_message->Location()->IsUnknown()) {
unsigned line_number = 0;
if (!IsInDocumentWrite() && GetScriptableDocumentParser()) {
ScriptableDocumentParser* parser = GetScriptableDocumentParser();
if (parser->IsParsingAtLineNumber())
line_number = parser->LineNumber().OneBasedInt();
}
Vector<DOMNodeId> nodes(console_message->Nodes());
console_message = ConsoleMessage::Create(
console_message->Source(), console_message->Level(),
console_message->Message(),
std::make_unique<SourceLocation>(Url().GetString(), line_number, 0,
nullptr));
console_message->SetNodes(frame_, std::move(nodes));
}
frame_->Console().AddMessage(console_message);
}
Commit Message: Cleanup and remove dead code in SetFocusedElement
This early-out was added in:
https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc
Back then, we applied fragment focus in LayoutUpdated() which could
cause this issue. This got cleaned up in:
https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2
so that focus is no longer applied after layout.
+Cleanup: Goto considered harmful
Bug: 795381
Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417
Commit-Queue: David Bokan <[email protected]>
Reviewed-by: Stefan Zager <[email protected]>
Cr-Commit-Position: refs/heads/master@{#641101}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool csum_and_copy_from_iter_full(void *addr, size_t bytes, __wsum *csum,
struct iov_iter *i)
{
char *to = addr;
__wsum sum, next;
size_t off = 0;
sum = *csum;
if (unlikely(i->type & ITER_PIPE)) {
WARN_ON(1);
return false;
}
if (unlikely(i->count < bytes))
return false;
iterate_all_kinds(i, bytes, v, ({
int err = 0;
next = csum_and_copy_from_user(v.iov_base,
(to += v.iov_len) - v.iov_len,
v.iov_len, 0, &err);
if (err)
return false;
sum = csum_block_add(sum, next, off);
off += v.iov_len;
0;
}), ({
char *p = kmap_atomic(v.bv_page);
next = csum_partial_copy_nocheck(p + v.bv_offset,
(to += v.bv_len) - v.bv_len,
v.bv_len, 0);
kunmap_atomic(p);
sum = csum_block_add(sum, next, off);
off += v.bv_len;
}),({
next = csum_partial_copy_nocheck(v.iov_base,
(to += v.iov_len) - v.iov_len,
v.iov_len, 0);
sum = csum_block_add(sum, next, off);
off += v.iov_len;
})
)
*csum = sum;
iov_iter_advance(i, bytes);
return true;
}
Commit Message: fix a fencepost error in pipe_advance()
The logics in pipe_advance() used to release all buffers past the new
position failed in cases when the number of buffers to release was equal
to pipe->buffers. If that happened, none of them had been released,
leaving pipe full. Worse, it was trivial to trigger and we end up with
pipe full of uninitialized pages. IOW, it's an infoleak.
Cc: [email protected] # v4.9
Reported-by: "Alan J. Wylie" <[email protected]>
Tested-by: "Alan J. Wylie" <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void send(node_t *node, node_t *child, byte *fout) {
if (node->parent) {
send(node->parent, node, fout);
}
if (child) {
if (node->right == child) {
add_bit(1, fout);
} else {
add_bit(0, fout);
}
}
}
Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.
CWE ID: CWE-119
Target: 1
Example 2:
Code: session_unused(int id)
{
debug3("%s: session id %d unused", __func__, id);
if (id >= options.max_sessions ||
id >= sessions_nalloc) {
fatal("%s: insane session id %d (max %d nalloc %d)",
__func__, id, options.max_sessions, sessions_nalloc);
}
memset(&sessions[id], 0, sizeof(*sessions));
sessions[id].self = id;
sessions[id].used = 0;
sessions[id].chanid = -1;
sessions[id].ptyfd = -1;
sessions[id].ttyfd = -1;
sessions[id].ptymaster = -1;
sessions[id].x11_chanids = NULL;
sessions[id].next_unused = sessions_first_unused;
sessions_first_unused = id;
}
Commit Message:
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int get_devices_from_authfile(const char *authfile, const char *username,
unsigned max_devs, int verbose, FILE *debug_file,
device_t *devices, unsigned *n_devs) {
char *buf = NULL;
char *s_user, *s_token;
int retval = 0;
int fd = -1;
struct stat st;
struct passwd *pw = NULL, pw_s;
char buffer[BUFSIZE];
int gpu_ret;
FILE *opwfile = NULL;
unsigned i, j;
/* Ensure we never return uninitialized count. */
*n_devs = 0;
fd = open(authfile, O_RDONLY, 0);
if (fd < 0) {
if (verbose)
D(debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno));
goto err;
}
if (fstat(fd, &st) < 0) {
if (verbose)
D(debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno));
goto err;
}
if (!S_ISREG(st.st_mode)) {
if (verbose)
D(debug_file, "%s is not a regular file", authfile);
goto err;
}
if (st.st_size == 0) {
if (verbose)
D(debug_file, "File %s is empty", authfile);
goto err;
}
gpu_ret = getpwuid_r(st.st_uid, &pw_s, buffer, sizeof(buffer), &pw);
if (gpu_ret != 0 || pw == NULL) {
D(debug_file, "Unable to retrieve credentials for uid %u, (%s)", st.st_uid,
strerror(errno));
goto err;
}
if (strcmp(pw->pw_name, username) != 0 && strcmp(pw->pw_name, "root") != 0) {
if (strcmp(username, "root") != 0) {
D(debug_file, "The owner of the authentication file is neither %s nor root",
username);
} else {
D(debug_file, "The owner of the authentication file is not root");
}
goto err;
}
opwfile = fdopen(fd, "r");
if (opwfile == NULL) {
if (verbose)
D(debug_file, "fdopen: %s", strerror(errno));
goto err;
}
buf = malloc(sizeof(char) * (DEVSIZE * max_devs));
if (!buf) {
if (verbose)
D(debug_file, "Unable to allocate memory");
goto err;
}
retval = -2;
while (fgets(buf, (int)(DEVSIZE * (max_devs - 1)), opwfile)) {
char *saveptr = NULL;
if (buf[strlen(buf) - 1] == '\n')
buf[strlen(buf) - 1] = '\0';
if (verbose)
D(debug_file, "Authorization line: %s", buf);
s_user = strtok_r(buf, ":", &saveptr);
if (s_user && strcmp(username, s_user) == 0) {
if (verbose)
D(debug_file, "Matched user: %s", s_user);
retval = -1; // We found at least one line for the user
for (i = 0; i < *n_devs; i++) {
free(devices[i].keyHandle);
free(devices[i].publicKey);
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
}
*n_devs = 0;
i = 0;
while ((s_token = strtok_r(NULL, ",", &saveptr))) {
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
if ((*n_devs)++ > MAX_DEVS - 1) {
*n_devs = MAX_DEVS;
if (verbose)
D(debug_file, "Found more than %d devices, ignoring the remaining ones",
MAX_DEVS);
break;
}
if (verbose)
D(debug_file, "KeyHandle for device number %d: %s", i + 1, s_token);
devices[i].keyHandle = strdup(s_token);
if (!devices[i].keyHandle) {
if (verbose)
D(debug_file, "Unable to allocate memory for keyHandle number %d", i);
goto err;
}
s_token = strtok_r(NULL, ":", &saveptr);
if (!s_token) {
if (verbose)
D(debug_file, "Unable to retrieve publicKey number %d", i + 1);
goto err;
}
if (verbose)
D(debug_file, "publicKey for device number %d: %s", i + 1, s_token);
if (strlen(s_token) % 2 != 0) {
if (verbose)
D(debug_file, "Length of key number %d not even", i + 1);
goto err;
}
devices[i].key_len = strlen(s_token) / 2;
if (verbose)
D(debug_file, "Length of key number %d is %zu", i + 1, devices[i].key_len);
devices[i].publicKey =
malloc((sizeof(unsigned char) * devices[i].key_len));
if (!devices[i].publicKey) {
if (verbose)
D(debug_file, "Unable to allocate memory for publicKey number %d", i);
goto err;
}
for (j = 0; j < devices[i].key_len; j++) {
unsigned int x;
if (sscanf(&s_token[2 * j], "%2x", &x) != 1) {
if (verbose)
D(debug_file, "Invalid hex number in key");
goto err;
}
devices[i].publicKey[j] = (unsigned char)x;
}
i++;
}
}
}
if (verbose)
D(debug_file, "Found %d device(s) for user %s", *n_devs, username);
retval = 1;
goto out;
err:
for (i = 0; i < *n_devs; i++) {
free(devices[i].keyHandle);
free(devices[i].publicKey);
devices[i].keyHandle = NULL;
devices[i].publicKey = NULL;
}
*n_devs = 0;
out:
if (buf) {
free(buf);
buf = NULL;
}
if (opwfile)
fclose(opwfile);
else if (fd >= 0)
close(fd);
return retval;
}
Commit Message: Do not leak file descriptor when doing exec
When opening a custom debug file, the descriptor would stay
open when calling exec and leak to the child process.
Make sure all files are opened with close-on-exec.
This fixes CVE-2019-12210.
Thanks to Matthias Gerstner of the SUSE Security Team for reporting
the issue.
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int Equalizer_getParameter(EffectContext *pContext,
void *pParam,
uint32_t *pValueSize,
void *pValue){
int status = 0;
int bMute = 0;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
int32_t param2;
char *name;
switch (param) {
case EQ_PARAM_NUM_BANDS:
case EQ_PARAM_CUR_PRESET:
case EQ_PARAM_GET_NUM_OF_PRESETS:
case EQ_PARAM_BAND_LEVEL:
case EQ_PARAM_GET_BAND:
if (*pValueSize < sizeof(int16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int16_t);
break;
case EQ_PARAM_LEVEL_RANGE:
if (*pValueSize < 2 * sizeof(int16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 2 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = 2 * sizeof(int16_t);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
if (*pValueSize < 2 * sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 3 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = 2 * sizeof(int32_t);
break;
case EQ_PARAM_CENTER_FREQ:
if (*pValueSize < sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 5 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int32_t);
break;
case EQ_PARAM_GET_PRESET_NAME:
break;
case EQ_PARAM_PROPERTIES:
if (*pValueSize < (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t);
break;
default:
ALOGV("\tLVM_ERROR : Equalizer_getParameter unknown param %d", param);
return -EINVAL;
}
switch (param) {
case EQ_PARAM_NUM_BANDS:
*(uint16_t *)pValue = (uint16_t)FIVEBAND_NUMBANDS;
break;
case EQ_PARAM_LEVEL_RANGE:
*(int16_t *)pValue = -1500;
*((int16_t *)pValue + 1) = 1500;
break;
case EQ_PARAM_BAND_LEVEL:
param2 = *pParamTemp;
if (param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
*(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, param2);
break;
case EQ_PARAM_CENTER_FREQ:
param2 = *pParamTemp;
if (param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
*(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, param2);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
param2 = *pParamTemp;
if (param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
EqualizerGetBandFreqRange(pContext, param2, (uint32_t *)pValue, ((uint32_t *)pValue + 1));
break;
case EQ_PARAM_GET_BAND:
param2 = *pParamTemp;
*(uint16_t *)pValue = (uint16_t)EqualizerGetBand(pContext, param2);
break;
case EQ_PARAM_CUR_PRESET:
*(uint16_t *)pValue = (uint16_t)EqualizerGetPreset(pContext);
break;
case EQ_PARAM_GET_NUM_OF_PRESETS:
*(uint16_t *)pValue = (uint16_t)EqualizerGetNumPresets();
break;
case EQ_PARAM_GET_PRESET_NAME:
param2 = *pParamTemp;
if (param2 >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
name = (char *)pValue;
strncpy(name, EqualizerGetPresetName(param2), *pValueSize - 1);
name[*pValueSize - 1] = 0;
*pValueSize = strlen(name) + 1;
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
ALOGV("\tEqualizer_getParameter() EQ_PARAM_PROPERTIES");
p[0] = (int16_t)EqualizerGetPreset(pContext);
p[1] = (int16_t)FIVEBAND_NUMBANDS;
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i);
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_getParameter */
int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int32_t preset;
int32_t band;
int32_t level;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param) {
case EQ_PARAM_CUR_PRESET:
preset = (int32_t)(*(uint16_t *)pValue);
if ((preset >= EqualizerGetNumPresets())||(preset < 0)) {
status = -EINVAL;
break;
}
EqualizerSetPreset(pContext, preset);
break;
case EQ_PARAM_BAND_LEVEL:
band = *pParamTemp;
level = (int32_t)(*(int16_t *)pValue);
if (band >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
EqualizerSetBandLevel(pContext, band, level);
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
if ((int)p[0] >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
if (p[0] >= 0) {
EqualizerSetPreset(pContext, (int)p[0]);
} else {
if ((int)p[1] != FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
}
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_setParameter */
int Volume_getParameter(EffectContext *pContext,
void *pParam,
uint32_t *pValueSize,
void *pValue){
int status = 0;
int bMute = 0;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;;
char *name;
switch (param){
case VOLUME_PARAM_LEVEL:
case VOLUME_PARAM_MAXLEVEL:
case VOLUME_PARAM_STEREOPOSITION:
if (*pValueSize != sizeof(int16_t)){
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int16_t);
break;
case VOLUME_PARAM_MUTE:
case VOLUME_PARAM_ENABLESTEREOPOSITION:
if (*pValueSize < sizeof(int32_t)){
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 2 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int32_t);
break;
default:
ALOGV("\tLVM_ERROR : Volume_getParameter unknown param %d", param);
return -EINVAL;
}
switch (param){
case VOLUME_PARAM_LEVEL:
status = VolumeGetVolumeLevel(pContext, (int16_t *)(pValue));
break;
case VOLUME_PARAM_MAXLEVEL:
*(int16_t *)pValue = 0;
break;
case VOLUME_PARAM_STEREOPOSITION:
VolumeGetStereoPosition(pContext, (int16_t *)pValue);
break;
case VOLUME_PARAM_MUTE:
status = VolumeGetMute(pContext, (uint32_t *)pValue);
ALOGV("\tVolume_getParameter() VOLUME_PARAM_MUTE Value is %d",
*(uint32_t *)pValue);
break;
case VOLUME_PARAM_ENABLESTEREOPOSITION:
*(int32_t *)pValue = pContext->pBundledContext->bStereoPositionEnabled;
break;
default:
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Volume_getParameter */
int Volume_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int16_t level;
int16_t position;
uint32_t mute;
uint32_t positionEnabled;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param){
case VOLUME_PARAM_LEVEL:
level = *(int16_t *)pValue;
status = VolumeSetVolumeLevel(pContext, (int16_t)level);
break;
case VOLUME_PARAM_MUTE:
mute = *(uint32_t *)pValue;
status = VolumeSetMute(pContext, mute);
break;
case VOLUME_PARAM_ENABLESTEREOPOSITION:
positionEnabled = *(uint32_t *)pValue;
status = VolumeEnableStereoPosition(pContext, positionEnabled);
status = VolumeSetStereoPosition(pContext, pContext->pBundledContext->positionSaved);
break;
case VOLUME_PARAM_STEREOPOSITION:
position = *(int16_t *)pValue;
status = VolumeSetStereoPosition(pContext, (int16_t)position);
break;
default:
ALOGV("\tLVM_ERROR : Volume_setParameter() invalid param %d", param);
break;
}
return status;
} /* end Volume_setParameter */
/****************************************************************************************
* Name : LVC_ToDB_s32Tos16()
* Input : Signed 32-bit integer
* Output : Signed 16-bit integer
* MSB (16) = sign bit
* (15->05) = integer part
* (04->01) = decimal part
* Returns : Db value with respect to full scale
* Description :
* Remarks :
****************************************************************************************/
LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix)
{
LVM_INT16 db_fix;
LVM_INT16 Shift;
LVM_INT16 SmallRemainder;
LVM_UINT32 Remainder = (LVM_UINT32)Lin_fix;
/* Count leading bits, 1 cycle in assembly*/
for (Shift = 0; Shift<32; Shift++)
{
if ((Remainder & 0x80000000U)!=0)
{
break;
}
Remainder = Remainder << 1;
}
/*
* Based on the approximation equation (for Q11.4 format):
*
* dB = -96 * Shift + 16 * (8 * Remainder - 2 * Remainder^2)
*/
db_fix = (LVM_INT16)(-96 * Shift); /* Six dB steps in Q11.4 format*/
SmallRemainder = (LVM_INT16)((Remainder & 0x7fffffff) >> 24);
db_fix = (LVM_INT16)(db_fix + SmallRemainder );
SmallRemainder = (LVM_INT16)(SmallRemainder * SmallRemainder);
db_fix = (LVM_INT16)(db_fix - (LVM_INT16)((LVM_UINT16)SmallRemainder >> 9));
/* Correct for small offset */
db_fix = (LVM_INT16)(db_fix - 5);
return db_fix;
}
int Effect_setEnabled(EffectContext *pContext, bool enabled)
{
ALOGV("\tEffect_setEnabled() type %d, enabled %d", pContext->EffectType, enabled);
if (enabled) {
bool tempDisabled = false;
switch (pContext->EffectType) {
case LVM_BASS_BOOST:
if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountBb <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountBb =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bBassEnabled = LVM_TRUE;
tempDisabled = pContext->pBundledContext->bBassTempDisabled;
break;
case LVM_EQUALIZER:
if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountEq <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountEq =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bEqualizerEnabled = LVM_TRUE;
break;
case LVM_VIRTUALIZER:
if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountVirt <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountVirt =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bVirtualizerEnabled = LVM_TRUE;
tempDisabled = pContext->pBundledContext->bVirtualizerTempDisabled;
break;
case LVM_VOLUME:
if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_VOLUME is already enabled");
return -EINVAL;
}
pContext->pBundledContext->NumberEffectsEnabled++;
pContext->pBundledContext->bVolumeEnabled = LVM_TRUE;
break;
default:
ALOGV("\tEffect_setEnabled() invalid effect type");
return -EINVAL;
}
if (!tempDisabled) {
LvmEffect_enable(pContext);
}
} else {
switch (pContext->EffectType) {
case LVM_BASS_BOOST:
if (pContext->pBundledContext->bBassEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bBassEnabled = LVM_FALSE;
break;
case LVM_EQUALIZER:
if (pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE;
break;
case LVM_VIRTUALIZER:
if (pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE;
break;
case LVM_VOLUME:
if (pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_VOLUME is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bVolumeEnabled = LVM_FALSE;
break;
default:
ALOGV("\tEffect_setEnabled() invalid effect type");
return -EINVAL;
}
LvmEffect_disable(pContext);
}
return 0;
}
int16_t LVC_Convert_VolToDb(uint32_t vol){
int16_t dB;
dB = LVC_ToDB_s32Tos16(vol <<7);
dB = (dB +8)>>4;
dB = (dB <-96) ? -96 : dB ;
return dB;
}
} // namespace
Commit Message: Fix security vulnerability: Equalizer command might allow negative indexes
Bug: 32247948
Bug: 32438598
Bug: 32436341
Test: use POC on bug or cts security test
Change-Id: I91bd6aadb6c7410163e03101f365db767f4cd2a3
(cherry picked from commit 0872b65cff9129633471945431b9a5a28418049c)
(cherry picked from commit e981cca9fff3608af22bdf8fc1acef5470e25663)
CWE ID: CWE-200
Target: 1
Example 2:
Code: nautilus_metadata_get_id (const char *metadata)
{
static GHashTable *hash;
int i;
if (hash == NULL)
{
hash = g_hash_table_new (g_str_hash, g_str_equal);
for (i = 0; used_metadata_names[i] != NULL; i++)
{
g_hash_table_insert (hash,
used_metadata_names[i],
GINT_TO_POINTER (i + 1));
}
}
return GPOINTER_TO_INT (g_hash_table_lookup (hash, metadata));
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int chmd_fast_find(struct mschm_decompressor *base,
struct mschmd_header *chm, const char *filename,
struct mschmd_file *f_ptr, int f_size)
{
struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base;
struct mspack_system *sys;
struct mspack_file *fh;
const unsigned char *chunk, *p, *end;
int err = MSPACK_ERR_OK, result = -1;
unsigned int n, sec;
if (!self || !chm || !f_ptr || (f_size != sizeof(struct mschmd_file))) {
return MSPACK_ERR_ARGS;
}
sys = self->system;
/* clear the results structure */
memset(f_ptr, 0, f_size);
if (!(fh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ))) {
return MSPACK_ERR_OPEN;
}
/* go through PMGI chunk hierarchy to reach PMGL chunk */
if (chm->index_root < chm->num_chunks) {
n = chm->index_root;
for (;;) {
if (!(chunk = read_chunk(self, chm, fh, n))) {
sys->close(fh);
return self->error;
}
/* search PMGI/PMGL chunk. exit early if no entry found */
if ((result = search_chunk(chm, chunk, filename, &p, &end)) <= 0) {
break;
}
/* found result. loop around for next chunk if this is PMGI */
if (chunk[3] == 0x4C) break; else READ_ENCINT(n);
}
}
else {
/* PMGL chunks only, search from first_pmgl to last_pmgl */
for (n = chm->first_pmgl; n <= chm->last_pmgl;
n = EndGetI32(&chunk[pmgl_NextChunk]))
{
if (!(chunk = read_chunk(self, chm, fh, n))) {
err = self->error;
break;
}
/* search PMGL chunk. exit if file found */
if ((result = search_chunk(chm, chunk, filename, &p, &end)) > 0) {
break;
}
/* stop simple infinite loops: can't visit the same chunk twice */
if ((int)n == EndGetI32(&chunk[pmgl_NextChunk])) {
break;
}
}
}
/* if we found a file, read it */
if (result > 0) {
READ_ENCINT(sec);
f_ptr->section = (sec == 0) ? (struct mschmd_section *) &chm->sec0
: (struct mschmd_section *) &chm->sec1;
READ_ENCINT(f_ptr->offset);
READ_ENCINT(f_ptr->length);
}
else if (result < 0) {
err = MSPACK_ERR_DATAFORMAT;
}
sys->close(fh);
return self->error = err;
chunk_end:
D(("read beyond end of chunk entries"))
sys->close(fh);
return self->error = MSPACK_ERR_DATAFORMAT;
}
Commit Message: Avoid returning CHM file entries that are "blank" because they have embedded null bytes
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
return ret;
}
Commit Message: fs: prevent page refcount overflow in pipe_buf_get
Change pipe_buf_get() to return a bool indicating whether it succeeded
in raising the refcount of the page (if the thing in the pipe is a page).
This removes another mechanism for overflowing the page refcount. All
callers converted to handle a failure.
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Matthew Wilcox <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: static struct fib6_node * fib6_lookup_1(struct fib6_node *root,
struct lookup_args *args)
{
struct fib6_node *fn;
__be32 dir;
if (unlikely(args->offset == 0))
return NULL;
/*
* Descend on a tree
*/
fn = root;
for (;;) {
struct fib6_node *next;
dir = addr_bit_set(args->addr, fn->fn_bit);
next = dir ? fn->right : fn->left;
if (next) {
fn = next;
continue;
}
break;
}
while (fn) {
if (FIB6_SUBTREE(fn) || fn->fn_flags & RTN_RTINFO) {
struct rt6key *key;
key = (struct rt6key *) ((u8 *) fn->leaf +
args->offset);
if (ipv6_prefix_equal(&key->addr, args->addr, key->plen)) {
#ifdef CONFIG_IPV6_SUBTREES
if (fn->subtree)
fn = fib6_lookup_1(fn->subtree, args + 1);
#endif
if (!fn || fn->fn_flags & RTN_RTINFO)
return fn;
}
}
if (fn->fn_flags & RTN_ROOT)
break;
fn = fn->parent;
}
return NULL;
}
Commit Message: ipv6: only static routes qualify for equal cost multipathing
Static routes in this case are non-expiring routes which did not get
configured by autoconf or by icmpv6 redirects.
To make sure we actually get an ecmp route while searching for the first
one in this fib6_node's leafs, also make sure it matches the ecmp route
assumptions.
v2:
a) Removed RTF_EXPIRE check in dst.from chain. The check of RTF_ADDRCONF
already ensures that this route, even if added again without
RTF_EXPIRES (in case of a RA announcement with infinite timeout),
does not cause the rt6i_nsiblings logic to go wrong if a later RA
updates the expiration time later.
v3:
a) Allow RTF_EXPIRES routes to enter the ecmp route set. We have to do so,
because an pmtu event could update the RTF_EXPIRES flag and we would
not count this route, if another route joins this set. We now filter
only for RTF_GATEWAY|RTF_ADDRCONF|RTF_DYNAMIC, which are flags that
don't get changed after rt6_info construction.
Cc: Nicolas Dichtel <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static long long ustime(void) {
struct timeval tv;
long long ust;
gettimeofday(&tv, NULL);
ust = ((long long)tv.tv_sec)*1000000;
ust += tv.tv_usec;
return ust;
}
Commit Message: Security: fix redis-cli buffer overflow.
Thanks to Fakhri Zulkifli for reporting it.
The fix switched to dynamic allocation, copying the final prompt in the
static buffer only at the end.
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,
const struct assoc_array_ops *ops,
const void *index_key,
struct assoc_array_walk_result *result)
{
struct assoc_array_shortcut *shortcut, *new_s0;
struct assoc_array_node *node, *new_n0, *new_n1, *side;
struct assoc_array_ptr *ptr;
unsigned long dissimilarity, base_seg, blank;
size_t keylen;
bool have_meta;
int level, diff;
int slot, next_slot, free_slot, i, j;
node = result->terminal_node.node;
level = result->terminal_node.level;
edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot;
pr_devel("-->%s()\n", __func__);
/* We arrived at a node which doesn't have an onward node or shortcut
* pointer that we have to follow. This means that (a) the leaf we
* want must go here (either by insertion or replacement) or (b) we
* need to split this node and insert in one of the fragments.
*/
free_slot = -1;
/* Firstly, we have to check the leaves in this node to see if there's
* a matching one we should replace in place.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (!ptr) {
free_slot = i;
continue;
}
if (ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) {
pr_devel("replace in slot %d\n", i);
edit->leaf_p = &node->slots[i];
edit->dead_leaf = node->slots[i];
pr_devel("<--%s() = ok [replace]\n", __func__);
return true;
}
}
/* If there is a free slot in this node then we can just insert the
* leaf here.
*/
if (free_slot >= 0) {
pr_devel("insert in free slot %d\n", free_slot);
edit->leaf_p = &node->slots[free_slot];
edit->adjust_count_on = node;
pr_devel("<--%s() = ok [insert]\n", __func__);
return true;
}
/* The node has no spare slots - so we're either going to have to split
* it or insert another node before it.
*
* Whatever, we're going to need at least two new nodes - so allocate
* those now. We may also need a new shortcut, but we deal with that
* when we need it.
*/
new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n0)
return false;
edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n1)
return false;
edit->new_meta[1] = assoc_array_node_to_ptr(new_n1);
/* We need to find out how similar the leaves are. */
pr_devel("no spare slots\n");
have_meta = false;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (assoc_array_ptr_is_meta(ptr)) {
edit->segment_cache[i] = 0xff;
have_meta = true;
continue;
}
base_seg = ops->get_object_key_chunk(
assoc_array_ptr_to_leaf(ptr), level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
}
if (have_meta) {
pr_devel("have meta\n");
goto split_node;
}
/* The node contains only leaves */
dissimilarity = 0;
base_seg = edit->segment_cache[0];
for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++)
dissimilarity |= edit->segment_cache[i] ^ base_seg;
pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity);
if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) {
/* The old leaves all cluster in the same slot. We will need
* to insert a shortcut if the new node wants to cluster with them.
*/
if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)
goto all_leaves_cluster_together;
/* Otherwise we can just insert a new node ahead of the old
* one.
*/
goto present_leaves_cluster_but_not_new_leaf;
}
split_node:
pr_devel("split node\n");
/* We need to split the current node; we know that the node doesn't
* simply contain a full set of leaves that cluster together (it
* contains meta pointers and/or non-clustering leaves).
*
* We need to expel at least two leaves out of a set consisting of the
* leaves in the node and the new leaf.
*
* We need a new node (n0) to replace the current one and a new node to
* take the expelled nodes (n1).
*/
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = -1; /* Need to calculate this */
do_split_node:
pr_devel("do_split_node\n");
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
new_n1->nr_leaves_on_branch = 0;
/* Begin by finding two matching leaves. There have to be at least two
* that match - even if there are meta pointers - because any leaf that
* would match a slot with a meta pointer in it must be somewhere
* behind that meta pointer and cannot be here. Further, given N
* remaining leaf slots, we now have N+1 leaves to go in them.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
slot = edit->segment_cache[i];
if (slot != 0xff)
for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++)
if (edit->segment_cache[j] == slot)
goto found_slot_for_multiple_occupancy;
}
found_slot_for_multiple_occupancy:
pr_devel("same slot: %x %x [%02x]\n", i, j, slot);
BUG_ON(i >= ASSOC_ARRAY_FAN_OUT);
BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1);
BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT);
new_n1->parent_slot = slot;
/* Metadata pointers cannot change slot */
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
if (assoc_array_ptr_is_meta(node->slots[i]))
new_n0->slots[i] = node->slots[i];
else
new_n0->slots[i] = NULL;
BUG_ON(new_n0->slots[slot] != NULL);
new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1);
/* Filter the leaf pointers between the new nodes */
free_slot = -1;
next_slot = 0;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
if (assoc_array_ptr_is_meta(node->slots[i]))
continue;
if (edit->segment_cache[i] == slot) {
new_n1->slots[next_slot++] = node->slots[i];
new_n1->nr_leaves_on_branch++;
} else {
do {
free_slot++;
} while (new_n0->slots[free_slot] != NULL);
new_n0->slots[free_slot] = node->slots[i];
}
}
pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot);
if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {
do {
free_slot++;
} while (new_n0->slots[free_slot] != NULL);
edit->leaf_p = &new_n0->slots[free_slot];
edit->adjust_count_on = new_n0;
} else {
edit->leaf_p = &new_n1->slots[next_slot++];
edit->adjust_count_on = new_n1;
}
BUG_ON(next_slot <= 1);
edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0);
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
if (edit->segment_cache[i] == 0xff) {
ptr = node->slots[i];
BUG_ON(assoc_array_ptr_is_leaf(ptr));
if (assoc_array_ptr_is_node(ptr)) {
side = assoc_array_ptr_to_node(ptr);
edit->set_backpointers[i] = &side->back_pointer;
} else {
shortcut = assoc_array_ptr_to_shortcut(ptr);
edit->set_backpointers[i] = &shortcut->back_pointer;
}
}
}
ptr = node->back_pointer;
if (!ptr)
edit->set[0].ptr = &edit->array->root;
else if (assoc_array_ptr_is_node(ptr))
edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot];
else
edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node;
edit->excised_meta[0] = assoc_array_node_to_ptr(node);
pr_devel("<--%s() = ok [split node]\n", __func__);
return true;
present_leaves_cluster_but_not_new_leaf:
/* All the old leaves cluster in the same slot, but the new leaf wants
* to go into a different slot, so we create a new node to hold the new
* leaf and a pointer to a new node holding all the old leaves.
*/
pr_devel("present leaves cluster but not new leaf\n");
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = edit->segment_cache[0];
new_n1->nr_leaves_on_branch = node->nr_leaves_on_branch;
edit->adjust_count_on = new_n0;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
new_n1->slots[i] = node->slots[i];
new_n0->slots[edit->segment_cache[0]] = assoc_array_node_to_ptr(new_n0);
edit->leaf_p = &new_n0->slots[edit->segment_cache[ASSOC_ARRAY_FAN_OUT]];
edit->set[0].ptr = &assoc_array_ptr_to_node(node->back_pointer)->slots[node->parent_slot];
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
edit->excised_meta[0] = assoc_array_node_to_ptr(node);
pr_devel("<--%s() = ok [insert node before]\n", __func__);
return true;
all_leaves_cluster_together:
/* All the leaves, new and old, want to cluster together in this node
* in the same slot, so we have to replace this node with a shortcut to
* skip over the identical parts of the key and then place a pair of
* nodes, one inside the other, at the end of the shortcut and
* distribute the keys between them.
*
* Firstly we need to work out where the leaves start diverging as a
* bit position into their keys so that we know how big the shortcut
* needs to be.
*
* We only need to make a single pass of N of the N+1 leaves because if
* any keys differ between themselves at bit X then at least one of
* them must also differ with the base key at bit X or before.
*/
pr_devel("all leaves cluster together\n");
diff = INT_MAX;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]),
index_key);
if (x < diff) {
BUG_ON(x < 0);
diff = x;
}
}
BUG_ON(diff == INT_MAX);
BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP);
keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long), GFP_KERNEL);
if (!new_s0)
return false;
edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0);
edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
new_s0->back_pointer = node->back_pointer;
new_s0->parent_slot = node->parent_slot;
new_s0->next_node = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
new_n0->parent_slot = 0;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = -1; /* Need to calculate this */
new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK;
pr_devel("skip_to_level = %d [diff %d]\n", level, diff);
BUG_ON(level <= 0);
for (i = 0; i < keylen; i++)
new_s0->index_key[i] =
ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);
blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank);
new_s0->index_key[keylen - 1] &= ~blank;
/* This now reduces to a node splitting exercise for which we'll need
* to regenerate the disparity table.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr),
level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
}
base_seg = ops->get_key_chunk(index_key, level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK;
goto do_split_node;
}
Commit Message: assoc_array: don't call compare_object() on a node
Changes since V1: fixed the description and added KASan warning.
In assoc_array_insert_into_terminal_node(), we call the
compare_object() method on all non-empty slots, even when they're
not leaves, passing a pointer to an unexpected structure to
compare_object(). Currently it causes an out-of-bound read access
in keyring_compare_object detected by KASan (see below). The issue
is easily reproduced with keyutils testsuite.
Only call compare_object() when the slot is a leave.
KASan warning:
==================================================================
BUG: KASAN: slab-out-of-bounds in keyring_compare_object+0x213/0x240 at addr ffff880060a6f838
Read of size 8 by task keyctl/1655
=============================================================================
BUG kmalloc-192 (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in assoc_array_insert+0xfd0/0x3a60 age=69 cpu=1 pid=1647
___slab_alloc+0x563/0x5c0
__slab_alloc+0x51/0x90
kmem_cache_alloc_trace+0x263/0x300
assoc_array_insert+0xfd0/0x3a60
__key_link_begin+0xfc/0x270
key_create_or_update+0x459/0xaf0
SyS_add_key+0x1ba/0x350
entry_SYSCALL_64_fastpath+0x12/0x76
INFO: Slab 0xffffea0001829b80 objects=16 used=8 fp=0xffff880060a6f550 flags=0x3fff8000004080
INFO: Object 0xffff880060a6f740 @offset=5952 fp=0xffff880060a6e5d1
Bytes b4 ffff880060a6f730: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
Object ffff880060a6f740: d1 e5 a6 60 00 88 ff ff 0e 00 00 00 00 00 00 00 ...`............
Object ffff880060a6f750: 02 cf 8e 60 00 88 ff ff 02 c0 8e 60 00 88 ff ff ...`.......`....
Object ffff880060a6f760: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
Object ffff880060a6f770: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
Object ffff880060a6f780: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
Object ffff880060a6f790: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
Object ffff880060a6f7a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
Object ffff880060a6f7b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
Object ffff880060a6f7c0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
Object ffff880060a6f7d0: 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
Object ffff880060a6f7e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
Object ffff880060a6f7f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
CPU: 0 PID: 1655 Comm: keyctl Tainted: G B 4.5.0-rc4-kasan+ #291
Hardware name: Bochs Bochs, BIOS Bochs 01/01/2011
0000000000000000 000000001b2800b4 ffff880060a179e0 ffffffff81b60491
ffff88006c802900 ffff880060a6f740 ffff880060a17a10 ffffffff815e2969
ffff88006c802900 ffffea0001829b80 ffff880060a6f740 ffff880060a6e650
Call Trace:
[<ffffffff81b60491>] dump_stack+0x85/0xc4
[<ffffffff815e2969>] print_trailer+0xf9/0x150
[<ffffffff815e9454>] object_err+0x34/0x40
[<ffffffff815ebe50>] kasan_report_error+0x230/0x550
[<ffffffff819949be>] ? keyring_get_key_chunk+0x13e/0x210
[<ffffffff815ec62d>] __asan_report_load_n_noabort+0x5d/0x70
[<ffffffff81994cc3>] ? keyring_compare_object+0x213/0x240
[<ffffffff81994cc3>] keyring_compare_object+0x213/0x240
[<ffffffff81bc238c>] assoc_array_insert+0x86c/0x3a60
[<ffffffff81bc1b20>] ? assoc_array_cancel_edit+0x70/0x70
[<ffffffff8199797d>] ? __key_link_begin+0x20d/0x270
[<ffffffff8199786c>] __key_link_begin+0xfc/0x270
[<ffffffff81993389>] key_create_or_update+0x459/0xaf0
[<ffffffff8128ce0d>] ? trace_hardirqs_on+0xd/0x10
[<ffffffff81992f30>] ? key_type_lookup+0xc0/0xc0
[<ffffffff8199e19d>] ? lookup_user_key+0x13d/0xcd0
[<ffffffff81534763>] ? memdup_user+0x53/0x80
[<ffffffff819983ea>] SyS_add_key+0x1ba/0x350
[<ffffffff81998230>] ? key_get_type_from_user.constprop.6+0xa0/0xa0
[<ffffffff828bcf4e>] ? retint_user+0x18/0x23
[<ffffffff8128cc7e>] ? trace_hardirqs_on_caller+0x3fe/0x580
[<ffffffff81004017>] ? trace_hardirqs_on_thunk+0x17/0x19
[<ffffffff828bc432>] entry_SYSCALL_64_fastpath+0x12/0x76
Memory state around the buggy address:
ffff880060a6f700: fc fc fc fc fc fc fc fc 00 00 00 00 00 00 00 00
ffff880060a6f780: 00 00 00 00 00 00 00 00 00 00 00 fc fc fc fc fc
>ffff880060a6f800: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
^
ffff880060a6f880: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffff880060a6f900: fc fc fc fc fc fc 00 00 00 00 00 00 00 00 00 00
==================================================================
Signed-off-by: Jerome Marchand <[email protected]>
Signed-off-by: David Howells <[email protected]>
cc: [email protected]
CWE ID: CWE-125
Target: 1
Example 2:
Code: Sampler* CreateSampler(
GLuint client_id, GLuint service_id) {
return sampler_manager()->CreateSampler(client_id, service_id);
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ChromeClientImpl::popupClosed(WebCore::PopupContainer* popupContainer)
{
m_webView->popupClosed(popupContainer);
}
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::string ExtensionTtsPlatformImpl::error() {
return error_;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 1
Example 2:
Code: write_and_read_gimp_2_8_format (gconstpointer data)
{
Gimp *gimp = GIMP (data);
gimp_write_and_read_file (gimp,
FALSE /*with_unusual_stuff*/,
FALSE /*compat_paths*/,
TRUE /*use_gimp_2_8_features*/);
}
Commit Message: Issue #1689: create unique temporary file with g_file_open_tmp().
Not sure this is really solving the issue reported, which is that
`g_get_tmp_dir()` uses environment variables (yet as g_file_open_tmp()
uses g_get_tmp_dir()…). But at least g_file_open_tmp() should create
unique temporary files, which prevents overriding existing files (which
is most likely the only real attack possible here, or at least the only
one I can think of unless some weird vulnerabilities exist in glib).
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool AudioFlinger::EffectModule::purgeHandles()
{
bool enabled = false;
Mutex::Autolock _l(mLock);
for (size_t i = 0; i < mHandles.size(); i++) {
EffectHandle *handle = mHandles[i];
if (handle != NULL && !handle->destroyed_l()) {
handle->effect().clear();
if (handle->hasControl()) {
enabled = handle->enabled();
}
}
}
return enabled;
}
Commit Message: Add EFFECT_CMD_SET_PARAM parameter checking
Bug: 30204301
Change-Id: Ib9c3ee1c2f23c96f8f7092dd9e146bc453d7a290
(cherry picked from commit e4a1d91501d47931dbae19c47815952378787ab6)
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ScrollHitTestDisplayItem::PropertiesAsJSON(JSONObject& json) const {
DisplayItem::PropertiesAsJSON(json);
json.SetString("scrollOffsetNode",
String::Format("%p", scroll_offset_node_.get()));
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID:
Target: 1
Example 2:
Code: static Handle<FixedArray> CreateListFromArrayImpl(Isolate* isolate,
Handle<JSArray> array) {
UNREACHABLE();
return Handle<FixedArray>();
}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PlatformSensorProviderWin::SensorReaderCreated(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback,
std::unique_ptr<PlatformSensorReaderWin> sensor_reader) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (!sensor_reader) {
callback.Run(nullptr);
return;
}
scoped_refptr<PlatformSensor> sensor = new PlatformSensorWin(
type, std::move(mapping), this, sensor_thread_->task_runner(),
std::move(sensor_reader));
callback.Run(sensor);
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int em_sysenter(struct x86_emulate_ctxt *ctxt)
{
const struct x86_emulate_ops *ops = ctxt->ops;
struct desc_struct cs, ss;
u64 msr_data;
u16 cs_sel, ss_sel;
u64 efer = 0;
ops->get_msr(ctxt, MSR_EFER, &efer);
/* inject #GP if in real mode */
if (ctxt->mode == X86EMUL_MODE_REAL)
return emulate_gp(ctxt, 0);
/*
* Not recognized on AMD in compat mode (but is recognized in legacy
* mode).
*/
if ((ctxt->mode == X86EMUL_MODE_PROT32) && (efer & EFER_LMA)
&& !vendor_intel(ctxt))
return emulate_ud(ctxt);
/* sysenter/sysexit have not been tested in 64bit mode. */
if (ctxt->mode == X86EMUL_MODE_PROT64)
return X86EMUL_UNHANDLEABLE;
setup_syscalls_segments(ctxt, &cs, &ss);
ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);
switch (ctxt->mode) {
case X86EMUL_MODE_PROT32:
if ((msr_data & 0xfffc) == 0x0)
return emulate_gp(ctxt, 0);
break;
case X86EMUL_MODE_PROT64:
if (msr_data == 0x0)
return emulate_gp(ctxt, 0);
break;
default:
break;
}
ctxt->eflags &= ~(EFLG_VM | EFLG_IF);
cs_sel = (u16)msr_data;
cs_sel &= ~SELECTOR_RPL_MASK;
ss_sel = cs_sel + 8;
ss_sel &= ~SELECTOR_RPL_MASK;
if (ctxt->mode == X86EMUL_MODE_PROT64 || (efer & EFER_LMA)) {
cs.d = 0;
cs.l = 1;
}
ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);
ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);
ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data);
ctxt->_eip = msr_data;
ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data);
*reg_write(ctxt, VCPU_REGS_RSP) = msr_data;
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: SYSENTER emulation is broken
SYSENTER emulation is broken in several ways:
1. It misses the case of 16-bit code segments completely (CVE-2015-0239).
2. MSR_IA32_SYSENTER_CS is checked in 64-bit mode incorrectly (bits 0 and 1 can
still be set without causing #GP).
3. MSR_IA32_SYSENTER_EIP and MSR_IA32_SYSENTER_ESP are not masked in
legacy-mode.
4. There is some unneeded code.
Fix it.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: int git_index_conflict_iterator_new(
git_index_conflict_iterator **iterator_out,
git_index *index)
{
git_index_conflict_iterator *it = NULL;
assert(iterator_out && index);
it = git__calloc(1, sizeof(git_index_conflict_iterator));
GITERR_CHECK_ALLOC(it);
it->index = index;
*iterator_out = it;
return 0;
}
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 <[email protected]>
Reported-by: Vivek Parikh <[email protected]>
CWE ID: CWE-415
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref)
{
/* try relative path, we do not try the absolute because it can leak information about our
system to an attacker */
if (ref->nlvl_to > 0 && ref->nlvl_from > 0) {
char filename[1025];
const char *src_path;
int i, l;
/* find a source dir */
src_path = strrchr(src, '/');
if (src_path)
src_path++;
else
src_path = src;
/* find a next level down to target */
for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--)
if (ref->path[l] == '/') {
if (i == ref->nlvl_to - 1)
break;
else
i++;
}
/* compose filename if next level down to target was found */
if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) {
memcpy(filename, src, src_path - src);
filename[src_path - src] = 0;
for (i = 1; i < ref->nlvl_from; i++)
av_strlcat(filename, "../", sizeof(filename));
av_strlcat(filename, ref->path + l + 1, sizeof(filename));
if (!c->use_absolute_path) {
int same_origin = test_same_origin(src, filename);
if (!same_origin) {
av_log(c->fc, AV_LOG_ERROR,
"Reference with mismatching origin, %s not tried for security reasons, "
"set demuxer option use_absolute_path to allow it anyway\n",
ref->path);
return AVERROR(ENOENT);
}
if(strstr(ref->path + l + 1, "..") ||
strstr(ref->path + l + 1, ":") ||
(ref->nlvl_from > 1 && same_origin < 0) ||
(filename[0] == '/' && src_path == src))
return AVERROR(ENOENT);
}
if (strlen(filename) + 1 == sizeof(filename))
return AVERROR(ENOENT);
if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL))
return 0;
}
} else if (c->use_absolute_path) {
av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, "
"this is a possible security issue\n");
if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL))
return 0;
} else {
av_log(c->fc, AV_LOG_ERROR,
"Absolute path %s not tried for security reasons, "
"set demuxer option use_absolute_path to allow absolute paths\n",
ref->path);
}
return AVERROR(ENOENT);
}
Commit Message: avformat/mov: Fix DoS in read_tfra()
Fixes: Missing EOF check in loop
No testcase
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-834
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PrintPreviewMessageHandler::OnDidPreviewPage(
const PrintHostMsg_DidPreviewPage_Params& params) {
int page_number = params.page_number;
if (page_number < FIRST_PAGE_INDEX || !params.data_size)
return;
PrintPreviewUI* print_preview_ui = GetPrintPreviewUI();
if (!print_preview_ui)
return;
scoped_refptr<base::RefCountedBytes> data_bytes =
GetDataFromHandle(params.metafile_data_handle, params.data_size);
DCHECK(data_bytes);
print_preview_ui->SetPrintPreviewDataForIndex(page_number,
std::move(data_bytes));
print_preview_ui->OnDidPreviewPage(page_number, params.preview_request_id);
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254
Target: 1
Example 2:
Code: void RenderFrameHostImpl::SaveImageAt(int x, int y) {
gfx::PointF point_in_view =
GetView()->TransformRootPointToViewCoordSpace(gfx::PointF(x, y));
Send(new FrameMsg_SaveImageAt(routing_id_, point_in_view.x(),
point_in_view.y()));
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int rawv6_sendmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len)
{
struct ipv6_txoptions opt_space;
struct sockaddr_in6 * sin6 = (struct sockaddr_in6 *) msg->msg_name;
struct in6_addr *daddr, *final_p, final;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
u16 proto;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (sin6) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (sin6->sin6_family && sin6->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
/* port is the proto value [0..255] carried in nexthdr */
proto = ntohs(sin6->sin6_port);
if (!proto)
proto = inet->inet_num;
else if (proto != inet->inet_num)
return -EINVAL;
if (proto > 255)
return -EINVAL;
daddr = &sin6->sin6_addr;
if (np->sndflow) {
fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
daddr = &flowlabel->dst;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
sin6->sin6_scope_id &&
__ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
fl6.flowi6_oif = sin6->sin6_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
proto = inet->inet_num;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (opt == NULL)
opt = np->opt;
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = proto;
err = rawv6_probe_proto_opt(&fl6, msg);
if (err)
goto out;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p, true);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0) {
if (ipv6_addr_is_multicast(&fl6.daddr))
hlimit = np->mcast_hops;
else
hlimit = np->hop_limit;
if (hlimit < 0)
hlimit = ip6_dst_hoplimit(dst);
}
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = rawv6_send_hdrinc(sk, msg->msg_iov, len, &fl6, &dst, msg->msg_flags);
else {
lock_sock(sk);
err = ip6_append_data(sk, ip_generic_getfrag, msg->msg_iov,
len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info*)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = rawv6_push_pending_frames(sk, &fl6, rp);
release_sock(sk);
}
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
return err<0?err:len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls
Only update *addr_len when we actually fill in sockaddr, otherwise we
can return uninitialized memory from the stack to the caller in the
recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)
checks because we only get called with a valid addr_len pointer either
from sock_common_recvmsg or inet_recvmsg.
If a blocking read waits on a socket which is concurrently shut down we
now return zero and set msg_msgnamelen to 0.
Reported-by: mpb <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: l2tp_call_errors_print(netdissect_options *ndo, const u_char *dat)
{
const uint16_t *ptr = (const uint16_t *)dat;
uint16_t val_h, val_l;
ptr++; /* skip "Reserved" */
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "CRCErr=%u ", (val_h<<16) + val_l));
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "FrameErr=%u ", (val_h<<16) + val_l));
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "HardOver=%u ", (val_h<<16) + val_l));
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "BufOver=%u ", (val_h<<16) + val_l));
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "Timeout=%u ", (val_h<<16) + val_l));
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "AlignErr=%u ", (val_h<<16) + val_l));
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: fs_print(netdissect_options *ndo,
register const u_char *bp, int length)
{
int fs_op;
unsigned long i;
if (length <= (int)sizeof(struct rx_header))
return;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) {
goto trunc;
}
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from fsint/afsint.xg
*/
fs_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " fs call %s", tok2str(fs_req, "op#%d", fs_op)));
/*
* Print out arguments to some of the AFS calls. This stuff is
* all from afsint.xg
*/
bp += sizeof(struct rx_header) + 4;
/*
* Sigh. This is gross. Ritchie forgive me.
*/
switch (fs_op) {
case 130: /* Fetch data */
FIDOUT();
ND_PRINT((ndo, " offset"));
UINTOUT();
ND_PRINT((ndo, " length"));
UINTOUT();
break;
case 131: /* Fetch ACL */
case 132: /* Fetch Status */
case 143: /* Old set lock */
case 144: /* Old extend lock */
case 145: /* Old release lock */
case 156: /* Set lock */
case 157: /* Extend lock */
case 158: /* Release lock */
FIDOUT();
break;
case 135: /* Store status */
FIDOUT();
STOREATTROUT();
break;
case 133: /* Store data */
FIDOUT();
STOREATTROUT();
ND_PRINT((ndo, " offset"));
UINTOUT();
ND_PRINT((ndo, " length"));
UINTOUT();
ND_PRINT((ndo, " flen"));
UINTOUT();
break;
case 134: /* Store ACL */
{
char a[AFSOPAQUEMAX+1];
FIDOUT();
ND_TCHECK2(bp[0], 4);
i = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_TCHECK2(bp[0], i);
i = min(AFSOPAQUEMAX, i);
strncpy(a, (const char *) bp, i);
a[i] = '\0';
acl_print(ndo, (u_char *) a, sizeof(a), (u_char *) a + i);
break;
}
case 137: /* Create file */
case 141: /* MakeDir */
FIDOUT();
STROUT(AFSNAMEMAX);
STOREATTROUT();
break;
case 136: /* Remove file */
case 142: /* Remove directory */
FIDOUT();
STROUT(AFSNAMEMAX);
break;
case 138: /* Rename file */
ND_PRINT((ndo, " old"));
FIDOUT();
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " new"));
FIDOUT();
STROUT(AFSNAMEMAX);
break;
case 139: /* Symlink */
FIDOUT();
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " link to"));
STROUT(AFSNAMEMAX);
break;
case 140: /* Link */
FIDOUT();
STROUT(AFSNAMEMAX);
ND_PRINT((ndo, " link to"));
FIDOUT();
break;
case 148: /* Get volume info */
STROUT(AFSNAMEMAX);
break;
case 149: /* Get volume stats */
case 150: /* Set volume stats */
ND_PRINT((ndo, " volid"));
UINTOUT();
break;
case 154: /* New get volume info */
ND_PRINT((ndo, " volname"));
STROUT(AFSNAMEMAX);
break;
case 155: /* Bulk stat */
case 65536: /* Inline bulk stat */
{
unsigned long j;
ND_TCHECK2(bp[0], 4);
j = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
for (i = 0; i < j; i++) {
FIDOUT();
if (i != j - 1)
ND_PRINT((ndo, ","));
}
if (j == 0)
ND_PRINT((ndo, " <none!>"));
}
case 65537: /* Fetch data 64 */
FIDOUT();
ND_PRINT((ndo, " offset"));
UINT64OUT();
ND_PRINT((ndo, " length"));
UINT64OUT();
break;
case 65538: /* Store data 64 */
FIDOUT();
STOREATTROUT();
ND_PRINT((ndo, " offset"));
UINT64OUT();
ND_PRINT((ndo, " length"));
UINT64OUT();
ND_PRINT((ndo, " flen"));
UINT64OUT();
break;
case 65541: /* CallBack rx conn address */
ND_PRINT((ndo, " addr"));
UINTOUT();
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|fs]"));
}
Commit Message: CVE-2017-13049/Rx: add a missing bounds check for Ubik
One of the case blocks in ubik_print() didn't check bounds before
fetching 32 bits of packet data and could overread past the captured
packet data by that amount.
This fixes a buffer over-read discovered by Henri Salo from Nixu
Corporation.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: v8::Handle<v8::Value> V8TestObj::constructorCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.Constructor");
if (!args.IsConstructCall())
return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function.");
if (ConstructorMode::current() == ConstructorMode::WrapExistingObject)
return args.Holder();
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
if (args.Length() <= 0 || !args[0]->IsFunction())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
RefPtr<TestCallback> testCallback = V8TestCallback::create(args[0], getScriptExecutionContext());
RefPtr<TestObj> impl = TestObj::create(testCallback);
v8::Handle<v8::Object> wrapper = args.Holder();
V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get());
V8DOMWrapper::setJSWrapperForDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate());
return args.Holder();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision,
char *errbuf, int *err)
{
bpf_u_int32 magic_int;
size_t amt_read;
bpf_u_int32 total_length;
bpf_u_int32 byte_order_magic;
struct block_header *bhdrp;
struct section_header_block *shbp;
pcap_t *p;
int swapped = 0;
struct pcap_ng_sf *ps;
int status;
struct block_cursor cursor;
struct interface_description_block *idbp;
/*
* Assume no read errors.
*/
*err = 0;
/*
* Check whether the first 4 bytes of the file are the block
* type for a pcapng savefile.
*/
memcpy(&magic_int, magic, sizeof(magic_int));
if (magic_int != BT_SHB) {
/*
* XXX - check whether this looks like what the block
* type would be after being munged by mapping between
* UN*X and DOS/Windows text file format and, if it
* does, look for the byte-order magic number in
* the appropriate place and, if we find it, report
* this as possibly being a pcapng file transferred
* between UN*X and Windows in text file format?
*/
return (NULL); /* nope */
}
/*
* OK, they are. However, that's just \n\r\r\n, so it could,
* conceivably, be an ordinary text file.
*
* It could not, however, conceivably be any other type of
* capture file, so we can read the rest of the putative
* Section Header Block; put the block type in the common
* header, read the rest of the common header and the
* fixed-length portion of the SHB, and look for the byte-order
* magic value.
*/
amt_read = fread(&total_length, 1, sizeof(total_length), fp);
if (amt_read < sizeof(total_length)) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
*err = 1;
return (NULL); /* fail */
}
/*
* Possibly a weird short text file, so just say
* "not pcapng".
*/
return (NULL);
}
amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp);
if (amt_read < sizeof(byte_order_magic)) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
*err = 1;
return (NULL); /* fail */
}
/*
* Possibly a weird short text file, so just say
* "not pcapng".
*/
return (NULL);
}
if (byte_order_magic != BYTE_ORDER_MAGIC) {
byte_order_magic = SWAPLONG(byte_order_magic);
if (byte_order_magic != BYTE_ORDER_MAGIC) {
/*
* Not a pcapng file.
*/
return (NULL);
}
swapped = 1;
total_length = SWAPLONG(total_length);
}
/*
* Check the sanity of the total length.
*/
if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer) ||
(total_length > BT_SHB_INSANE_MAX)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Section Header Block in pcapng dump file has invalid length %" PRIsize " < _%lu_ < %lu (BT_SHB_INSANE_MAX)",
sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer),
total_length,
BT_SHB_INSANE_MAX);
*err = 1;
return (NULL);
}
/*
* OK, this is a good pcapng file.
* Allocate a pcap_t for it.
*/
p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf));
if (p == NULL) {
/* Allocation failed. */
*err = 1;
return (NULL);
}
p->swapped = swapped;
ps = p->priv;
/*
* What precision does the user want?
*/
switch (precision) {
case PCAP_TSTAMP_PRECISION_MICRO:
ps->user_tsresol = 1000000;
break;
case PCAP_TSTAMP_PRECISION_NANO:
ps->user_tsresol = 1000000000;
break;
default:
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"unknown time stamp resolution %u", precision);
free(p);
*err = 1;
return (NULL);
}
p->opt.tstamp_precision = precision;
/*
* Allocate a buffer into which to read blocks. We default to
* the maximum of:
*
* the total length of the SHB for which we read the header;
*
* 2K, which should be more than large enough for an Enhanced
* Packet Block containing a full-size Ethernet frame, and
* leaving room for some options.
*
* If we find a bigger block, we reallocate the buffer, up to
* the maximum size. We start out with a maximum size of
* INITIAL_MAX_BLOCKSIZE; if we see any link-layer header types
* with a maximum snapshot that results in a larger maximum
* block length, we boost the maximum.
*/
p->bufsize = 2048;
if (p->bufsize < total_length)
p->bufsize = total_length;
p->buffer = malloc(p->bufsize);
if (p->buffer == NULL) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
free(p);
*err = 1;
return (NULL);
}
ps->max_blocksize = INITIAL_MAX_BLOCKSIZE;
/*
* Copy the stuff we've read to the buffer, and read the rest
* of the SHB.
*/
bhdrp = (struct block_header *)p->buffer;
shbp = (struct section_header_block *)((u_char *)p->buffer + sizeof(struct block_header));
bhdrp->block_type = magic_int;
bhdrp->total_length = total_length;
shbp->byte_order_magic = byte_order_magic;
if (read_bytes(fp,
(u_char *)p->buffer + (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)),
total_length - (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)),
1, errbuf) == -1)
goto fail;
if (p->swapped) {
/*
* Byte-swap the fields we've read.
*/
shbp->major_version = SWAPSHORT(shbp->major_version);
shbp->minor_version = SWAPSHORT(shbp->minor_version);
/*
* XXX - we don't care about the section length.
*/
}
/* currently only SHB version 1.0 is supported */
if (! (shbp->major_version == PCAP_NG_VERSION_MAJOR &&
shbp->minor_version == PCAP_NG_VERSION_MINOR)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"unsupported pcapng savefile version %u.%u",
shbp->major_version, shbp->minor_version);
goto fail;
}
p->version_major = shbp->major_version;
p->version_minor = shbp->minor_version;
/*
* Save the time stamp resolution the user requested.
*/
p->opt.tstamp_precision = precision;
/*
* Now start looking for an Interface Description Block.
*/
for (;;) {
/*
* Read the next block.
*/
status = read_block(fp, p, &cursor, errbuf);
if (status == 0) {
/* EOF - no IDB in this file */
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"the capture file has no Interface Description Blocks");
goto fail;
}
if (status == -1)
goto fail; /* error */
switch (cursor.block_type) {
case BT_IDB:
/*
* Get a pointer to the fixed-length portion of the
* IDB.
*/
idbp = get_from_block_data(&cursor, sizeof(*idbp),
errbuf);
if (idbp == NULL)
goto fail; /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
idbp->linktype = SWAPSHORT(idbp->linktype);
idbp->snaplen = SWAPLONG(idbp->snaplen);
}
/*
* Try to add this interface.
*/
if (!add_interface(p, &cursor, errbuf))
goto fail;
goto done;
case BT_EPB:
case BT_SPB:
case BT_PB:
/*
* Saw a packet before we saw any IDBs. That's
* not valid, as we don't know what link-layer
* encapsulation the packet has.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"the capture file has a packet block before any Interface Description Blocks");
goto fail;
default:
/*
* Just ignore it.
*/
break;
}
}
done:
p->tzoff = 0; /* XXX - not used in pcap */
p->linktype = linktype_to_dlt(idbp->linktype);
p->snapshot = pcap_adjust_snapshot(p->linktype, idbp->snaplen);
p->linktype_ext = 0;
/*
* If the maximum block size for a packet with the maximum
* snapshot length for this DLT_ is bigger than the current
* maximum block size, increase the maximum.
*/
if (MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)) > ps->max_blocksize)
ps->max_blocksize = MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype));
p->next_packet_op = pcap_ng_next_packet;
p->cleanup_op = pcap_ng_cleanup;
return (p);
fail:
free(ps->ifaces);
free(p->buffer);
free(p);
*err = 1;
return (NULL);
}
Commit Message: Fix some format warnings.
CWE ID: CWE-20
Target: 1
Example 2:
Code: media_status_t AMediaCodec_setAsyncNotifyCallback(
AMediaCodec *mData,
AMediaCodecOnAsyncNotifyCallback callback,
void *userdata) {
if (mData->mAsyncNotify == NULL && userdata != NULL) {
mData->mAsyncNotify = new AMessage(kWhatAsyncNotify, mData->mHandler);
status_t err = mData->mCodec->setCallback(mData->mAsyncNotify);
if (err != OK) {
ALOGE("setAsyncNotifyCallback: err(%d), failed to set async callback", err);
return translate_error(err);
}
}
Mutex::Autolock _l(mData->mAsyncCallbackLock);
mData->mAsyncCallback = callback;
mData->mAsyncCallbackUserData = userdata;
return AMEDIA_OK;
}
Commit Message: Check for overflow of crypto size
Bug: 111603051
Test: CTS
Change-Id: Ib5b1802b9b35769a25c16e2b977308cf7a810606
(cherry picked from commit d1fd02761236b35a336434367131f71bef7405c9)
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t Camera2Client::dump(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("Client2[%d] (%p) Client: %s PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
String8(mClientPackageName).string(),
mClientPid);
result.append(" State: ");
#define CASE_APPEND_ENUM(x) case x: result.append(#x "\n"); break;
const Parameters& p = mParameters.unsafeAccess();
result.append(Parameters::getStateName(p.state));
result.append("\n Current parameters:\n");
result.appendFormat(" Preview size: %d x %d\n",
p.previewWidth, p.previewHeight);
result.appendFormat(" Preview FPS range: %d - %d\n",
p.previewFpsRange[0], p.previewFpsRange[1]);
result.appendFormat(" Preview HAL pixel format: 0x%x\n",
p.previewFormat);
result.appendFormat(" Preview transform: %x\n",
p.previewTransform);
result.appendFormat(" Picture size: %d x %d\n",
p.pictureWidth, p.pictureHeight);
result.appendFormat(" Jpeg thumbnail size: %d x %d\n",
p.jpegThumbSize[0], p.jpegThumbSize[1]);
result.appendFormat(" Jpeg quality: %d, thumbnail quality: %d\n",
p.jpegQuality, p.jpegThumbQuality);
result.appendFormat(" Jpeg rotation: %d\n", p.jpegRotation);
result.appendFormat(" GPS tags %s\n",
p.gpsEnabled ? "enabled" : "disabled");
if (p.gpsEnabled) {
result.appendFormat(" GPS lat x long x alt: %f x %f x %f\n",
p.gpsCoordinates[0], p.gpsCoordinates[1],
p.gpsCoordinates[2]);
result.appendFormat(" GPS timestamp: %lld\n",
p.gpsTimestamp);
result.appendFormat(" GPS processing method: %s\n",
p.gpsProcessingMethod.string());
}
result.append(" White balance mode: ");
switch (p.wbMode) {
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_AUTO)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_INCANDESCENT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_FLUORESCENT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_DAYLIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_TWILIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_SHADE)
default: result.append("UNKNOWN\n");
}
result.append(" Effect mode: ");
switch (p.effectMode) {
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_OFF)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_MONO)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_NEGATIVE)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_SOLARIZE)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_SEPIA)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_POSTERIZE)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_WHITEBOARD)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_BLACKBOARD)
CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_AQUA)
default: result.append("UNKNOWN\n");
}
result.append(" Antibanding mode: ");
switch (p.antibandingMode) {
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO)
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF)
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_50HZ)
CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_60HZ)
default: result.append("UNKNOWN\n");
}
result.append(" Scene mode: ");
switch (p.sceneMode) {
case ANDROID_CONTROL_SCENE_MODE_UNSUPPORTED:
result.append("AUTO\n"); break;
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_ACTION)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_PORTRAIT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_LANDSCAPE)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_NIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_NIGHT_PORTRAIT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_THEATRE)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_BEACH)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SNOW)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SUNSET)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_STEADYPHOTO)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_FIREWORKS)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SPORTS)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_PARTY)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_CANDLELIGHT)
CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_BARCODE)
default: result.append("UNKNOWN\n");
}
result.append(" Flash mode: ");
switch (p.flashMode) {
CASE_APPEND_ENUM(Parameters::FLASH_MODE_OFF)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_AUTO)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_ON)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_TORCH)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_RED_EYE)
CASE_APPEND_ENUM(Parameters::FLASH_MODE_INVALID)
default: result.append("UNKNOWN\n");
}
result.append(" Focus mode: ");
switch (p.focusMode) {
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_AUTO)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_MACRO)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_CONTINUOUS_VIDEO)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_CONTINUOUS_PICTURE)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_EDOF)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_INFINITY)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_FIXED)
CASE_APPEND_ENUM(Parameters::FOCUS_MODE_INVALID)
default: result.append("UNKNOWN\n");
}
result.append(" Focus state: ");
switch (p.focusState) {
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_INACTIVE)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_SCAN)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_FOCUSED)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_UNFOCUSED)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_ACTIVE_SCAN)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED)
CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED)
default: result.append("UNKNOWN\n");
}
result.append(" Focusing areas:\n");
for (size_t i = 0; i < p.focusingAreas.size(); i++) {
result.appendFormat(" [ (%d, %d, %d, %d), weight %d ]\n",
p.focusingAreas[i].left,
p.focusingAreas[i].top,
p.focusingAreas[i].right,
p.focusingAreas[i].bottom,
p.focusingAreas[i].weight);
}
result.appendFormat(" Exposure compensation index: %d\n",
p.exposureCompensation);
result.appendFormat(" AE lock %s, AWB lock %s\n",
p.autoExposureLock ? "enabled" : "disabled",
p.autoWhiteBalanceLock ? "enabled" : "disabled" );
result.appendFormat(" Metering areas:\n");
for (size_t i = 0; i < p.meteringAreas.size(); i++) {
result.appendFormat(" [ (%d, %d, %d, %d), weight %d ]\n",
p.meteringAreas[i].left,
p.meteringAreas[i].top,
p.meteringAreas[i].right,
p.meteringAreas[i].bottom,
p.meteringAreas[i].weight);
}
result.appendFormat(" Zoom index: %d\n", p.zoom);
result.appendFormat(" Video size: %d x %d\n", p.videoWidth,
p.videoHeight);
result.appendFormat(" Recording hint is %s\n",
p.recordingHint ? "set" : "not set");
result.appendFormat(" Video stabilization is %s\n",
p.videoStabilization ? "enabled" : "disabled");
result.appendFormat(" Selected still capture FPS range: %d - %d\n",
p.fastInfo.bestStillCaptureFpsRange[0],
p.fastInfo.bestStillCaptureFpsRange[1]);
result.append(" Current streams:\n");
result.appendFormat(" Preview stream ID: %d\n",
getPreviewStreamId());
result.appendFormat(" Capture stream ID: %d\n",
getCaptureStreamId());
result.appendFormat(" Recording stream ID: %d\n",
getRecordingStreamId());
result.append(" Quirks for this camera:\n");
bool haveQuirk = false;
if (p.quirks.triggerAfWithAuto) {
result.appendFormat(" triggerAfWithAuto\n");
haveQuirk = true;
}
if (p.quirks.useZslFormat) {
result.appendFormat(" useZslFormat\n");
haveQuirk = true;
}
if (p.quirks.meteringCropRegion) {
result.appendFormat(" meteringCropRegion\n");
haveQuirk = true;
}
if (p.quirks.partialResults) {
result.appendFormat(" usePartialResult\n");
haveQuirk = true;
}
if (!haveQuirk) {
result.appendFormat(" none\n");
}
write(fd, result.string(), result.size());
mStreamingProcessor->dump(fd, args);
mCaptureSequencer->dump(fd, args);
mFrameProcessor->dump(fd, args);
mZslProcessor->dump(fd, args);
return dumpDevice(fd, args);
#undef CASE_APPEND_ENUM
}
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t MPEG4Extractor::readMetaData() {
if (mInitCheck != NO_INIT) {
return mInitCheck;
}
off64_t offset = 0;
status_t err;
bool sawMoovOrSidx = false;
while (!(sawMoovOrSidx && (mMdatFound || mMoofFound))) {
off64_t orig_offset = offset;
err = parseChunk(&offset, 0);
if (err != OK && err != UNKNOWN_ERROR) {
break;
} else if (offset <= orig_offset) {
ALOGE("did not advance: %lld->%lld", (long long)orig_offset, (long long)offset);
err = ERROR_MALFORMED;
break;
} else if (err == UNKNOWN_ERROR) {
sawMoovOrSidx = true;
}
}
if (mInitCheck == OK) {
if (mHasVideo) {
mFileMetaData->setCString(
kKeyMIMEType, MEDIA_MIMETYPE_CONTAINER_MPEG4);
} else {
mFileMetaData->setCString(kKeyMIMEType, "audio/mp4");
}
} else {
mInitCheck = err;
}
CHECK_NE(err, (status_t)NO_INIT);
uint64_t psshsize = 0;
for (size_t i = 0; i < mPssh.size(); i++) {
psshsize += 20 + mPssh[i].datalen;
}
if (psshsize > 0 && psshsize <= UINT32_MAX) {
char *buf = (char*)malloc(psshsize);
char *ptr = buf;
for (size_t i = 0; i < mPssh.size(); i++) {
memcpy(ptr, mPssh[i].uuid, 20); // uuid + length
memcpy(ptr + 20, mPssh[i].data, mPssh[i].datalen);
ptr += (20 + mPssh[i].datalen);
}
mFileMetaData->setData(kKeyPssh, 'pssh', buf, psshsize);
free(buf);
}
return mInitCheck;
}
Commit Message: Check malloc result to avoid NPD
Bug: 28471206
Change-Id: Id5d055d76893d6f53a2e524ff5f282d1ddca3345
CWE ID: CWE-20
Target: 1
Example 2:
Code: ClearNetworkErrorLoggingTester(TestingProfile* profile, bool create_service)
: profile_(profile) {
if (create_service)
delegate_ = std::make_unique<MockNetworkErrorLoggingDelegate>();
net::URLRequestContext* request_context =
profile_->GetRequestContext()->GetURLRequestContext();
request_context->set_network_error_logging_delegate(delegate_.get());
}
Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate.
DownloadManager has public SetDelegate method and tests and or other subsystems
can install their own implementations of the delegate.
Bug: 805905
Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8
TBR: tests updated to follow the API change.
Reviewed-on: https://chromium-review.googlesource.com/894702
Reviewed-by: David Vallet <[email protected]>
Reviewed-by: Min Qin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533515}
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Response StorageHandler::TrackCacheStorageForOrigin(const std::string& origin) {
if (!process_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&CacheStorageObserver::TrackOriginOnIOThread,
base::Unretained(GetCacheStorageObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadFPXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
FPXColorspace
colorspace;
FPXImageComponentDesc
*alpha_component,
*blue_component,
*green_component,
*red_component;
FPXImageDesc
fpx_info;
FPXImageHandle
*flashpix;
FPXStatus
fpx_status;
FPXSummaryInformation
summary_info;
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*a,
*b,
*g,
*r;
size_t
memory_limit;
ssize_t
y;
unsigned char
*pixels;
unsigned int
height,
tile_width,
tile_height,
width;
size_t
scene;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) CloseBlob(image);
/*
Initialize FPX toolkit.
*/
fpx_status=FPX_InitSystem();
if (fpx_status != FPX_OK)
ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
memory_limit=20000000;
fpx_status=FPX_SetToolkitMemoryLimit(&memory_limit);
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowReaderException(CoderError,"UnableToInitializeFPXLibrary");
}
tile_width=64;
tile_height=64;
flashpix=(FPXImageHandle *) NULL;
{
#if defined(macintosh)
FSSpec
fsspec;
FilenameToFSSpec(image->filename,&fsspec);
fpx_status=FPX_OpenImageByFilename((const FSSpec &) fsspec,(char *) NULL,
#else
fpx_status=FPX_OpenImageByFilename(image->filename,(char *) NULL,
#endif
&width,&height,&tile_width,&tile_height,&colorspace,&flashpix);
}
if (fpx_status == FPX_LOW_MEMORY_ERROR)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (colorspace.numberOfComponents == 0)
{
FPX_ClearSystem();
ThrowReaderException(CorruptImageError,"ImageTypeNotSupported");
}
if (image_info->view == (char *) NULL)
{
float
aspect_ratio;
/*
Get the aspect ratio.
*/
aspect_ratio=(float) width/height;
fpx_status=FPX_GetImageResultAspectRatio(flashpix,&aspect_ratio);
if (fpx_status != FPX_OK)
ThrowReaderException(DelegateError,"UnableToReadAspectRatio");
if (width != (size_t) floor((aspect_ratio*height)+0.5))
Swap(width,height);
}
fpx_status=FPX_GetSummaryInformation(flashpix,&summary_info);
if (fpx_status != FPX_OK)
{
FPX_ClearSystem();
ThrowReaderException(DelegateError,"UnableToReadSummaryInfo");
}
if (summary_info.title_valid)
if ((summary_info.title.length != 0) &&
(summary_info.title.ptr != (unsigned char *) NULL))
{
char
*label;
/*
Note image label.
*/
label=(char *) NULL;
if (~summary_info.title.length >= (MaxTextExtent-1))
label=(char *) AcquireQuantumMemory(summary_info.title.length+
MaxTextExtent,sizeof(*label));
if (label == (char *) NULL)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickString(label,(char *) summary_info.title.ptr,
summary_info.title.length+1);
(void) SetImageProperty(image,"label",label);
label=DestroyString(label);
}
if (summary_info.comments_valid)
if ((summary_info.comments.length != 0) &&
(summary_info.comments.ptr != (unsigned char *) NULL))
{
char
*comments;
/*
Note image comment.
*/
comments=(char *) NULL;
if (~summary_info.comments.length >= (MaxTextExtent-1))
comments=(char *) AcquireQuantumMemory(summary_info.comments.length+
MaxTextExtent,sizeof(*comments));
if (comments == (char *) NULL)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) CopyMagickString(comments,(char *) summary_info.comments.ptr,
summary_info.comments.length+1);
(void) SetImageProperty(image,"comment",comments);
comments=DestroyString(comments);
}
/*
Determine resolution by scene specification.
*/
for (i=1; ; i++)
if (((width >> i) < tile_width) || ((height >> i) < tile_height))
break;
scene=i;
if (image_info->number_scenes != 0)
while (scene > image_info->scene)
{
width>>=1;
height>>=1;
scene--;
}
if (image_info->size != (char *) NULL)
while ((width > image->columns) || (height > image->rows))
{
width>>=1;
height>>=1;
scene--;
}
image->depth=8;
image->columns=width;
image->rows=height;
if ((colorspace.numberOfComponents % 2) == 0)
image->matte=MagickTrue;
if (colorspace.numberOfComponents == 1)
{
/*
Create linear colormap.
*/
if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse)
{
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (image_info->ping != MagickFalse)
{
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(GetFirstImageInList(image));
}
/*
Allocate memory for the image and pixel buffer.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,(tile_height+
1UL)*colorspace.numberOfComponents*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
FPX_ClearSystem();
(void) FPX_CloseImage(flashpix);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize FlashPix image description.
*/
fpx_info.numberOfComponents=colorspace.numberOfComponents;
for (i=0; i < 4; i++)
{
fpx_info.components[i].myColorType.myDataType=DATA_TYPE_UNSIGNED_BYTE;
fpx_info.components[i].horzSubSampFactor=1;
fpx_info.components[i].vertSubSampFactor=1;
fpx_info.components[i].columnStride=fpx_info.numberOfComponents;
fpx_info.components[i].lineStride=image->columns*
fpx_info.components[i].columnStride;
fpx_info.components[i].theData=pixels+i;
}
fpx_info.components[0].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
NIFRGB_R : MONOCHROME;
red_component=(&fpx_info.components[0]);
fpx_info.components[1].myColorType.myColor=fpx_info.numberOfComponents > 2 ?
NIFRGB_G : ALPHA;
green_component=(&fpx_info.components[1]);
fpx_info.components[2].myColorType.myColor=NIFRGB_B;
blue_component=(&fpx_info.components[2]);
fpx_info.components[3].myColorType.myColor=ALPHA;
alpha_component=(&fpx_info.components[fpx_info.numberOfComponents-1]);
FPX_SetResampleMethod(FPX_LINEAR_INTERPOLATION);
/*
Initialize image pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
if ((y % tile_height) == 0)
{
/*
Read FPX image tile (with or without viewing affine)..
*/
if (image_info->view != (char *) NULL)
fpx_status=FPX_ReadImageRectangle(flashpix,0,y,image->columns,y+
tile_height-1,scene,&fpx_info);
else
fpx_status=FPX_ReadImageTransformRectangle(flashpix,0.0F,
(float) y/image->rows,(float) image->columns/image->rows,
(float) (y+tile_height-1)/image->rows,(ssize_t) image->columns,
(ssize_t) tile_height,&fpx_info);
if (fpx_status == FPX_LOW_MEMORY_ERROR)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
/*
Transfer a FPX pixels.
*/
r=red_component->theData+(y % tile_height)*red_component->lineStride;
g=green_component->theData+(y % tile_height)*green_component->lineStride;
b=blue_component->theData+(y % tile_height)*blue_component->lineStride;
a=alpha_component->theData+(y % tile_height)*alpha_component->lineStride;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (fpx_info.numberOfComponents > 2)
{
SetPixelRed(q,ScaleCharToQuantum(*r));
SetPixelGreen(q,ScaleCharToQuantum(*g));
SetPixelBlue(q,ScaleCharToQuantum(*b));
}
else
{
index=ScaleCharToQuantum(*r);
SetPixelIndex(indexes+x,index);
SetPixelRed(q,index);
SetPixelGreen(q,index);
SetPixelBlue(q,index);
}
SetPixelOpacity(q,OpaqueOpacity);
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*a));
q++;
r+=red_component->columnStride;
g+=green_component->columnStride;
b+=blue_component->columnStride;
a+=alpha_component->columnStride;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) FPX_CloseImage(flashpix);
FPX_ClearSystem();
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static bool __init avx2_usable(void)
{
if (avx_usable() && cpu_has_avx2 && boot_cpu_has(X86_FEATURE_BMI1) &&
boot_cpu_has(X86_FEATURE_BMI2))
return true;
return false;
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct sock *__l2cap_get_chan_by_ident(struct l2cap_chan_list *l, u8 ident)
{
struct sock *s;
for (s = l->head; s; s = l2cap_pi(s)->next_c) {
if (l2cap_pi(s)->ident == ident)
break;
}
return s;
}
Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a,
ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
unsigned char *buf_in=NULL;
int ret= -1,inl;
int mdnid, pknid;
if (!pkey)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7)
{
ASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
return -1;
}
EVP_MD_CTX_init(&ctx);
/* Convert signature OID into digest and public key OIDs */
if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
if (mdnid == NID_undef)
{
if (!pkey->ameth || !pkey->ameth->item_verify)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
ret = pkey->ameth->item_verify(&ctx, it, asn, a,
signature, pkey);
/* Return value of 2 means carry on, anything else means we
* exit straight away: either a fatal error of the underlying
* verification routine handles all verification.
*/
if (ret != 2)
goto err;
ret = -1;
}
else
{
const EVP_MD *type;
type=EVP_get_digestbynid(mdnid);
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
/* Check public key OID matches public key type */
if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey))
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
}
inl = ASN1_item_i2d(asn, &buf_in, it);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
ret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (!ret)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
goto err;
}
ret = -1;
if (EVP_DigestVerifyFinal(&ctx,signature->data,
(size_t)signature->length) <= 0)
{
ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
Commit Message: use correct function name
Reviewed-by: Rich Salz <[email protected]>
Reviewed-by: Matt Caswell <[email protected]>
CWE ID: CWE-310
Target: 1
Example 2:
Code: void WorkerFetchContext::AddAdditionalRequestHeaders(ResourceRequest& request,
FetchResourceType type) {
BaseFetchContext::AddAdditionalRequestHeaders(request, type);
if (!request.Url().IsEmpty() && !request.Url().ProtocolIsInHTTPFamily())
return;
if (web_context_->IsDataSaverEnabled())
request.SetHTTPHeaderField(HTTPNames::Save_Data, "on");
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: EXPORTED void mboxlist_init(int myflags)
{
if (myflags & MBOXLIST_SYNC) {
cyrusdb_sync(DB);
}
}
Commit Message: mboxlist: fix uninitialised memory use where pattern is "Other Users"
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void sample_hbp_handler(struct perf_event *bp, int nmi,
struct perf_sample_data *data,
struct pt_regs *regs)
{
printk(KERN_INFO "%s value is changed\n", ksym_name);
dump_stack();
printk(KERN_INFO "Dump stack from sample_hbp_handler\n");
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: gray_find_cell( RAS_ARG )
{
PCell *pcell, cell;
TPos x = ras.ex;
if ( x > ras.count_ex )
x = ras.count_ex;
pcell = &ras.ycells[ras.ey];
for (;;)
{
cell = *pcell;
if ( cell == NULL || cell->x > x )
break;
if ( cell->x == x )
goto Exit;
pcell = &cell->next;
}
if ( ras.num_cells >= ras.max_cells )
ft_longjmp( ras.jump_buffer, 1 );
cell = ras.cells + ras.num_cells++;
cell->x = x;
cell->area = 0;
cell->cover = 0;
cell->next = *pcell;
*pcell = cell;
Exit:
return cell;
}
Commit Message:
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __blk_mq_requeue_request(struct request *rq)
{
struct request_queue *q = rq->q;
trace_block_rq_requeue(q, rq);
if (test_and_clear_bit(REQ_ATOM_STARTED, &rq->atomic_flags)) {
if (q->dma_drain_size && blk_rq_bytes(rq))
rq->nr_phys_segments--;
}
}
Commit Message: blk-mq: fix race between timeout and freeing request
Inside timeout handler, blk_mq_tag_to_rq() is called
to retrieve the request from one tag. This way is obviously
wrong because the request can be freed any time and some
fiedds of the request can't be trusted, then kernel oops
might be triggered[1].
Currently wrt. blk_mq_tag_to_rq(), the only special case is
that the flush request can share same tag with the request
cloned from, and the two requests can't be active at the same
time, so this patch fixes the above issue by updating tags->rqs[tag]
with the active request(either flush rq or the request cloned
from) of the tag.
Also blk_mq_tag_to_rq() gets much simplified with this patch.
Given blk_mq_tag_to_rq() is mainly for drivers and the caller must
make sure the request can't be freed, so in bt_for_each() this
helper is replaced with tags->rqs[tag].
[1] kernel oops log
[ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M
[ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M
[ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M
[ 439.700653] Dumping ftrace buffer:^M
[ 439.700653] (ftrace buffer empty)^M
[ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M
[ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M
[ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M
[ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M
[ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M
[ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M
[ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M
[ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M
[ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M
[ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M
[ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M
[ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M
[ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M
[ 439.730500] Stack:^M
[ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M
[ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M
[ 439.755663] Call Trace:^M
[ 439.755663] <IRQ> ^M
[ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M
[ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M
[ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M
[ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M
[ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M
[ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M
[ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M
[ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M
[ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M
[ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M
[ 439.755663] <EOI> ^M
[ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M
[ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M
[ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M
[ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M
[ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M
[ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M
[ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M
[ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M
[ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M
[ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M
[ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M
[ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M
[ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89
f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b
53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10
^M
[ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M
[ 439.790911] RSP <ffff880819203da0>^M
[ 439.790911] CR2: 0000000000000158^M
[ 439.790911] ---[ end trace d40af58949325661 ]---^M
Cc: <[email protected]>
Signed-off-by: Ming Lei <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
{
if (file->f_flags & O_DSYNC)
return 0;
if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
return 1;
if (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL ||
(inode->i_flock->fl_start == 0 &&
inode->i_flock->fl_end == OFFSET_MAX &&
inode->i_flock->fl_type != F_RDLCK)))
return 1;
return 0;
}
Commit Message: nfs: always make sure page is up-to-date before extending a write to cover the entire page
We should always make sure the cached page is up-to-date when we're
determining whether we can extend a write to cover the full page -- even
if we've received a write delegation from the server.
Commit c7559663 added logic to skip this check if we have a write
delegation, which can lead to data corruption such as the following
scenario if client B receives a write delegation from the NFS server:
Client A:
# echo 123456789 > /mnt/file
Client B:
# echo abcdefghi >> /mnt/file
# cat /mnt/file
0�D0�abcdefghi
Just because we hold a write delegation doesn't mean that we've read in
the entire page contents.
Cc: <[email protected]> # v3.11+
Signed-off-by: Scott Mayhew <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: void Con_MessageMode_f( void ) {
chat_playerNum = -1;
chat_team = qfalse;
Field_Clear( &chatField );
chatField.widthInChars = 30;
Key_SetCatcher( Key_GetCatcher( ) ^ KEYCATCH_MESSAGE );
}
Commit Message: All: Merge some file writing extension checks
CWE ID: CWE-269
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static irqreturn_t wanxl_intr(int irq, void* dev_id)
{
card_t *card = dev_id;
int i;
u32 stat;
int handled = 0;
while((stat = readl(card->plx + PLX_DOORBELL_FROM_CARD)) != 0) {
handled = 1;
writel(stat, card->plx + PLX_DOORBELL_FROM_CARD);
for (i = 0; i < card->n_ports; i++) {
if (stat & (1 << (DOORBELL_FROM_CARD_TX_0 + i)))
wanxl_tx_intr(&card->ports[i]);
if (stat & (1 << (DOORBELL_FROM_CARD_CABLE_0 + i)))
wanxl_cable_intr(&card->ports[i]);
}
if (stat & (1 << DOORBELL_FROM_CARD_RX))
wanxl_rx_intr(card);
}
return IRQ_RETVAL(handled);
}
Commit Message: wanxl: fix info leak in ioctl
The wanxl_ioctl() code fails to initialize the two padding bytes of
struct sync_serial_settings after the ->loopback member. Add an explicit
memset(0) before filling the structure to avoid the info leak.
Signed-off-by: Salva Peiró <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BrowserGpuChannelHostFactory::EstablishRequest::EstablishRequest()
: event(false, false),
gpu_process_handle(base::kNullProcessHandle) {
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: static ssize_t usbdev_read(struct file *file, char __user *buf, size_t nbytes,
loff_t *ppos)
{
struct usb_dev_state *ps = file->private_data;
struct usb_device *dev = ps->dev;
ssize_t ret = 0;
unsigned len;
loff_t pos;
int i;
pos = *ppos;
usb_lock_device(dev);
if (!connected(ps)) {
ret = -ENODEV;
goto err;
} else if (pos < 0) {
ret = -EINVAL;
goto err;
}
if (pos < sizeof(struct usb_device_descriptor)) {
/* 18 bytes - fits on the stack */
struct usb_device_descriptor temp_desc;
memcpy(&temp_desc, &dev->descriptor, sizeof(dev->descriptor));
le16_to_cpus(&temp_desc.bcdUSB);
le16_to_cpus(&temp_desc.idVendor);
le16_to_cpus(&temp_desc.idProduct);
le16_to_cpus(&temp_desc.bcdDevice);
len = sizeof(struct usb_device_descriptor) - pos;
if (len > nbytes)
len = nbytes;
if (copy_to_user(buf, ((char *)&temp_desc) + pos, len)) {
ret = -EFAULT;
goto err;
}
*ppos += len;
buf += len;
nbytes -= len;
ret += len;
}
pos = sizeof(struct usb_device_descriptor);
for (i = 0; nbytes && i < dev->descriptor.bNumConfigurations; i++) {
struct usb_config_descriptor *config =
(struct usb_config_descriptor *)dev->rawdescriptors[i];
unsigned int length = le16_to_cpu(config->wTotalLength);
if (*ppos < pos + length) {
/* The descriptor may claim to be longer than it
* really is. Here is the actual allocated length. */
unsigned alloclen =
le16_to_cpu(dev->config[i].desc.wTotalLength);
len = length - (*ppos - pos);
if (len > nbytes)
len = nbytes;
/* Simply don't write (skip over) unallocated parts */
if (alloclen > (*ppos - pos)) {
alloclen -= (*ppos - pos);
if (copy_to_user(buf,
dev->rawdescriptors[i] + (*ppos - pos),
min(len, alloclen))) {
ret = -EFAULT;
goto err;
}
}
*ppos += len;
buf += len;
nbytes -= len;
ret += len;
}
pos += length;
}
err:
usb_unlock_device(dev);
return ret;
}
Commit Message: USB: usbfs: fix potential infoleak in devio
The stack object “ci” has a total size of 8 bytes. Its last 3 bytes
are padding bytes which are not initialized and leaked to userland
via “copy_to_user”.
Signed-off-by: Kangjie Lu <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 4;
fwd_txfm_ref = fht4x4_ref;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int parse_packet (sockent_t *se, /* {{{ */
void *buffer, size_t buffer_size, int flags,
const char *username)
{
int status;
value_list_t vl = VALUE_LIST_INIT;
notification_t n;
#if HAVE_LIBGCRYPT
int packet_was_signed = (flags & PP_SIGNED);
int packet_was_encrypted = (flags & PP_ENCRYPTED);
int printed_ignore_warning = 0;
#endif /* HAVE_LIBGCRYPT */
memset (&vl, '\0', sizeof (vl));
memset (&n, '\0', sizeof (n));
status = 0;
while ((status == 0) && (0 < buffer_size)
&& ((unsigned int) buffer_size > sizeof (part_header_t)))
{
uint16_t pkg_length;
uint16_t pkg_type;
memcpy ((void *) &pkg_type,
(void *) buffer,
sizeof (pkg_type));
memcpy ((void *) &pkg_length,
(void *) (buffer + sizeof (pkg_type)),
sizeof (pkg_length));
pkg_length = ntohs (pkg_length);
pkg_type = ntohs (pkg_type);
if (pkg_length > buffer_size)
break;
/* Ensure that this loop terminates eventually */
if (pkg_length < (2 * sizeof (uint16_t)))
break;
if (pkg_type == TYPE_ENCR_AES256)
{
status = parse_part_encr_aes256 (se,
&buffer, &buffer_size, flags);
if (status != 0)
{
ERROR ("network plugin: Decrypting AES256 "
"part failed "
"with status %i.", status);
break;
}
}
#if HAVE_LIBGCRYPT
else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT)
&& (packet_was_encrypted == 0))
{
if (printed_ignore_warning == 0)
{
INFO ("network plugin: Unencrypted packet or "
"part has been ignored.");
printed_ignore_warning = 1;
}
buffer = ((char *) buffer) + pkg_length;
continue;
}
#endif /* HAVE_LIBGCRYPT */
else if (pkg_type == TYPE_SIGN_SHA256)
{
status = parse_part_sign_sha256 (se,
&buffer, &buffer_size, flags);
if (status != 0)
{
ERROR ("network plugin: Verifying HMAC-SHA-256 "
"signature failed "
"with status %i.", status);
break;
}
}
#if HAVE_LIBGCRYPT
else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN)
&& (packet_was_encrypted == 0)
&& (packet_was_signed == 0))
{
if (printed_ignore_warning == 0)
{
INFO ("network plugin: Unsigned packet or "
"part has been ignored.");
printed_ignore_warning = 1;
}
buffer = ((char *) buffer) + pkg_length;
continue;
}
#endif /* HAVE_LIBGCRYPT */
else if (pkg_type == TYPE_VALUES)
{
status = parse_part_values (&buffer, &buffer_size,
&vl.values, &vl.values_len);
if (status != 0)
break;
network_dispatch_values (&vl, username);
sfree (vl.values);
}
else if (pkg_type == TYPE_TIME)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
{
vl.time = TIME_T_TO_CDTIME_T (tmp);
n.time = TIME_T_TO_CDTIME_T (tmp);
}
}
else if (pkg_type == TYPE_TIME_HR)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
{
vl.time = (cdtime_t) tmp;
n.time = (cdtime_t) tmp;
}
}
else if (pkg_type == TYPE_INTERVAL)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
vl.interval = TIME_T_TO_CDTIME_T (tmp);
}
else if (pkg_type == TYPE_INTERVAL_HR)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
vl.interval = (cdtime_t) tmp;
}
else if (pkg_type == TYPE_HOST)
{
status = parse_part_string (&buffer, &buffer_size,
vl.host, sizeof (vl.host));
if (status == 0)
sstrncpy (n.host, vl.host, sizeof (n.host));
}
else if (pkg_type == TYPE_PLUGIN)
{
status = parse_part_string (&buffer, &buffer_size,
vl.plugin, sizeof (vl.plugin));
if (status == 0)
sstrncpy (n.plugin, vl.plugin,
sizeof (n.plugin));
}
else if (pkg_type == TYPE_PLUGIN_INSTANCE)
{
status = parse_part_string (&buffer, &buffer_size,
vl.plugin_instance,
sizeof (vl.plugin_instance));
if (status == 0)
sstrncpy (n.plugin_instance,
vl.plugin_instance,
sizeof (n.plugin_instance));
}
else if (pkg_type == TYPE_TYPE)
{
status = parse_part_string (&buffer, &buffer_size,
vl.type, sizeof (vl.type));
if (status == 0)
sstrncpy (n.type, vl.type, sizeof (n.type));
}
else if (pkg_type == TYPE_TYPE_INSTANCE)
{
status = parse_part_string (&buffer, &buffer_size,
vl.type_instance,
sizeof (vl.type_instance));
if (status == 0)
sstrncpy (n.type_instance, vl.type_instance,
sizeof (n.type_instance));
}
else if (pkg_type == TYPE_MESSAGE)
{
status = parse_part_string (&buffer, &buffer_size,
n.message, sizeof (n.message));
if (status != 0)
{
/* do nothing */
}
else if ((n.severity != NOTIF_FAILURE)
&& (n.severity != NOTIF_WARNING)
&& (n.severity != NOTIF_OKAY))
{
INFO ("network plugin: "
"Ignoring notification with "
"unknown severity %i.",
n.severity);
}
else if (n.time <= 0)
{
INFO ("network plugin: "
"Ignoring notification with "
"time == 0.");
}
else if (strlen (n.message) <= 0)
{
INFO ("network plugin: "
"Ignoring notification with "
"an empty message.");
}
else
{
network_dispatch_notification (&n);
}
}
else if (pkg_type == TYPE_SEVERITY)
{
uint64_t tmp = 0;
status = parse_part_number (&buffer, &buffer_size,
&tmp);
if (status == 0)
n.severity = (int) tmp;
}
else
{
DEBUG ("network plugin: parse_packet: Unknown part"
" type: 0x%04hx", pkg_type);
buffer = ((char *) buffer) + pkg_length;
}
} /* while (buffer_size > sizeof (part_header_t)) */
if (status == 0 && buffer_size > 0)
WARNING ("network plugin: parse_packet: Received truncated "
"packet, try increasing `MaxPacketSize'");
return (status);
} /* }}} int parse_packet */
Commit Message: network plugin: Fix heap overflow in parse_packet().
Emilien Gaspar has identified a heap overflow in parse_packet(), the
function used by the network plugin to parse incoming network packets.
This is a vulnerability in collectd, though the scope is not clear at
this point. At the very least specially crafted network packets can be
used to crash the daemon. We can't rule out a potential remote code
execution though.
Fixes: CVE-2016-6254
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline struct net_device** get_dev_p(pvc_device *pvc, int type)
{
if (type == ARPHRD_ETHER)
return &pvc->ether;
else
return &pvc->main;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn,
struct xfrm_replay_state_esn **preplay_esn,
struct nlattr *rta)
{
struct xfrm_replay_state_esn *p, *pp, *up;
if (!rta)
return 0;
up = nla_data(rta);
p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!p)
return -ENOMEM;
pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL);
if (!pp) {
kfree(p);
return -ENOMEM;
}
*replay_esn = p;
*preplay_esn = pp;
return 0;
}
Commit Message: xfrm_user: ensure user supplied esn replay window is valid
The current code fails to ensure that the netlink message actually
contains as many bytes as the header indicates. If a user creates a new
state or updates an existing one but does not supply the bytes for the
whole ESN replay window, the kernel copies random heap bytes into the
replay bitmap, the ones happen to follow the XFRMA_REPLAY_ESN_VAL
netlink attribute. This leads to following issues:
1. The replay window has random bits set confusing the replay handling
code later on.
2. A malicious user could use this flaw to leak up to ~3.5kB of heap
memory when she has access to the XFRM netlink interface (requires
CAP_NET_ADMIN).
Known users of the ESN replay window are strongSwan and Steffen's
iproute2 patch (<http://patchwork.ozlabs.org/patch/85962/>). The latter
uses the interface with a bitmap supplied while the former does not.
strongSwan is therefore prone to run into issue 1.
To fix both issues without breaking existing userland allow using the
XFRMA_REPLAY_ESN_VAL netlink attribute with either an empty bitmap or a
fully specified one. For the former case we initialize the in-kernel
bitmap with zero, for the latter we copy the user supplied bitmap. For
state updates the full bitmap must be supplied.
To prevent overflows in the bitmap length calculation the maximum size
of bmp_len is limited to 128 by this patch -- resulting in a maximum
replay window of 4096 packets. This should be sufficient for all real
life scenarios (RFC 4303 recommends a default replay window size of 64).
Cc: Steffen Klassert <[email protected]>
Cc: Martin Willi <[email protected]>
Cc: Ben Hutchings <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_,
unsigned char*& buf, size_t& buflen) {
assert(pReader);
assert(pos >= 0);
long long total, available;
long status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
if (status < 0)
return false;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
if ((unsigned long)id != id_)
return false;
pos += len; // consume id
const long long size_ = ReadUInt(pReader, pos, len);
assert(size_ >= 0);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
pos += len; // consume length of size of payload
assert((pos + size_) <= available);
const long buflen_ = static_cast<long>(size_);
buf = new (std::nothrow) unsigned char[buflen_];
assert(buf); // TODO
status = pReader->Read(pos, buflen_, buf);
assert(status == 0); // TODO
buflen = buflen_;
pos += size_; // consume size of payload
return true;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
Target: 1
Example 2:
Code: ModuleExport void UnregisterGIFImage(void)
{
(void) UnregisterMagickInfo("GIF");
(void) UnregisterMagickInfo("GIF87");
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/592
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ssize_t socket_bytes_available(const socket_t *socket) {
assert(socket != NULL);
int size = 0;
if (ioctl(socket->fd, FIONREAD, &size) == -1)
return -1;
return size;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual void SetUp() {
UUT_ = GET_PARAM(2);
/* Set up guard blocks for an inner block centered in the outer block */
for (int i = 0; i < kOutputBufferSize; ++i) {
if (IsIndexInBorder(i))
output_[i] = 255;
else
output_[i] = 0;
}
::libvpx_test::ACMRandom prng;
for (int i = 0; i < kInputBufferSize; ++i)
input_[i] = prng.Rand8Extremes();
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Target: 1
Example 2:
Code: BufFilePushCompressed (BufFilePtr f)
{
int code;
int maxbits;
int hsize;
CompressedFile *file;
int extra;
if ((BufFileGet(f) != (magic_header[0] & 0xFF)) ||
(BufFileGet(f) != (magic_header[1] & 0xFF)))
{
return 0;
}
code = BufFileGet (f);
if (code == BUFFILEEOF) return 0;
maxbits = code & BIT_MASK;
if (maxbits > BITS || maxbits < 12)
return 0;
hsize = hsize_table[maxbits - 12];
extra = (1 << maxbits) * sizeof (char_type) +
hsize * sizeof (unsigned short);
file = malloc (sizeof (CompressedFile) + extra);
if (!file)
return 0;
file->file = f;
file->maxbits = maxbits;
file->block_compress = code & BLOCK_MASK;
file->maxmaxcode = 1 << file->maxbits;
file->tab_suffix = (char_type *) &file[1];
file->tab_prefix = (unsigned short *) (file->tab_suffix + file->maxmaxcode);
/*
* As above, initialize the first 256 entries in the table.
*/
file->maxcode = MAXCODE(file->n_bits = INIT_BITS);
for ( code = 255; code >= 0; code-- ) {
file->tab_prefix[code] = 0;
file->tab_suffix[code] = (char_type) code;
}
file->free_ent = ((file->block_compress) ? FIRST : 256 );
file->clear_flg = 0;
file->offset = 0;
file->size = 0;
file->stackp = file->de_stack;
bzero(file->buf, BITS);
file->finchar = file->oldcode = getcode (file);
if (file->oldcode != -1)
*file->stackp++ = file->finchar;
return BufFileCreate ((char *) file,
BufCompressedFill,
0,
BufCompressedSkip,
BufCompressedClose);
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int ssl3_get_client_hello(SSL *s)
{
int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1, cookie_valid = 0;
unsigned int cookie_len;
long n;
unsigned long id;
unsigned char *p, *d;
SSL_CIPHER *c;
#ifndef OPENSSL_NO_COMP
unsigned char *q;
SSL_COMP *comp = NULL;
#endif
STACK_OF(SSL_CIPHER) *ciphers = NULL;
if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
goto retry_cert;
/*
* We do this so that we will respond with our native type. If we are
* TLSv1 and we get SSLv3, we will respond with TLSv1, This down
* switching should be handled by a different method. If we are SSLv3, we
* will respond with SSLv3, even if prompted with TLSv1.
*/
if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
s->state = SSL3_ST_SR_CLNT_HELLO_B;
}
s->first_packet = 1;
n = s->method->ssl_get_message(s,
SSL3_ST_SR_CLNT_HELLO_B,
SSL3_ST_SR_CLNT_HELLO_C,
SSL3_MT_CLIENT_HELLO,
SSL3_RT_MAX_PLAIN_LENGTH, &ok);
if (!ok)
return ((int)n);
s->first_packet = 0;
d = p = (unsigned char *)s->init_msg;
/*
* 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte
* for session id length
*/
if (n < 2 + SSL3_RANDOM_SIZE + 1) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
/*
* use version from inside client hello, not from record header (may
* differ: see RFC 2246, Appendix E, second paragraph)
*/
s->client_version = (((int)p[0]) << 8) | (int)p[1];
p += 2;
if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
s->method->version != DTLS_ANY_VERSION)
: (s->client_version < s->version)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
if ((s->client_version >> 8) == SSL3_VERSION_MAJOR &&
!s->enc_write_ctx && !s->write_hash) {
/*
* similar to ssl3_get_record, send alert using remote version
* number
*/
s->version = s->client_version;
}
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
/*
* If we require cookies and this ClientHello doesn't contain one, just
* return since we do not want to allocate any memory yet. So check
* cookie length...
*/
if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
unsigned int session_length, cookie_length;
session_length = *(p + SSL3_RANDOM_SIZE);
if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
if (cookie_length == 0)
return 1;
}
/* load the client random */
memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
p += SSL3_RANDOM_SIZE;
/* get the session-id */
j = *(p++);
if (p + j > d + n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
if ((j < 0) || (j > SSL_MAX_SSL_SESSION_ID_LENGTH)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
s->hit = 0;
/*
* Versions before 0.9.7 always allow clients to resume sessions in
* renegotiation. 0.9.7 and later allow this by default, but optionally
* ignore resumption requests with flag
* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
* than a change to default behavior so that applications relying on this
* for security won't even compile against older library versions).
* 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
* request renegotiation but not a new session (s->new_session remains
* unset): for servers, this essentially just means that the
* SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored.
*/
if ((s->new_session
&& (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
if (!ssl_get_new_session(s, 1))
goto err;
} else {
i = ssl_get_prev_session(s, p, j, d + n);
/*
* Only resume if the session's version matches the negotiated
* version.
* RFC 5246 does not provide much useful advice on resumption
* with a different protocol version. It doesn't forbid it but
* the sanity of such behaviour would be questionable.
* In practice, clients do not accept a version mismatch and
* will abort the handshake with an error.
*/
if (i == 1 && s->version == s->session->ssl_version) { /* previous
* session */
s->hit = 1;
} else if (i == -1)
goto err;
else { /* i == 0 */
if (!ssl_get_new_session(s, 1))
goto err;
}
}
p += j;
if (SSL_IS_DTLS(s)) {
/* cookie stuff */
if (p + 1 > d + n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
cookie_len = *(p++);
if (p + cookie_len > d + n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
/*
* The ClientHello may contain a cookie even if the
* HelloVerify message has not been sent--make sure that it
* does not cause an overflow.
*/
if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
/* too much data */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
goto f_err;
}
/* verify the cookie if appropriate option is set. */
if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) {
memcpy(s->d1->rcvd_cookie, p, cookie_len);
if (s->ctx->app_verify_cookie_cb != NULL) {
if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
cookie_len) == 0) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_COOKIE_MISMATCH);
goto f_err;
}
/* else cookie verification succeeded */
}
/* default verification */
else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
s->d1->cookie_len) != 0) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
goto f_err;
}
cookie_valid = 1;
}
p += cookie_len;
if (s->method->version == DTLS_ANY_VERSION) {
/* Select version to use */
if (s->client_version <= DTLS1_2_VERSION &&
!(s->options & SSL_OP_NO_DTLSv1_2)) {
s->version = DTLS1_2_VERSION;
s->method = DTLSv1_2_server_method();
} else if (tls1_suiteb(s)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
s->version = s->client_version;
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
} else if (s->client_version <= DTLS1_VERSION &&
!(s->options & SSL_OP_NO_DTLSv1)) {
s->version = DTLS1_VERSION;
s->method = DTLSv1_server_method();
} else {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_WRONG_VERSION_NUMBER);
s->version = s->client_version;
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
s->session->ssl_version = s->version;
}
}
if (p + 2 > d + n) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
n2s(p, i);
if (i == 0) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
goto f_err;
}
/* i bytes of cipher data + 1 byte for compression length later */
if ((p + i + 1) > (d + n)) {
/* not enough data */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) {
goto err;
}
p += i;
/* If it is a hit, check that the cipher is in the list */
if (s->hit) {
j = 0;
id = s->session->cipher->id;
#ifdef CIPHER_DEBUG
fprintf(stderr, "client sent %d ciphers\n",
sk_SSL_CIPHER_num(ciphers));
#endif
for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
c = sk_SSL_CIPHER_value(ciphers, i);
#ifdef CIPHER_DEBUG
fprintf(stderr, "client [%2d of %2d]:%s\n",
i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
#endif
if (c->id == id) {
j = 1;
break;
}
}
/*
* Disabled because it can be used in a ciphersuite downgrade attack:
* CVE-2010-4180.
*/
#if 0
if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
&& (sk_SSL_CIPHER_num(ciphers) == 1)) {
/*
* Special case as client bug workaround: the previously used
* cipher may not be in the current list, the client instead
* might be trying to continue using a cipher that before wasn't
* chosen due to server preferences. We'll have to reject the
* connection if the cipher is not enabled, though.
*/
c = sk_SSL_CIPHER_value(ciphers, 0);
if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
s->session->cipher = c;
j = 1;
}
}
#endif
if (j == 0) {
/*
* we need to have the cipher in the cipher list if we are asked
* to reuse it
*/
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_REQUIRED_CIPHER_MISSING);
goto f_err;
}
}
/* compression */
i = *(p++);
if ((p + i) > (d + n)) {
/* not enough data */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
goto f_err;
}
#ifndef OPENSSL_NO_COMP
q = p;
#endif
for (j = 0; j < i; j++) {
if (p[j] == 0)
break;
}
p += i;
if (j >= i) {
/* no compress */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
goto f_err;
}
#ifndef OPENSSL_NO_TLSEXT
/* TLS extensions */
if (s->version >= SSL3_VERSION) {
if (!ssl_parse_clienthello_tlsext(s, &p, d + n)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
goto err;
}
}
/*
* Check if we want to use external pre-shared secret for this handshake
* for not reused session only. We need to generate server_random before
* calling tls_session_secret_cb in order to allow SessionTicket
* processing to use it in key derivation.
*/
{
unsigned char *pos;
pos = s->s3->server_random;
if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
goto f_err;
}
}
if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
SSL_CIPHER *pref_cipher = NULL;
s->session->master_key_length = sizeof(s->session->master_key);
if (s->tls_session_secret_cb(s, s->session->master_key,
&s->session->master_key_length, ciphers,
&pref_cipher,
s->tls_session_secret_cb_arg)) {
s->hit = 1;
s->session->ciphers = ciphers;
s->session->verify_result = X509_V_OK;
ciphers = NULL;
/* check if some cipher was preferred by call back */
pref_cipher =
pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
s->
session->ciphers,
SSL_get_ciphers
(s));
if (pref_cipher == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
goto f_err;
}
s->session->cipher = pref_cipher;
if (s->cipher_list)
sk_SSL_CIPHER_free(s->cipher_list);
if (s->cipher_list_by_id)
sk_SSL_CIPHER_free(s->cipher_list_by_id);
s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
}
}
#endif
/*
* Worst case, we will use the NULL compression, but if we have other
* options, we will now look for them. We have i-1 compression
* algorithms from the client, starting at q.
*/
s->s3->tmp.new_compression = NULL;
#ifndef OPENSSL_NO_COMP
/* This only happens if we have a cache hit */
if (s->session->compress_meth != 0) {
int m, comp_id = s->session->compress_meth;
/* Perform sanity checks on resumed compression algorithm */
/* Can't disable compression */
if (s->options & SSL_OP_NO_COMPRESSION) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_INCONSISTENT_COMPRESSION);
goto f_err;
}
/* Look for resumed compression method */
for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
if (comp_id == comp->id) {
s->s3->tmp.new_compression = comp;
break;
}
}
if (s->s3->tmp.new_compression == NULL) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_INVALID_COMPRESSION_ALGORITHM);
goto f_err;
}
/* Look for resumed method in compression list */
for (m = 0; m < i; m++) {
if (q[m] == comp_id)
break;
}
if (m >= i) {
al = SSL_AD_ILLEGAL_PARAMETER;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
goto f_err;
}
} else if (s->hit)
comp = NULL;
else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) {
/* See if we have a match */
int m, nn, o, v, done = 0;
nn = sk_SSL_COMP_num(s->ctx->comp_methods);
for (m = 0; m < nn; m++) {
comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
v = comp->id;
for (o = 0; o < i; o++) {
if (v == q[o]) {
done = 1;
break;
}
}
if (done)
break;
}
if (done)
s->s3->tmp.new_compression = comp;
else
comp = NULL;
}
#else
/*
* If compression is disabled we'd better not try to resume a session
* using compression.
*/
if (s->session->compress_meth != 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
goto f_err;
}
#endif
/*
* Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
*/
if (!s->hit) {
#ifdef OPENSSL_NO_COMP
s->session->compress_meth = 0;
#else
s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
#endif
if (s->session->ciphers != NULL)
sk_SSL_CIPHER_free(s->session->ciphers);
s->session->ciphers = ciphers;
if (ciphers == NULL) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
goto f_err;
}
ciphers = NULL;
if (!tls1_set_server_sigalgs(s)) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
/* Let cert callback update server certificates if required */
retry_cert:
if (s->cert->cert_cb) {
int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
if (rv == 0) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
goto f_err;
}
if (rv < 0) {
s->rwstate = SSL_X509_LOOKUP;
return -1;
}
s->rwstate = SSL_NOTHING;
}
c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
if (c == NULL) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
goto f_err;
}
s->s3->tmp.new_cipher = c;
} else {
/* Session-id reuse */
#ifdef REUSE_CIPHER_BUG
STACK_OF(SSL_CIPHER) *sk;
SSL_CIPHER *nc = NULL;
SSL_CIPHER *ec = NULL;
if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) {
sk = s->session->ciphers;
for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
c = sk_SSL_CIPHER_value(sk, i);
if (c->algorithm_enc & SSL_eNULL)
nc = c;
if (SSL_C_IS_EXPORT(c))
ec = c;
}
if (nc != NULL)
s->s3->tmp.new_cipher = nc;
else if (ec != NULL)
s->s3->tmp.new_cipher = ec;
else
s->s3->tmp.new_cipher = s->session->cipher;
} else
#endif
s->s3->tmp.new_cipher = s->session->cipher;
}
if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
if (!ssl3_digest_cached_records(s))
goto f_err;
}
/*-
* we now have the following setup.
* client_random
* cipher_list - our prefered list of ciphers
* ciphers - the clients prefered list of ciphers
* compression - basically ignored right now
* ssl version is set - sslv3
* s->session - The ssl session has been setup.
* s->hit - session reuse flag
* s->tmp.new_cipher - the new cipher to use.
*/
/* Handles TLS extensions that we couldn't check earlier */
if (s->version >= SSL3_VERSION) {
if (ssl_check_clienthello_tlsext_late(s) <= 0) {
SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
goto err;
}
}
ret = cookie_valid ? 2 : 1;
if (0) {
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
s->state = SSL_ST_ERR;
}
if (ciphers != NULL)
sk_SSL_CIPHER_free(ciphers);
return ret;
}
Commit Message:
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: tt_sbit_decoder_load_image( TT_SBitDecoder decoder,
FT_UInt glyph_index,
FT_Int x_pos,
FT_Int y_pos )
{
/*
* First, we find the correct strike range that applies to this
* glyph index.
*/
FT_Byte* p = decoder->eblc_base + decoder->strike_index_array;
FT_Byte* p_limit = decoder->eblc_limit;
FT_ULong num_ranges = decoder->strike_index_count;
FT_UInt start, end, index_format, image_format;
FT_ULong image_start = 0, image_end = 0, image_offset;
for ( ; num_ranges > 0; num_ranges-- )
{
start = FT_NEXT_USHORT( p );
end = FT_NEXT_USHORT( p );
if ( glyph_index >= start && glyph_index <= end )
goto FoundRange;
p += 4; /* ignore index offset */
}
goto NoBitmap;
FoundRange:
image_offset = FT_NEXT_ULONG( p );
/* overflow check */
p = decoder->eblc_base + decoder->strike_index_array;
if ( image_offset > (FT_ULong)( p_limit - p ) )
goto Failure;
p += image_offset;
if ( p + 8 > p_limit )
goto NoBitmap;
/* now find the glyph's location and extend within the ebdt table */
index_format = FT_NEXT_USHORT( p );
image_format = FT_NEXT_USHORT( p );
image_offset = FT_NEXT_ULONG ( p );
switch ( index_format )
{
case 1: /* 4-byte offsets relative to `image_offset' */
p += 4 * ( glyph_index - start );
if ( p + 8 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_ULONG( p );
image_end = FT_NEXT_ULONG( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 2: /* big metrics, constant image size */
{
FT_ULong image_size;
if ( p + 12 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
image_start = image_size * ( glyph_index - start );
image_end = image_start + image_size;
}
break;
case 3: /* 2-byte offsets relative to 'image_offset' */
p += 2 * ( glyph_index - start );
if ( p + 4 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_USHORT( p );
image_end = FT_NEXT_USHORT( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 4: /* sparse glyph array with (glyph,offset) pairs */
{
FT_ULong mm, num_glyphs;
if ( p + 4 > p_limit )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + ( num_glyphs + 1 ) * 4 */
if ( num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
{
image_start = FT_NEXT_USHORT( p );
p += 2;
image_end = FT_PEEK_USHORT( p );
break;
}
p += 2;
}
if ( mm >= num_glyphs )
goto NoBitmap;
}
break;
case 5: /* constant metrics with sparse glyph codes */
case 19:
{
FT_ULong image_size, mm, num_glyphs;
if ( p + 16 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + 2 * num_glyphs */
if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
{
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
break;
}
if ( mm >= num_glyphs )
goto NoBitmap;
image_start = image_size * mm;
image_end = image_start + image_size;
}
break;
default:
goto NoBitmap;
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: status_t OMXCodec::allocateOutputBuffersFromNativeWindow() {
OMX_PARAM_PORTDEFINITIONTYPE def;
InitOMXParams(&def);
def.nPortIndex = kPortIndexOutput;
status_t err = mOMX->getParameter(
mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
if (err != OK) {
CODEC_LOGE("getParameter failed: %d", err);
return err;
}
sp<MetaData> meta = mSource->getFormat();
int32_t rotationDegrees;
if (!meta->findInt32(kKeyRotation, &rotationDegrees)) {
rotationDegrees = 0;
}
OMX_U32 usage = 0;
err = mOMX->getGraphicBufferUsage(mNode, kPortIndexOutput, &usage);
if (err != 0) {
ALOGW("querying usage flags from OMX IL component failed: %d", err);
usage = 0;
}
if (mFlags & kEnableGrallocUsageProtected) {
usage |= GRALLOC_USAGE_PROTECTED;
}
err = setNativeWindowSizeFormatAndUsage(
mNativeWindow.get(),
def.format.video.nFrameWidth,
def.format.video.nFrameHeight,
def.format.video.eColorFormat,
rotationDegrees,
usage | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_EXTERNAL_DISP);
if (err != 0) {
return err;
}
int minUndequeuedBufs = 0;
err = mNativeWindow->query(mNativeWindow.get(),
NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufs);
if (err != 0) {
ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
strerror(-err), -err);
return err;
}
CODEC_LOGI("OMX-buffers: min=%u actual=%u undeq=%d+1",
def.nBufferCountMin, def.nBufferCountActual, minUndequeuedBufs);
for (OMX_U32 extraBuffers = 2 + 1; /* condition inside loop */; extraBuffers--) {
OMX_U32 newBufferCount =
def.nBufferCountMin + minUndequeuedBufs + extraBuffers;
def.nBufferCountActual = newBufferCount;
err = mOMX->setParameter(
mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
if (err == OK) {
minUndequeuedBufs += extraBuffers;
break;
}
CODEC_LOGW("setting nBufferCountActual to %u failed: %d",
newBufferCount, err);
/* exit condition */
if (extraBuffers == 0) {
return err;
}
}
CODEC_LOGI("OMX-buffers: min=%u actual=%u undeq=%d+1",
def.nBufferCountMin, def.nBufferCountActual, minUndequeuedBufs);
err = native_window_set_buffer_count(
mNativeWindow.get(), def.nBufferCountActual);
if (err != 0) {
ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
-err);
return err;
}
CODEC_LOGV("allocating %u buffers from a native window of size %u on "
"output port", def.nBufferCountActual, def.nBufferSize);
for (OMX_U32 i = 0; i < def.nBufferCountActual; i++) {
ANativeWindowBuffer* buf;
err = native_window_dequeue_buffer_and_wait(mNativeWindow.get(), &buf);
if (err != 0) {
ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), -err);
break;
}
sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(buf, false));
BufferInfo info;
info.mData = NULL;
info.mSize = def.nBufferSize;
info.mStatus = OWNED_BY_US;
info.mMem = NULL;
info.mMediaBuffer = new MediaBuffer(graphicBuffer);
info.mMediaBuffer->setObserver(this);
mPortBuffers[kPortIndexOutput].push(info);
IOMX::buffer_id bufferId;
err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer,
&bufferId);
if (err != 0) {
CODEC_LOGE("registering GraphicBuffer with OMX IL component "
"failed: %d", err);
break;
}
mPortBuffers[kPortIndexOutput].editItemAt(i).mBuffer = bufferId;
CODEC_LOGV("registered graphic buffer with ID %u (pointer = %p)",
bufferId, graphicBuffer.get());
}
OMX_U32 cancelStart;
OMX_U32 cancelEnd;
if (err != 0) {
cancelStart = 0;
cancelEnd = mPortBuffers[kPortIndexOutput].size();
} else {
cancelStart = def.nBufferCountActual - minUndequeuedBufs;
cancelEnd = def.nBufferCountActual;
}
for (OMX_U32 i = cancelStart; i < cancelEnd; i++) {
BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(i);
cancelBufferToNativeWindow(info);
}
return err;
}
Commit Message: OMXCodec: check IMemory::pointer() before using allocation
Bug: 29421811
Change-Id: I0a73ba12bae4122f1d89fc92e5ea4f6a96cd1ed1
CWE ID: CWE-284
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int __init cuse_init(void)
{
int i, rc;
/* init conntbl */
for (i = 0; i < CUSE_CONNTBL_LEN; i++)
INIT_LIST_HEAD(&cuse_conntbl[i]);
/* inherit and extend fuse_dev_operations */
cuse_channel_fops = fuse_dev_operations;
cuse_channel_fops.owner = THIS_MODULE;
cuse_channel_fops.open = cuse_channel_open;
cuse_channel_fops.release = cuse_channel_release;
cuse_class = class_create(THIS_MODULE, "cuse");
if (IS_ERR(cuse_class))
return PTR_ERR(cuse_class);
cuse_class->dev_groups = cuse_class_dev_groups;
rc = misc_register(&cuse_miscdev);
if (rc) {
class_destroy(cuse_class);
return rc;
}
return 0;
}
Commit Message: cuse: fix memory leak
The problem is that fuse_dev_alloc() acquires an extra reference to cc.fc,
and the original ref count is never dropped.
Reported-by: Colin Ian King <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
Fixes: cc080e9e9be1 ("fuse: introduce per-instance fuse_dev structure")
Cc: <[email protected]> # v4.2+
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadNULLImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickPixelPacket
background;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
if (image->columns == 0)
image->columns=1;
if (image->rows == 0)
image->rows=1;
image->matte=MagickTrue;
GetMagickPixelPacket(image,&background);
background.opacity=(MagickRealType) TransparentOpacity;
if (image->colorspace == CMYKColorspace)
ConvertRGBToCMYK(&background);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelPacket(image,&background,q,indexes);
q++;
indexes++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void pmcraid_erp_done(struct pmcraid_cmd *cmd)
{
struct scsi_cmnd *scsi_cmd = cmd->scsi_cmd;
struct pmcraid_instance *pinstance = cmd->drv_inst;
u32 ioasc = le32_to_cpu(cmd->ioa_cb->ioasa.ioasc);
if (PMCRAID_IOASC_SENSE_KEY(ioasc) > 0) {
scsi_cmd->result |= (DID_ERROR << 16);
scmd_printk(KERN_INFO, scsi_cmd,
"command CDB[0] = %x failed with IOASC: 0x%08X\n",
cmd->ioa_cb->ioarcb.cdb[0], ioasc);
}
/* if we had allocated sense buffers for request sense, copy the sense
* release the buffers
*/
if (cmd->sense_buffer != NULL) {
memcpy(scsi_cmd->sense_buffer,
cmd->sense_buffer,
SCSI_SENSE_BUFFERSIZE);
pci_free_consistent(pinstance->pdev,
SCSI_SENSE_BUFFERSIZE,
cmd->sense_buffer, cmd->sense_buffer_dma);
cmd->sense_buffer = NULL;
cmd->sense_buffer_dma = 0;
}
scsi_dma_unmap(scsi_cmd);
pmcraid_return_cmd(cmd);
scsi_cmd->scsi_done(scsi_cmd);
}
Commit Message: [SCSI] pmcraid: reject negative request size
There's a code path in pmcraid that can be reached via device ioctl that
causes all sorts of ugliness, including heap corruption or triggering the
OOM killer due to consecutive allocation of large numbers of pages.
First, the user can call pmcraid_chr_ioctl(), with a type
PMCRAID_PASSTHROUGH_IOCTL. This calls through to
pmcraid_ioctl_passthrough(). Next, a pmcraid_passthrough_ioctl_buffer
is copied in, and the request_size variable is set to
buffer->ioarcb.data_transfer_length, which is an arbitrary 32-bit
signed value provided by the user. If a negative value is provided
here, bad things can happen. For example,
pmcraid_build_passthrough_ioadls() is called with this request_size,
which immediately calls pmcraid_alloc_sglist() with a negative size.
The resulting math on allocating a scatter list can result in an
overflow in the kzalloc() call (if num_elem is 0, the sglist will be
smaller than expected), or if num_elem is unexpectedly large the
subsequent loop will call alloc_pages() repeatedly, a high number of
pages will be allocated and the OOM killer might be invoked.
It looks like preventing this value from being negative in
pmcraid_ioctl_passthrough() would be sufficient.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: James Bottomley <[email protected]>
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void http_reset_txn(struct stream *s)
{
http_end_txn(s);
http_init_txn(s);
/* reinitialise the current rule list pointer to NULL. We are sure that
* any rulelist match the NULL pointer.
*/
s->current_rule_list = NULL;
s->be = strm_fe(s);
s->logs.logwait = strm_fe(s)->to_log;
s->logs.level = 0;
stream_del_srv_conn(s);
s->target = NULL;
/* re-init store persistence */
s->store_count = 0;
s->uniq_id = global.req_count++;
s->req.flags |= CF_READ_DONTWAIT; /* one read is usually enough */
/* We must trim any excess data from the response buffer, because we
* may have blocked an invalid response from a server that we don't
* want to accidentely forward once we disable the analysers, nor do
* we want those data to come along with next response. A typical
* example of such data would be from a buggy server responding to
* a HEAD with some data, or sending more than the advertised
* content-length.
*/
if (unlikely(s->res.buf->i))
s->res.buf->i = 0;
/* Now we can realign the response buffer */
buffer_realign(s->res.buf);
s->req.rto = strm_fe(s)->timeout.client;
s->req.wto = TICK_ETERNITY;
s->res.rto = TICK_ETERNITY;
s->res.wto = strm_fe(s)->timeout.client;
s->req.rex = TICK_ETERNITY;
s->req.wex = TICK_ETERNITY;
s->req.analyse_exp = TICK_ETERNITY;
s->res.rex = TICK_ETERNITY;
s->res.wex = TICK_ETERNITY;
s->res.analyse_exp = TICK_ETERNITY;
s->si[1].hcto = TICK_ETERNITY;
}
Commit Message:
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GpuChannelHost::Connect(
const IPC::ChannelHandle& channel_handle,
base::ProcessHandle client_process_for_gpu) {
DCHECK(factory_->IsMainThread());
scoped_refptr<base::MessageLoopProxy> io_loop = factory_->GetIOLoopProxy();
channel_.reset(new IPC::SyncChannel(
channel_handle, IPC::Channel::MODE_CLIENT, NULL,
io_loop, true,
factory_->GetShutDownEvent()));
sync_filter_ = new IPC::SyncMessageFilter(
factory_->GetShutDownEvent());
channel_->AddFilter(sync_filter_.get());
channel_filter_ = new MessageFilter(this);
channel_->AddFilter(channel_filter_.get());
state_ = kConnected;
Send(new GpuChannelMsg_Initialize(client_process_for_gpu));
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: ntpd_time_stepped(void)
{
u_int saved_mon_enabled;
/*
* flush the monitor MRU list which contains l_fp timestamps
* which should not be compared across the step.
*/
if (MON_OFF != mon_enabled) {
saved_mon_enabled = mon_enabled;
mon_stop(MON_OFF);
mon_start(saved_mon_enabled);
}
/* inform interpolating Windows code to allow time to go back */
#ifdef SYS_WINNT
win_time_stepped();
#endif
}
Commit Message: [Bug 1773] openssl not detected during ./configure.
[Bug 1774] Segfaults if cryptostats enabled and built without OpenSSL.
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual ~ResizingVideoSource() {}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SharedWorkerDevToolsAgentHost::WorkerRestarted(
SharedWorkerHost* worker_host) {
DCHECK_EQ(WORKER_TERMINATED, state_);
DCHECK(!worker_host_);
state_ = WORKER_NOT_READY;
worker_host_ = worker_host;
for (DevToolsSession* session : sessions())
session->SetRenderer(GetProcess(), nullptr);
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
Target: 1
Example 2:
Code: ar6000_regDomain_event(struct ar6_softc *ar, u32 regCode)
{
A_PRINTF("AR6000 Reg Code = 0x%x\n", regCode);
ar->arRegCode = regCode;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
{
struct userfaultfd_ctx *ctx = file->private_data;
unsigned int ret;
poll_wait(file, &ctx->fd_wqh, wait);
switch (ctx->state) {
case UFFD_STATE_WAIT_API:
return POLLERR;
case UFFD_STATE_RUNNING:
/*
* poll() never guarantees that read won't block.
* userfaults can be waken before they're read().
*/
if (unlikely(!(file->f_flags & O_NONBLOCK)))
return POLLERR;
/*
* lockless access to see if there are pending faults
* __pollwait last action is the add_wait_queue but
* the spin_unlock would allow the waitqueue_active to
* pass above the actual list_add inside
* add_wait_queue critical section. So use a full
* memory barrier to serialize the list_add write of
* add_wait_queue() with the waitqueue_active read
* below.
*/
ret = 0;
smp_mb();
if (waitqueue_active(&ctx->fault_pending_wqh))
ret = POLLIN;
else if (waitqueue_active(&ctx->event_wqh))
ret = POLLIN;
return ret;
default:
WARN_ON_ONCE(1);
return POLLERR;
}
}
Commit Message: userfaultfd: non-cooperative: fix fork use after free
When reading the event from the uffd, we put it on a temporary
fork_event list to detect if we can still access it after releasing and
retaking the event_wqh.lock.
If fork aborts and removes the event from the fork_event all is fine as
long as we're still in the userfault read context and fork_event head is
still alive.
We've to put the event allocated in the fork kernel stack, back from
fork_event list-head to the event_wqh head, before returning from
userfaultfd_ctx_read, because the fork_event head lifetime is limited to
the userfaultfd_ctx_read stack lifetime.
Forgetting to move the event back to its event_wqh place then results in
__remove_wait_queue(&ctx->event_wqh, &ewq->wq); in
userfaultfd_event_wait_completion to remove it from a head that has been
already freed from the reader stack.
This could only happen if resolve_userfault_fork failed (for example if
there are no file descriptors available to allocate the fork uffd). If
it succeeded it was put back correctly.
Furthermore, after find_userfault_evt receives a fork event, the forked
userfault context in fork_nctx and uwq->msg.arg.reserved.reserved1 can
be released by the fork thread as soon as the event_wqh.lock is
released. Taking a reference on the fork_nctx before dropping the lock
prevents an use after free in resolve_userfault_fork().
If the fork side aborted and it already released everything, we still
try to succeed resolve_userfault_fork(), if possible.
Fixes: 893e26e61d04eac9 ("userfaultfd: non-cooperative: Add fork() event")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Andrea Arcangeli <[email protected]>
Reported-by: Mark Rutland <[email protected]>
Tested-by: Mark Rutland <[email protected]>
Cc: Pavel Emelyanov <[email protected]>
Cc: Mike Rapoport <[email protected]>
Cc: "Dr. David Alan Gilbert" <[email protected]>
Cc: Mike Kravetz <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int hci_uart_set_proto(struct hci_uart *hu, int id)
{
const struct hci_uart_proto *p;
int err;
p = hci_uart_get_proto(id);
if (!p)
return -EPROTONOSUPPORT;
hu->proto = p;
set_bit(HCI_UART_PROTO_READY, &hu->flags);
err = hci_uart_register_dev(hu);
if (err) {
clear_bit(HCI_UART_PROTO_READY, &hu->flags);
return err;
}
return 0;
}
Commit Message: Bluetooth: hci_ldisc: Postpone HCI_UART_PROTO_READY bit set in hci_uart_set_proto()
task A: task B:
hci_uart_set_proto flush_to_ldisc
- p->open(hu) -> h5_open //alloc h5 - receive_buf
- set_bit HCI_UART_PROTO_READY - tty_port_default_receive_buf
- hci_uart_register_dev - tty_ldisc_receive_buf
- hci_uart_tty_receive
- test_bit HCI_UART_PROTO_READY
- h5_recv
- clear_bit HCI_UART_PROTO_READY while() {
- p->open(hu) -> h5_close //free h5
- h5_rx_3wire_hdr
- h5_reset() //use-after-free
}
It could use ioctl to set hci uart proto, but there is
a use-after-free issue when hci_uart_register_dev() fail in
hci_uart_set_proto(), see stack above, fix this by setting
HCI_UART_PROTO_READY bit only when hci_uart_register_dev()
return success.
Reported-by: [email protected]
Signed-off-by: Kefeng Wang <[email protected]>
Reviewed-by: Jeremy Cline <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: void sas_scsi_recover_host(struct Scsi_Host *shost)
{
struct sas_ha_struct *ha = SHOST_TO_SAS_HA(shost);
LIST_HEAD(eh_work_q);
int tries = 0;
bool retry;
retry:
tries++;
retry = true;
spin_lock_irq(shost->host_lock);
list_splice_init(&shost->eh_cmd_q, &eh_work_q);
spin_unlock_irq(shost->host_lock);
SAS_DPRINTK("Enter %s busy: %d failed: %d\n",
__func__, atomic_read(&shost->host_busy), shost->host_failed);
/*
* Deal with commands that still have SAS tasks (i.e. they didn't
* complete via the normal sas_task completion mechanism),
* SAS_HA_FROZEN gives eh dominion over all sas_task completion.
*/
set_bit(SAS_HA_FROZEN, &ha->state);
sas_eh_handle_sas_errors(shost, &eh_work_q);
clear_bit(SAS_HA_FROZEN, &ha->state);
if (list_empty(&eh_work_q))
goto out;
/*
* Now deal with SCSI commands that completed ok but have a an error
* code (and hopefully sense data) attached. This is roughly what
* scsi_unjam_host does, but we skip scsi_eh_abort_cmds because any
* command we see here has no sas_task and is thus unknown to the HA.
*/
sas_ata_eh(shost, &eh_work_q, &ha->eh_done_q);
if (!scsi_eh_get_sense(&eh_work_q, &ha->eh_done_q))
scsi_eh_ready_devs(shost, &eh_work_q, &ha->eh_done_q);
out:
sas_eh_handle_resets(shost);
/* now link into libata eh --- if we have any ata devices */
sas_ata_strategy_handler(shost);
scsi_eh_flush_done_q(&ha->eh_done_q);
/* check if any new eh work was scheduled during the last run */
spin_lock_irq(&ha->lock);
if (ha->eh_active == 0) {
shost->host_eh_scheduled = 0;
retry = false;
}
spin_unlock_irq(&ha->lock);
if (retry)
goto retry;
SAS_DPRINTK("--- Exit %s: busy: %d failed: %d tries: %d\n",
__func__, atomic_read(&shost->host_busy),
shost->host_failed, tries);
}
Commit Message: scsi: libsas: defer ata device eh commands to libata
When ata device doing EH, some commands still attached with tasks are
not passed to libata when abort failed or recover failed, so libata did
not handle these commands. After these commands done, sas task is freed,
but ata qc is not freed. This will cause ata qc leak and trigger a
warning like below:
WARNING: CPU: 0 PID: 28512 at drivers/ata/libata-eh.c:4037
ata_eh_finish+0xb4/0xcc
CPU: 0 PID: 28512 Comm: kworker/u32:2 Tainted: G W OE 4.14.0#1
......
Call trace:
[<ffff0000088b7bd0>] ata_eh_finish+0xb4/0xcc
[<ffff0000088b8420>] ata_do_eh+0xc4/0xd8
[<ffff0000088b8478>] ata_std_error_handler+0x44/0x8c
[<ffff0000088b8068>] ata_scsi_port_error_handler+0x480/0x694
[<ffff000008875fc4>] async_sas_ata_eh+0x4c/0x80
[<ffff0000080f6be8>] async_run_entry_fn+0x4c/0x170
[<ffff0000080ebd70>] process_one_work+0x144/0x390
[<ffff0000080ec100>] worker_thread+0x144/0x418
[<ffff0000080f2c98>] kthread+0x10c/0x138
[<ffff0000080855dc>] ret_from_fork+0x10/0x18
If ata qc leaked too many, ata tag allocation will fail and io blocked
for ever.
As suggested by Dan Williams, defer ata device commands to libata and
merge sas_eh_finish_cmd() with sas_eh_defer_cmd(). libata will handle
ata qcs correctly after this.
Signed-off-by: Jason Yan <[email protected]>
CC: Xiaofei Tan <[email protected]>
CC: John Garry <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Dan Williams <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: pgp_enumerate_blob(sc_card_t *card, pgp_blob_t *blob)
{
const u8 *in;
int r;
if (blob->files != NULL)
return SC_SUCCESS;
if ((r = pgp_read_blob(card, blob)) < 0)
return r;
in = blob->data;
while ((int) blob->len > (in - blob->data)) {
unsigned int cla, tag, tmptag;
size_t len;
const u8 *data = in;
pgp_blob_t *new;
r = sc_asn1_read_tag(&data, blob->len - (in - blob->data),
&cla, &tag, &len);
if (r < 0 || data == NULL) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Unexpected end of contents\n");
return SC_ERROR_OBJECT_NOT_VALID;
}
/* undo ASN1's split of tag & class */
for (tmptag = tag; tmptag > 0x0FF; tmptag >>= 8) {
cla <<= 8;
}
tag |= cla;
/* Awful hack for composite DOs that have
* a TLV with the DO's id encompassing the
* entire blob. Example: Yubikey Neo */
if (tag == blob->id) {
in = data;
continue;
}
/* create fake file system hierarchy by
* using constructed DOs as DF */
if ((new = pgp_new_blob(card, blob, tag, sc_file_new())) == NULL)
return SC_ERROR_OUT_OF_MEMORY;
pgp_set_blob(new, data, len);
in = data + len;
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: standard_test(png_store* PNG_CONST psIn, png_uint_32 PNG_CONST id,
int do_interlace, int use_update_info)
{
standard_display d;
context(psIn, fault);
/* Set up the display (stack frame) variables from the arguments to the
* function and initialize the locals that are filled in later.
*/
standard_display_init(&d, psIn, id, do_interlace, use_update_info);
/* Everything is protected by a Try/Catch. The functions called also
* typically have local Try/Catch blocks.
*/
Try
{
png_structp pp;
png_infop pi;
/* Get a png_struct for reading the image. This will throw an error if it
* fails, so we don't need to check the result.
*/
pp = set_store_for_read(d.ps, &pi, d.id,
d.do_interlace ? (d.ps->progressive ?
"pngvalid progressive deinterlacer" :
"pngvalid sequential deinterlacer") : (d.ps->progressive ?
"progressive reader" : "sequential reader"));
/* Initialize the palette correctly from the png_store_file. */
standard_palette_init(&d);
/* Introduce the correct read function. */
if (d.ps->progressive)
{
png_set_progressive_read_fn(pp, &d, standard_info, progressive_row,
standard_end);
/* Now feed data into the reader until we reach the end: */
store_progressive_read(d.ps, pp, pi);
}
else
{
/* Note that this takes the store, not the display. */
png_set_read_fn(pp, d.ps, store_read);
/* Check the header values: */
png_read_info(pp, pi);
/* The code tests both versions of the images that the sequential
* reader can produce.
*/
standard_info_imp(&d, pp, pi, 2 /*images*/);
/* Need the total bytes in the image below; we can't get to this point
* unless the PNG file values have been checked against the expected
* values.
*/
{
sequential_row(&d, pp, pi, 0, 1);
/* After the last pass loop over the rows again to check that the
* image is correct.
*/
if (!d.speed)
{
standard_text_validate(&d, pp, pi, 1/*check_end*/);
standard_image_validate(&d, pp, 0, 1);
}
else
d.ps->validated = 1;
}
}
/* Check for validation. */
if (!d.ps->validated)
png_error(pp, "image read failed silently");
/* Successful completion. */
}
Catch(fault)
d.ps = fault; /* make sure this hasn't been clobbered. */
/* In either case clean up the store. */
store_read_reset(d.ps);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: static void nfnl_err_del(struct nfnl_err *nfnl_err)
{
list_del(&nfnl_err->head);
kfree(nfnl_err);
}
Commit Message: netfilter: nfnetlink: correctly validate length of batch messages
If nlh->nlmsg_len is zero then an infinite loop is triggered because
'skb_pull(skb, msglen);' pulls zero bytes.
The calculation in nlmsg_len() underflows if 'nlh->nlmsg_len <
NLMSG_HDRLEN' which bypasses the length validation and will later
trigger an out-of-bound read.
If the length validation does fail then the malformed batch message is
copied back to userspace. However, we cannot do this because the
nlh->nlmsg_len can be invalid. This leads to an out-of-bounds read in
netlink_ack:
[ 41.455421] ==================================================================
[ 41.456431] BUG: KASAN: slab-out-of-bounds in memcpy+0x1d/0x40 at addr ffff880119e79340
[ 41.456431] Read of size 4294967280 by task a.out/987
[ 41.456431] =============================================================================
[ 41.456431] BUG kmalloc-512 (Not tainted): kasan: bad access detected
[ 41.456431] -----------------------------------------------------------------------------
...
[ 41.456431] Bytes b4 ffff880119e79310: 00 00 00 00 d5 03 00 00 b0 fb fe ff 00 00 00 00 ................
[ 41.456431] Object ffff880119e79320: 20 00 00 00 10 00 05 00 00 00 00 00 00 00 00 00 ...............
[ 41.456431] Object ffff880119e79330: 14 00 0a 00 01 03 fc 40 45 56 11 22 33 10 00 05 .......@EV."3...
[ 41.456431] Object ffff880119e79340: f0 ff ff ff 88 99 aa bb 00 14 00 0a 00 06 fe fb ................
^^ start of batch nlmsg with
nlmsg_len=4294967280
...
[ 41.456431] Memory state around the buggy address:
[ 41.456431] ffff880119e79400: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 41.456431] ffff880119e79480: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 41.456431] >ffff880119e79500: 00 00 00 00 fc fc fc fc fc fc fc fc fc fc fc fc
[ 41.456431] ^
[ 41.456431] ffff880119e79580: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 41.456431] ffff880119e79600: fc fc fc fc fc fc fc fc fc fc fb fb fb fb fb fb
[ 41.456431] ==================================================================
Fix this with better validation of nlh->nlmsg_len and by setting
NFNL_BATCH_FAILURE if any batch message fails length validation.
CAP_NET_ADMIN is required to trigger the bugs.
Fixes: 9ea2aa8b7dba ("netfilter: nfnetlink: validate nfnetlink header from batch")
Signed-off-by: Phil Turnbull <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int sched_group_set_shares(struct task_group *tg, unsigned long shares)
{
int i;
/*
* We can't change the weight of the root cgroup.
*/
if (!tg->se[0])
return -EINVAL;
shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
mutex_lock(&shares_mutex);
if (tg->shares == shares)
goto done;
tg->shares = shares;
for_each_possible_cpu(i) {
struct rq *rq = cpu_rq(i);
struct sched_entity *se = tg->se[i];
struct rq_flags rf;
/* Propagate contribution to hierarchy */
rq_lock_irqsave(rq, &rf);
update_rq_clock(rq);
for_each_sched_entity(se) {
update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
update_cfs_group(se);
}
rq_unlock_irqrestore(rq, &rf);
}
done:
mutex_unlock(&shares_mutex);
return 0;
}
Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c
Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the
scheduler under high loads, starting at around the v4.18 time frame,
and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list
manipulation.
Do a (manual) revert of:
a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
It turns out that the list_del_leaf_cfs_rq() introduced by this commit
is a surprising property that was not considered in followup commits
such as:
9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list")
As Vincent Guittot explains:
"I think that there is a bigger problem with commit a9e7f6544b9c and
cfs_rq throttling:
Let take the example of the following topology TG2 --> TG1 --> root:
1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1
cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in
one path because it has never been used and can't be throttled so
tmp_alone_branch will point to leaf_cfs_rq_list at the end.
2) Then TG1 is throttled
3) and we add TG3 as a new child of TG1.
4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1
cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list.
With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list.
So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1
cfs_rq is removed from the list.
Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list
but tmp_alone_branch still points to TG3 cfs_rq because its throttled
parent can't be enqueued when the lock is released.
tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should.
So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch
points on another TG cfs_rq, the next TG cfs_rq that will be added,
will be linked outside rq->leaf_cfs_rq_list - which is bad.
In addition, we can break the ordering of the cfs_rq in
rq->leaf_cfs_rq_list but this ordering is used to update and
propagate the update from leaf down to root."
Instead of trying to work through all these cases and trying to reproduce
the very high loads that produced the lockup to begin with, simplify
the code temporarily by reverting a9e7f6544b9c - which change was clearly
not thought through completely.
This (hopefully) gives us a kernel that doesn't lock up so people
can continue to enjoy their holidays without worrying about regressions. ;-)
[ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ]
Analyzed-by: Xie XiuQi <[email protected]>
Analyzed-by: Vincent Guittot <[email protected]>
Reported-by: Zhipeng Xie <[email protected]>
Reported-by: Sargun Dhillon <[email protected]>
Reported-by: Xie XiuQi <[email protected]>
Tested-by: Zhipeng Xie <[email protected]>
Tested-by: Sargun Dhillon <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Acked-by: Vincent Guittot <[email protected]>
Cc: <[email protected]> # v4.13+
Cc: Bin Li <[email protected]>
Cc: Mike Galbraith <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-400
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int handle_vmptrst(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t vmcs_gva;
struct x86_exception e;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, true, &vmcs_gva))
return 1;
/* ok to use *_system, as hardware has verified cpl=0 */
if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
(void *)&to_vmx(vcpu)->nested.current_vmptr,
sizeof(u64), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions
VMX instructions executed inside a L1 VM will always trigger a VM exit
even when executed with cpl 3. This means we must perform the
privilege check in software.
Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks")
Cc: [email protected]
Signed-off-by: Felix Wilhelm <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static int udf_char_to_ustr(struct ustr *dest, const uint8_t *src, int strlen)
{
if ((!dest) || (!src) || (!strlen) || (strlen > UDF_NAME_LEN - 2))
return 0;
memset(dest, 0, sizeof(struct ustr));
memcpy(dest->u_name, src, strlen);
dest->u_cmpID = 0x08;
dest->u_len = strlen;
return strlen;
}
Commit Message: udf: Check path length when reading symlink
Symlink reading code does not check whether the resulting path fits into
the page provided by the generic code. This isn't as easy as just
checking the symlink size because of various encoding conversions we
perform on path. So we have to check whether there is still enough space
in the buffer on the fly.
CC: [email protected]
Reported-by: Carl Henrik Lunde <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-17
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PHP_FUNCTION(mdecrypt_generic)
{
zval *mcryptind;
char *data;
int data_len;
php_mcrypt *pm;
char* data_s;
int block_size, data_size;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pm, php_mcrypt * , &mcryptind, -1, "MCrypt", le_mcrypt);
PHP_MCRYPT_INIT_CHECK
if (data_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed");
RETURN_FALSE
}
/* Check blocksize */
if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */
block_size = mcrypt_enc_get_block_size(pm->td);
data_size = (((data_len - 1) / block_size) + 1) * block_size;
data_s = emalloc(data_size + 1);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
} else { /* It's not a block algorithm */
data_size = data_len;
data_s = emalloc(data_size + 1);
memset(data_s, 0, data_size);
memcpy(data_s, data, data_len);
}
mdecrypt_generic(pm->td, data_s, data_size);
RETVAL_STRINGL(data_s, data_size, 1);
efree(data_s);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool asn1_write_DATA_BLOB_LDAPString(struct asn1_data *data, const DATA_BLOB *s)
{
asn1_write(data, s->data, s->length);
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399
Target: 1
Example 2:
Code: void nfs_idmap_quit(void)
{
nfs_idmap_quit_keyring();
}
Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse
A previous patch added a ->match_preparse() method to the key type. This is
allowed to override the function called by the iteration algorithm.
Therefore, we can just set a default that simply checks for an exact match of
the key description with the original criterion data and allow match_preparse
to override it as needed.
The key_type::match op is then redundant and can be removed, as can the
user_match() function.
Signed-off-by: David Howells <[email protected]>
Acked-by: Vivek Goyal <[email protected]>
CWE ID: CWE-476
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
int compno;
int tileno;
jpc_dec_tile_t *tile;
jpc_dec_tcomp_t *tcomp;
int htileno;
int vtileno;
jpc_dec_cmpt_t *cmpt;
dec->xstart = siz->xoff;
dec->ystart = siz->yoff;
dec->xend = siz->width;
dec->yend = siz->height;
dec->tilewidth = siz->tilewidth;
dec->tileheight = siz->tileheight;
dec->tilexoff = siz->tilexoff;
dec->tileyoff = siz->tileyoff;
dec->numcomps = siz->numcomps;
if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
return -1;
}
if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
++cmpt) {
cmpt->prec = siz->comps[compno].prec;
cmpt->sgnd = siz->comps[compno].sgnd;
cmpt->hstep = siz->comps[compno].hsamp;
cmpt->vstep = siz->comps[compno].vsamp;
cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -
JPC_CEILDIV(dec->xstart, cmpt->hstep);
cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -
JPC_CEILDIV(dec->ystart, cmpt->vstep);
cmpt->hsubstep = 0;
cmpt->vsubstep = 0;
}
dec->image = 0;
dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);
dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
dec->numtiles = dec->numhtiles * dec->numvtiles;
JAS_DBGLOG(10, ("numtiles = %d; numhtiles = %d; numvtiles = %d;\n",
dec->numtiles, dec->numhtiles, dec->numvtiles));
if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {
return -1;
}
for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
++tile) {
htileno = tileno % dec->numhtiles;
vtileno = tileno / dec->numhtiles;
tile->realmode = 0;
tile->state = JPC_TILE_INIT;
tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,
dec->xstart);
tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,
dec->ystart);
tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *
dec->tilewidth, dec->xend);
tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *
dec->tileheight, dec->yend);
tile->numparts = 0;
tile->partno = 0;
tile->pkthdrstream = 0;
tile->pkthdrstreampos = 0;
tile->pptstab = 0;
tile->cp = 0;
tile->pi = 0;
if (!(tile->tcomps = jas_alloc2(dec->numcomps,
sizeof(jpc_dec_tcomp_t)))) {
return -1;
}
for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
tcomp->rlvls = 0;
tcomp->numrlvls = 0;
tcomp->data = 0;
tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);
tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);
tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);
tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);
tcomp->tsfb = 0;
}
}
dec->pkthdrstreams = 0;
/* We should expect to encounter other main header marker segments
or an SOT marker segment next. */
dec->state = JPC_MH;
return 0;
}
Commit Message: Fixed another integer overflow problem.
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: nfs4_xdr_dec_getacl(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs_getaclres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_getacl(xdr, rqstp, &res->acl_len);
out:
return status;
}
Commit Message: NFSv4: include bitmap in nfsv4 get acl data
The NFSv4 bitmap size is unbounded: a server can return an arbitrary
sized bitmap in an FATTR4_WORD0_ACL request. Replace using the
nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server
with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data
xdr length to the (cached) acl page data.
This is a general solution to commit e5012d1f "NFSv4.1: update
nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead
when getting ACLs.
Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr
was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved.
Cc: [email protected]
Signed-off-by: Andy Adamson <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: int js_gettop(js_State *J)
{
return TOP - BOT;
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Resource::~Resource() {
}
Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed,
BUG=85808
Review URL: http://codereview.chromium.org/7196001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: Block Tifinagh + Latin mix
BUG=chromium:722639
TEST=components_unittests --gtest_filter=*IDNToU*
Review-Url: https://codereview.chromium.org/2894313002
Cr-Commit-Position: refs/heads/master@{#474199}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void V8TestObject::NullableLongSequenceMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_nullableLongSequenceMethod");
test_object_v8_internal::NullableLongSequenceMethodMethod(info);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int _nfs4_do_open_reclaim(struct nfs_open_context *ctx, struct nfs4_state *state)
{
struct nfs_delegation *delegation;
struct nfs4_opendata *opendata;
int delegation_type = 0;
int status;
opendata = nfs4_open_recoverdata_alloc(ctx, state);
if (IS_ERR(opendata))
return PTR_ERR(opendata);
opendata->o_arg.claim = NFS4_OPEN_CLAIM_PREVIOUS;
opendata->o_arg.fh = NFS_FH(state->inode);
rcu_read_lock();
delegation = rcu_dereference(NFS_I(state->inode)->delegation);
if (delegation != NULL && test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) != 0)
delegation_type = delegation->type;
rcu_read_unlock();
opendata->o_arg.u.delegation_type = delegation_type;
status = nfs4_open_recover(opendata, state);
nfs4_opendata_put(opendata);
return status;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_FUNCTION(locale_get_display_script)
{
get_icu_disp_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
Target: 1
Example 2:
Code: static v8::Handle<v8::Value> createAttrGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info)
{
INC_STATS("DOM.TestObj.create._get");
TestObj* imp = V8TestObj::toNative(info.Holder());
return v8Boolean(imp->isCreate());
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void UDPSocketWin::Core::WriteDelegate::OnObjectSignaled(HANDLE object) {
DCHECK_EQ(object, core_->write_overlapped_.hEvent);
if (core_->socket_)
core_->socket_->DidCompleteWrite();
core_->Release();
}
Commit Message: Map posix error codes in bind better, and fix one windows mapping.
r=wtc
BUG=330233
Review URL: https://codereview.chromium.org/101193008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: DictionaryValue* ExtensionTabUtil::CreateTabValue(
const WebContents* contents,
TabStripModel* tab_strip,
int tab_index,
const Extension* extension) {
bool has_permission = extension && extension->HasAPIPermissionForTab(
GetTabId(contents), APIPermission::kTab);
return CreateTabValue(contents, tab_strip, tab_index,
has_permission ? INCLUDE_PRIVACY_SENSITIVE_FIELDS :
OMIT_PRIVACY_SENSITIVE_FIELDS);
}
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
Target: 1
Example 2:
Code: MD5Init(struct MD5Context *ctx) {
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bytes[0] = 0;
ctx->bytes[1] = 0;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ImageLoader::dispatchPendingErrorEvent() {
if (!m_hasPendingErrorEvent)
return;
m_hasPendingErrorEvent = false;
if (element()->document().frame())
element()->dispatchEvent(Event::create(EventTypeNames::error));
updatedHasPendingEvent();
}
Commit Message: Move ImageLoader timer to frame-specific TaskRunnerTimer.
Move ImageLoader timer m_derefElementTimer to frame-specific TaskRunnerTimer.
This associates it with the frame's Networking timer task queue.
BUG=624694
Review-Url: https://codereview.chromium.org/2642103002
Cr-Commit-Position: refs/heads/master@{#444927}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual void scheduleBeginFrameAndCommit()
{
CCMainThread::postTask(m_proxy->createBeginFrameAndCommitTaskOnCCThread());
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 1
Example 2:
Code: int MakeFrontendID(const std::string& cc_sid,
const std::string& profile_sid) const {
return autofill_manager_->MakeFrontendID(cc_sid, profile_sid);
}
Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections.
Since Autofill does not fill field by field anymore, this simplifying
and deduping of suggestions is not useful anymore.
Bug: 858820
Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b
Reviewed-on: https://chromium-review.googlesource.com/1128255
Reviewed-by: Roger McFarlane <[email protected]>
Commit-Queue: Sebastien Seguin-Gagnon <[email protected]>
Cr-Commit-Position: refs/heads/master@{#573315}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: decode_set_vlan_vid(uint16_t vid, bool push_vlan_if_needed, struct ofpbuf *out)
{
if (vid & ~0xfff) {
return OFPERR_OFPBAC_BAD_ARGUMENT;
} else {
struct ofpact_vlan_vid *vlan_vid = ofpact_put_SET_VLAN_VID(out);
vlan_vid->vlan_vid = vid;
vlan_vid->push_vlan_if_needed = push_vlan_if_needed;
return 0;
}
}
Commit Message: ofp-actions: Avoid buffer overread in BUNDLE action decoding.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9052
Signed-off-by: Ben Pfaff <[email protected]>
Acked-by: Justin Pettit <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FrameImpl::GoBack() {
NOTIMPLEMENTED();
}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264
Target: 1
Example 2:
Code: bool DriveFsHost::Mount() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const AccountId& account_id = delegate_->GetAccountId();
if (mount_state_ || !account_id.HasAccountIdKey() ||
account_id.GetUserEmail().empty()) {
return false;
}
mount_state_ = std::make_unique<MountState>(this);
return true;
}
Commit Message: Add a fake DriveFS launcher client.
Using DriveFS requires building and deploying ChromeOS. Add a client for
the fake DriveFS launcher to allow the use of a real DriveFS from a
ChromeOS chroot to be used with a target_os="chromeos" build of chrome.
This connects to the fake DriveFS launcher using mojo over a unix domain
socket named by a command-line flag, using the launcher to create
DriveFS instances.
Bug: 848126
Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1
Reviewed-on: https://chromium-review.googlesource.com/1098434
Reviewed-by: Xiyuan Xia <[email protected]>
Commit-Queue: Sam McNally <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567513}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SavePayload(size_t handle, uint32_t *payload, uint32_t index)
{
mp4object *mp4 = (mp4object *)handle;
if (mp4 == NULL) return;
uint32_t *MP4buffer = NULL;
if (index < mp4->indexcount && mp4->mediafp && payload)
{
LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET);
fwrite(payload, 1, mp4->metasizes[index], mp4->mediafp);
}
return;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int process_line(URLContext *h, char *line, int line_count,
int *new_location)
{
HTTPContext *s = h->priv_data;
const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
char *tag, *p, *end, *method, *resource, *version;
int ret;
/* end of header */
if (line[0] == '\0') {
s->end_header = 1;
return 0;
}
p = line;
if (line_count == 0) {
if (s->is_connected_server) {
method = p;
while (*p && !av_isspace(*p))
p++;
*(p++) = '\0';
av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
if (s->method) {
if (av_strcasecmp(s->method, method)) {
av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
s->method, method);
return ff_http_averror(400, AVERROR(EIO));
}
} else {
av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
if (av_strcasecmp(auto_method, method)) {
av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
"(%s autodetected %s received)\n", auto_method, method);
return ff_http_averror(400, AVERROR(EIO));
}
if (!(s->method = av_strdup(method)))
return AVERROR(ENOMEM);
}
while (av_isspace(*p))
p++;
resource = p;
while (!av_isspace(*p))
p++;
*(p++) = '\0';
av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
if (!(s->resource = av_strdup(resource)))
return AVERROR(ENOMEM);
while (av_isspace(*p))
p++;
version = p;
while (*p && !av_isspace(*p))
p++;
*p = '\0';
if (av_strncasecmp(version, "HTTP/", 5)) {
av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
return ff_http_averror(400, AVERROR(EIO));
}
av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
} else {
while (!av_isspace(*p) && *p != '\0')
p++;
while (av_isspace(*p))
p++;
s->http_code = strtol(p, &end, 10);
av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
if ((ret = check_http_code(h, s->http_code, end)) < 0)
return ret;
}
} else {
while (*p != '\0' && *p != ':')
p++;
if (*p != ':')
return 1;
*p = '\0';
tag = line;
p++;
while (av_isspace(*p))
p++;
if (!av_strcasecmp(tag, "Location")) {
if ((ret = parse_location(s, p)) < 0)
return ret;
*new_location = 1;
} else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
s->filesize = strtoll(p, NULL, 10);
} else if (!av_strcasecmp(tag, "Content-Range")) {
parse_content_range(h, p);
} else if (!av_strcasecmp(tag, "Accept-Ranges") &&
!strncmp(p, "bytes", 5) &&
s->seekable == -1) {
h->is_streamed = 0;
} else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
!av_strncasecmp(p, "chunked", 7)) {
s->filesize = -1;
s->chunksize = 0;
} else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
ff_http_auth_handle_header(&s->auth_state, tag, p);
} else if (!av_strcasecmp(tag, "Authentication-Info")) {
ff_http_auth_handle_header(&s->auth_state, tag, p);
} else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
} else if (!av_strcasecmp(tag, "Connection")) {
if (!strcmp(p, "close"))
s->willclose = 1;
} else if (!av_strcasecmp(tag, "Server")) {
if (!av_strcasecmp(p, "AkamaiGHost")) {
s->is_akamai = 1;
} else if (!av_strncasecmp(p, "MediaGateway", 12)) {
s->is_mediagateway = 1;
}
} else if (!av_strcasecmp(tag, "Content-Type")) {
av_free(s->mime_type);
s->mime_type = av_strdup(p);
} else if (!av_strcasecmp(tag, "Set-Cookie")) {
if (parse_cookie(s, p, &s->cookie_dict))
av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
} else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
s->icy_metaint = strtoll(p, NULL, 10);
} else if (!av_strncasecmp(tag, "Icy-", 4)) {
if ((ret = parse_icy(s, tag, p)) < 0)
return ret;
} else if (!av_strcasecmp(tag, "Content-Encoding")) {
if ((ret = parse_content_encoding(h, p)) < 0)
return ret;
}
}
return 1;
}
Commit Message: http: make length/offset-related variables unsigned.
Fixes #5992, reported and found by Paul Cher <[email protected]>.
CWE ID: CWE-119
Target: 1
Example 2:
Code: ScriptPromise Notification::requestPermission(ScriptState* scriptState, NotificationPermissionCallback* deprecatedCallback)
{
ExecutionContext* context = scriptState->executionContext();
if (NotificationPermissionClient* permissionClient = NotificationPermissionClient::from(context))
return permissionClient->requestPermission(scriptState, deprecatedCallback);
ASSERT(context->activeDOMObjectsAreStopped());
return ScriptPromise();
}
Commit Message: Notification actions may have an icon url.
This is behind a runtime flag for two reasons:
* The implementation is incomplete.
* We're still evaluating the API design.
Intent to Implement and Ship: Notification Action Icons
https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ
BUG=581336
Review URL: https://codereview.chromium.org/1644573002
Cr-Commit-Position: refs/heads/master@{#374649}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct rtable *rt_dst_alloc(struct net_device *dev,
unsigned int flags, u16 type,
bool nopolicy, bool noxfrm, bool will_cache)
{
struct rtable *rt;
rt = dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK,
(will_cache ? 0 : DST_HOST) |
(nopolicy ? DST_NOPOLICY : 0) |
(noxfrm ? DST_NOXFRM : 0));
if (rt) {
rt->rt_genid = rt_genid_ipv4(dev_net(dev));
rt->rt_flags = flags;
rt->rt_type = type;
rt->rt_is_input = 0;
rt->rt_iif = 0;
rt->rt_pmtu = 0;
rt->rt_mtu_locked = 0;
rt->rt_gateway = 0;
rt->rt_uses_gateway = 0;
INIT_LIST_HEAD(&rt->rt_uncached);
rt->dst.output = ip_output;
if (flags & RTCF_LOCAL)
rt->dst.input = ip_local_deliver;
}
return rt;
}
Commit Message: inet: switch IP ID generator to siphash
According to Amit Klein and Benny Pinkas, IP ID generation is too weak
and might be used by attackers.
Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())
having 64bit key and Jenkins hash is risky.
It is time to switch to siphash and its 128bit keys.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: do_ed_script (char const *inname, char const *outname,
bool *outname_needs_removal, FILE *ofp)
{
static char const editor_program[] = EDITOR_PROGRAM;
file_offset beginning_of_this_line;
size_t chars_read;
FILE *tmpfp = 0;
char const *tmpname;
int tmpfd;
pid_t pid;
if (! dry_run && ! skip_rest_of_patch)
{
/* Write ed script to a temporary file. This causes ed to abort on
invalid commands such as when line numbers or ranges exceed the
number of available lines. When ed reads from a pipe, it rejects
invalid commands and treats the next line as a new command, which
can lead to arbitrary command execution. */
tmpfd = make_tempfile (&tmpname, 'e', NULL, O_RDWR | O_BINARY, 0);
if (tmpfd == -1)
pfatal ("Can't create temporary file %s", quotearg (tmpname));
tmpfp = fdopen (tmpfd, "w+b");
if (! tmpfp)
pfatal ("Can't open stream for file %s", quotearg (tmpname));
}
for (;;) {
char ed_command_letter;
beginning_of_this_line = file_tell (pfp);
chars_read = get_line ();
if (! chars_read) {
next_intuit_at(beginning_of_this_line,p_input_line);
break;
}
ed_command_letter = get_ed_command_letter (buf);
if (ed_command_letter) {
if (tmpfp)
if (! fwrite (buf, sizeof *buf, chars_read, tmpfp))
write_fatal ();
if (ed_command_letter != 'd' && ed_command_letter != 's') {
p_pass_comments_through = true;
while ((chars_read = get_line ()) != 0) {
if (tmpfp)
if (! fwrite (buf, sizeof *buf, chars_read, tmpfp))
write_fatal ();
if (chars_read == 2 && strEQ (buf, ".\n"))
break;
}
p_pass_comments_through = false;
}
}
else {
next_intuit_at(beginning_of_this_line,p_input_line);
break;
}
}
if (!tmpfp)
return;
if (fwrite ("w\nq\n", sizeof (char), (size_t) 4, tmpfp) == 0
|| fflush (tmpfp) != 0)
write_fatal ();
if (lseek (tmpfd, 0, SEEK_SET) == -1)
pfatal ("Can't rewind to the beginning of file %s", quotearg (tmpname));
if (! dry_run && ! skip_rest_of_patch) {
int exclusive = *outname_needs_removal ? 0 : O_EXCL;
*outname_needs_removal = true;
if (inerrno != ENOENT)
{
*outname_needs_removal = true;
copy_file (inname, outname, 0, exclusive, instat.st_mode, true);
}
sprintf (buf, "%s %s%s", editor_program,
verbosity == VERBOSE ? "" : "- ",
outname);
fflush (stdout);
pid = fork();
fflush (stdout);
else if (pid == 0)
{
dup2 (tmpfd, 0);
execl ("/bin/sh", "sh", "-c", buf, (char *) 0);
_exit (2);
}
else
}
else
{
int wstatus;
if (waitpid (pid, &wstatus, 0) == -1
|| ! WIFEXITED (wstatus)
|| WEXITSTATUS (wstatus) != 0)
fatal ("%s FAILED", editor_program);
}
}
Commit Message:
CWE ID: CWE-78
Target: 1
Example 2:
Code: static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/714
CWE ID: CWE-834
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: dissect_pktap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_tree *pktap_tree = NULL;
proto_item *ti = NULL;
tvbuff_t *next_tvb;
int offset = 0;
guint32 pkt_len, rectype, dlt;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PKTAP");
col_clear(pinfo->cinfo, COL_INFO);
pkt_len = tvb_get_letohl(tvb, offset);
col_add_fstr(pinfo->cinfo, COL_INFO, "PKTAP, %u byte header", pkt_len);
/* Dissect the packet */
ti = proto_tree_add_item(tree, proto_pktap, tvb, offset, pkt_len, ENC_NA);
pktap_tree = proto_item_add_subtree(ti, ett_pktap);
proto_tree_add_item(pktap_tree, hf_pktap_hdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
if (pkt_len < MIN_PKTAP_HDR_LEN) {
proto_tree_add_expert(tree, pinfo, &ei_pktap_hdrlen_too_short,
tvb, offset, 4);
return;
}
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_rectype, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
rectype = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_dlt, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
dlt = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ifname, tvb, offset, 24,
ENC_ASCII|ENC_NA);
offset += 24;
proto_tree_add_item(pktap_tree, hf_pktap_flags, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pfamily, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_llhdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_lltrlrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_cmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
offset += 20;
proto_tree_add_item(pktap_tree, hf_pktap_svc_class, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_iftype, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_ifunit, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_epid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ecmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
/*offset += 20;*/
if (rectype == PKT_REC_PACKET) {
next_tvb = tvb_new_subset_remaining(tvb, pkt_len);
dissector_try_uint(wtap_encap_dissector_table,
wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree);
}
}
Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr.
We now require that. Make it so.
Bug: 12440
Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76
Reviewed-on: https://code.wireshark.org/review/15424
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){
uint16 edge=0;
tsize_t written=0;
unsigned char* buffer=NULL;
tsize_t bufferoffset=0;
unsigned char* samplebuffer=NULL;
tsize_t samplebufferoffset=0;
tsize_t read=0;
uint16 i=0;
ttile_t tilecount=0;
/* tsize_t tilesize=0; */
ttile_t septilecount=0;
tsize_t septilesize=0;
#ifdef JPEG_SUPPORT
unsigned char* jpt;
float* xfloatp;
uint32 xuint32=0;
#endif
/* Fail if prior error (in particular, can't trust tiff_datasize) */
if (t2p->t2p_error != T2P_ERR_OK)
return(0);
edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0)
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
|| (t2p->pdf_compression == T2P_COMPRESS_JPEG)
#endif
)
){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
t2pWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(! t2p->pdf_ojpegdata){
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with "
"bad tables",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
if(edge!=0){
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[7]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff;
buffer[8]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff;
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[9]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff;
buffer[10]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff;
}
}
bufferoffset=t2p->pdf_ojpegdatalength;
bufferoffset+=TIFFReadRawTile(input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
((unsigned char*)buffer)[bufferoffset++]=0xff;
((unsigned char*)buffer)[bufferoffset++]=0xd9;
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG){
unsigned char table_end[2];
uint32 count = 0;
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate " TIFF_SIZE_FORMAT " bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(TIFF_SIZE_T) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0) {
if (count >= 4) {
int retTIFFReadRawTile;
/* Ignore EOI marker of JpegTables */
_TIFFmemcpy(buffer, jpt, count - 2);
bufferoffset += count - 2;
/* Store last 2 bytes of the JpegTables */
table_end[0] = buffer[bufferoffset-2];
table_end[1] = buffer[bufferoffset-1];
xuint32 = bufferoffset;
bufferoffset -= 2;
retTIFFReadRawTile= TIFFReadRawTile(
input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
if( retTIFFReadRawTile < 0 )
{
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
bufferoffset += retTIFFReadRawTile;
/* Overwrite SOI marker of image scan with previously */
/* saved end of JpegTables */
buffer[xuint32-2]=table_end[0];
buffer[xuint32-1]=table_end[1];
}
}
t2pWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
(void)0;
}
if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for "
"t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
} else {
if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
septilesize=TIFFTileSize(input);
septilecount=TIFFNumberOfTiles(input);
/* tilesize=septilesize*t2p->tiff_samplesperpixel; */
tilecount=septilecount/t2p->tiff_samplesperpixel;
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebufferoffset=0;
for(i=0;i<t2p->tiff_samplesperpixel;i++){
read =
TIFFReadEncodedTile(input,
tile + i*tilecount,
(tdata_t) &(samplebuffer[samplebufferoffset]),
septilesize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile + i*tilecount,
TIFFFileName(input));
_TIFFfree(samplebuffer);
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
samplebufferoffset+=read;
}
t2p_sample_planar_separate_to_contig(
t2p,
&(buffer[bufferoffset]),
samplebuffer,
samplebufferoffset);
bufferoffset+=samplebufferoffset;
_TIFFfree(samplebuffer);
}
if(buffer==NULL){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
(unsigned long) t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
TIFFError(TIFF2PDF_MODULE,
"No support for YCbCr to RGB in tile for %s",
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){
t2p_tile_collapse_left(
buffer,
TIFFTileRowSize(input),
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
t2p_disable(output);
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
}
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
}
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
switch(t2p->pdf_compression){
case T2P_COMPRESS_NONE:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
if (t2p->tiff_photometric==PHOTOMETRIC_YCBCR) {
uint16 hor = 0, ver = 0;
if (TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &hor, &ver)!=0) {
if (hor != 0 && ver != 0) {
TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, hor, ver);
}
}
if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
}
}
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */
if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else {
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
}
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
(void)0;
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
(void)0;
}
if(t2p->pdf_defaultcompressionquality != 0){
TIFFSetField(output,
TIFFTAG_JPEGQUALITY,
t2p->pdf_defaultcompressionquality);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
if(t2p->pdf_defaultcompressionquality%100 != 0){
TIFFSetField(output,
TIFFTAG_PREDICTOR,
t2p->pdf_defaultcompressionquality % 100);
}
if(t2p->pdf_defaultcompressionquality/100 != 0){
TIFFSetField(output,
TIFFTAG_ZIPQUALITY,
(t2p->pdf_defaultcompressionquality / 100));
}
break;
#endif
default:
break;
}
t2p_enable(output);
t2p->outputwritten = 0;
bufferoffset = TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer,
TIFFStripSize(output));
if (buffer != NULL) {
_TIFFfree(buffer);
buffer = NULL;
}
if (bufferoffset == -1) {
TIFFError(TIFF2PDF_MODULE,
"Error writing encoded tile to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
written = t2p->outputwritten;
return(written);
}
Commit Message: * tools/tiff2pdf.c: avoid potential heap-based overflow in
t2p_readwrite_pdf_image_tile().
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2640
CWE ID: CWE-189
Target: 1
Example 2:
Code: void DiceTurnSyncOnHelper::TurnSyncOnWithProfileMode(ProfileMode profile_mode) {
syncer::SyncPrefs sync_prefs(profile_->GetPrefs());
sync_prefs.SetSyncRequested(true);
switch (profile_mode) {
case ProfileMode::CURRENT_PROFILE: {
policy::UserPolicySigninService* policy_service =
policy::UserPolicySigninServiceFactory::GetForProfile(profile_);
policy_service->RegisterForPolicyWithAccountId(
account_info_.email, account_info_.account_id,
base::Bind(&DiceTurnSyncOnHelper::OnRegisteredForPolicy,
weak_pointer_factory_.GetWeakPtr()));
break;
}
case ProfileMode::NEW_PROFILE:
CreateNewSignedInProfile();
break;
}
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
struct buffer_head *exbh)
{
struct inode *inode = mpd->inode;
struct address_space *mapping = inode->i_mapping;
int blocks = exbh->b_size >> inode->i_blkbits;
sector_t pblock = exbh->b_blocknr, cur_logical;
struct buffer_head *head, *bh;
pgoff_t index, end;
struct pagevec pvec;
int nr_pages, i;
index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
pagevec_init(&pvec, 0);
while (index <= end) {
/* XXX: optimize tail */
nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
if (nr_pages == 0)
break;
for (i = 0; i < nr_pages; i++) {
struct page *page = pvec.pages[i];
index = page->index;
if (index > end)
break;
index++;
BUG_ON(!PageLocked(page));
BUG_ON(PageWriteback(page));
BUG_ON(!page_has_buffers(page));
bh = page_buffers(page);
head = bh;
/* skip blocks out of the range */
do {
if (cur_logical >= logical)
break;
cur_logical++;
} while ((bh = bh->b_this_page) != head);
do {
if (cur_logical >= logical + blocks)
break;
if (buffer_delay(bh) ||
buffer_unwritten(bh)) {
BUG_ON(bh->b_bdev != inode->i_sb->s_bdev);
if (buffer_delay(bh)) {
clear_buffer_delay(bh);
bh->b_blocknr = pblock;
} else {
/*
* unwritten already should have
* blocknr assigned. Verify that
*/
clear_buffer_unwritten(bh);
BUG_ON(bh->b_blocknr != pblock);
}
} else if (buffer_mapped(bh))
BUG_ON(bh->b_blocknr != pblock);
cur_logical++;
pblock++;
} while ((bh = bh->b_this_page) != head);
}
pagevec_release(&pvec);
}
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x),
Min(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
}
SkipDXTMipmaps(image, dds_info, 16);
return MagickTrue;
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void __free_event(struct perf_event *event)
{
if (!event->parent) {
if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
put_callchain_buffers();
}
perf_event_free_bpf_prog(event);
if (event->destroy)
event->destroy(event);
if (event->ctx)
put_ctx(event->ctx);
if (event->pmu) {
exclusive_event_destroy(event);
module_put(event->pmu->module);
}
call_rcu(&event->rcu_head, free_event_rcu);
}
Commit Message: perf: Fix race in swevent hash
There's a race on CPU unplug where we free the swevent hash array
while it can still have events on. This will result in a
use-after-free which is BAD.
Simply do not free the hash array on unplug. This leaves the thing
around and no use-after-free takes place.
When the last swevent dies, we do a for_each_possible_cpu() iteration
anyway to clean these up, at which time we'll free it, so no leakage
will occur.
Reported-by: Sasha Levin <[email protected]>
Tested-by: Sasha Levin <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Stephane Eranian <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Vince Weaver <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev)
{
struct rtnl_link_ifmap map = {
.mem_start = dev->mem_start,
.mem_end = dev->mem_end,
.base_addr = dev->base_addr,
.irq = dev->irq,
.dma = dev->dma,
.port = dev->if_port,
};
if (nla_put(skb, IFLA_MAP, sizeof(map), &map))
return -EMSGSIZE;
return 0;
}
Commit Message: net: fix infoleak in rtnetlink
The stack object “map” has a total size of 32 bytes. Its last 4
bytes are padding generated by compiler. These padding bytes are
not initialized and sent out via “nla_put”.
Signed-off-by: Kangjie Lu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: qboolean S_AL_Init( soundInterface_t *si )
{
#ifdef USE_OPENAL
const char* device = NULL;
const char* inputdevice = NULL;
int i;
if( !si ) {
return qfalse;
}
for (i = 0; i < MAX_RAW_STREAMS; i++) {
streamSourceHandles[i] = -1;
streamPlaying[i] = qfalse;
streamSources[i] = 0;
streamNumBuffers[i] = 0;
streamBufIndex[i] = 0;
}
s_alPrecache = Cvar_Get( "s_alPrecache", "1", CVAR_ARCHIVE );
s_alGain = Cvar_Get( "s_alGain", "1.0", CVAR_ARCHIVE );
s_alSources = Cvar_Get( "s_alSources", "96", CVAR_ARCHIVE );
s_alDopplerFactor = Cvar_Get( "s_alDopplerFactor", "1.0", CVAR_ARCHIVE );
s_alDopplerSpeed = Cvar_Get( "s_alDopplerSpeed", "9000", CVAR_ARCHIVE );
s_alMinDistance = Cvar_Get( "s_alMinDistance", "120", CVAR_CHEAT );
s_alMaxDistance = Cvar_Get("s_alMaxDistance", "1024", CVAR_CHEAT);
s_alRolloff = Cvar_Get( "s_alRolloff", "2", CVAR_CHEAT);
s_alGraceDistance = Cvar_Get("s_alGraceDistance", "512", CVAR_CHEAT);
s_alDriver = Cvar_Get( "s_alDriver", ALDRIVER_DEFAULT, CVAR_ARCHIVE | CVAR_LATCH );
s_alInputDevice = Cvar_Get( "s_alInputDevice", "", CVAR_ARCHIVE | CVAR_LATCH );
s_alDevice = Cvar_Get("s_alDevice", "", CVAR_ARCHIVE | CVAR_LATCH);
if( !QAL_Init( s_alDriver->string ) )
{
Com_Printf( "Failed to load library: \"%s\".\n", s_alDriver->string );
if( !Q_stricmp( s_alDriver->string, ALDRIVER_DEFAULT ) || !QAL_Init( ALDRIVER_DEFAULT ) ) {
return qfalse;
}
}
device = s_alDevice->string;
if(device && !*device)
device = NULL;
inputdevice = s_alInputDevice->string;
if(inputdevice && !*inputdevice)
inputdevice = NULL;
enumeration_all_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATE_ALL_EXT");
enumeration_ext = qalcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT");
if(enumeration_ext || enumeration_all_ext)
{
char devicenames[16384] = "";
const char *devicelist;
#ifdef _WIN32
const char *defaultdevice;
#endif
int curlen;
if(enumeration_all_ext)
{
devicelist = qalcGetString(NULL, ALC_ALL_DEVICES_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_ALL_DEVICES_SPECIFIER);
#endif
}
else
{
devicelist = qalcGetString(NULL, ALC_DEVICE_SPECIFIER);
#ifdef _WIN32
defaultdevice = qalcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
#endif
enumeration_ext = qtrue;
}
#ifdef _WIN32
if(!device && defaultdevice && !strcmp(defaultdevice, "Generic Hardware"))
device = "Generic Software";
#endif
if(devicelist)
{
while((curlen = strlen(devicelist)))
{
Q_strcat(devicenames, sizeof(devicenames), devicelist);
Q_strcat(devicenames, sizeof(devicenames), "\n");
devicelist += curlen + 1;
}
}
s_alAvailableDevices = Cvar_Get("s_alAvailableDevices", devicenames, CVAR_ROM | CVAR_NORESTART);
}
alDevice = qalcOpenDevice(device);
if( !alDevice && device )
{
Com_Printf( "Failed to open OpenAL device '%s', trying default.\n", device );
alDevice = qalcOpenDevice(NULL);
}
if( !alDevice )
{
QAL_Shutdown( );
Com_Printf( "Failed to open OpenAL device.\n" );
return qfalse;
}
alContext = qalcCreateContext( alDevice, NULL );
if( !alContext )
{
QAL_Shutdown( );
qalcCloseDevice( alDevice );
Com_Printf( "Failed to create OpenAL context.\n" );
return qfalse;
}
qalcMakeContextCurrent( alContext );
S_AL_BufferInit( );
S_AL_SrcInit( );
qalDistanceModel(AL_INVERSE_DISTANCE_CLAMPED);
qalDopplerFactor( s_alDopplerFactor->value );
qalSpeedOfSound( s_alDopplerSpeed->value );
#ifdef USE_VOIP
s_alCapture = Cvar_Get( "s_alCapture", "1", CVAR_ARCHIVE | CVAR_LATCH );
if (!s_alCapture->integer)
{
Com_Printf("OpenAL capture support disabled by user ('+set s_alCapture 1' to enable)\n");
}
#if USE_MUMBLE
else if (cl_useMumble->integer)
{
Com_Printf("OpenAL capture support disabled for Mumble support\n");
}
#endif
else
{
#ifdef __APPLE__
if (qalcCaptureOpenDevice == NULL)
#else
if (!qalcIsExtensionPresent(NULL, "ALC_EXT_capture"))
#endif
{
Com_Printf("No ALC_EXT_capture support, can't record audio.\n");
}
else
{
char inputdevicenames[16384] = "";
const char *inputdevicelist;
const char *defaultinputdevice;
int curlen;
capture_ext = qtrue;
inputdevicelist = qalcGetString(NULL, ALC_CAPTURE_DEVICE_SPECIFIER);
defaultinputdevice = qalcGetString(NULL, ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER);
if (inputdevicelist)
{
while((curlen = strlen(inputdevicelist)))
{
Q_strcat(inputdevicenames, sizeof(inputdevicenames), inputdevicelist);
Q_strcat(inputdevicenames, sizeof(inputdevicenames), "\n");
inputdevicelist += curlen + 1;
}
}
s_alAvailableInputDevices = Cvar_Get("s_alAvailableInputDevices", inputdevicenames, CVAR_ROM | CVAR_NORESTART);
Com_Printf("OpenAL default capture device is '%s'\n", defaultinputdevice ? defaultinputdevice : "none");
alCaptureDevice = qalcCaptureOpenDevice(inputdevice, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
if( !alCaptureDevice && inputdevice )
{
Com_Printf( "Failed to open OpenAL Input device '%s', trying default.\n", inputdevice );
alCaptureDevice = qalcCaptureOpenDevice(NULL, 48000, AL_FORMAT_MONO16, VOIP_MAX_PACKET_SAMPLES*4);
}
Com_Printf( "OpenAL capture device %s.\n",
(alCaptureDevice == NULL) ? "failed to open" : "opened");
}
}
#endif
si->Shutdown = S_AL_Shutdown;
si->StartSound = S_AL_StartSound;
si->StartLocalSound = S_AL_StartLocalSound;
si->StartBackgroundTrack = S_AL_StartBackgroundTrack;
si->StopBackgroundTrack = S_AL_StopBackgroundTrack;
si->RawSamples = S_AL_RawSamples;
si->StopAllSounds = S_AL_StopAllSounds;
si->ClearLoopingSounds = S_AL_ClearLoopingSounds;
si->AddLoopingSound = S_AL_AddLoopingSound;
si->AddRealLoopingSound = S_AL_AddRealLoopingSound;
si->StopLoopingSound = S_AL_StopLoopingSound;
si->Respatialize = S_AL_Respatialize;
si->UpdateEntityPosition = S_AL_UpdateEntityPosition;
si->Update = S_AL_Update;
si->DisableSounds = S_AL_DisableSounds;
si->BeginRegistration = S_AL_BeginRegistration;
si->RegisterSound = S_AL_RegisterSound;
si->ClearSoundBuffer = S_AL_ClearSoundBuffer;
si->SoundInfo = S_AL_SoundInfo;
si->SoundList = S_AL_SoundList;
#ifdef USE_VOIP
si->StartCapture = S_AL_StartCapture;
si->AvailableCaptureSamples = S_AL_AvailableCaptureSamples;
si->Capture = S_AL_Capture;
si->StopCapture = S_AL_StopCapture;
si->MasterGain = S_AL_MasterGain;
#endif
return qtrue;
#else
return qfalse;
#endif
}
Commit Message: Don't open .pk3 files as OpenAL drivers.
CWE ID: CWE-269
Target: 1
Example 2:
Code: int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
struct audit_context *actx)
{
struct context *ctxt;
struct mls_level *level;
struct selinux_audit_rule *rule = vrule;
int match = 0;
if (!rule) {
audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"selinux_audit_rule_match: missing rule\n");
return -ENOENT;
}
read_lock(&policy_rwlock);
if (rule->au_seqno < latest_granting) {
audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"selinux_audit_rule_match: stale rule\n");
match = -ESTALE;
goto out;
}
ctxt = sidtab_search(&sidtab, sid);
if (!ctxt) {
audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"selinux_audit_rule_match: unrecognized SID %d\n",
sid);
match = -ENOENT;
goto out;
}
/* a field/op pair that is not caught here will simply fall through
without a match */
switch (field) {
case AUDIT_SUBJ_USER:
case AUDIT_OBJ_USER:
switch (op) {
case Audit_equal:
match = (ctxt->user == rule->au_ctxt.user);
break;
case Audit_not_equal:
match = (ctxt->user != rule->au_ctxt.user);
break;
}
break;
case AUDIT_SUBJ_ROLE:
case AUDIT_OBJ_ROLE:
switch (op) {
case Audit_equal:
match = (ctxt->role == rule->au_ctxt.role);
break;
case Audit_not_equal:
match = (ctxt->role != rule->au_ctxt.role);
break;
}
break;
case AUDIT_SUBJ_TYPE:
case AUDIT_OBJ_TYPE:
switch (op) {
case Audit_equal:
match = (ctxt->type == rule->au_ctxt.type);
break;
case Audit_not_equal:
match = (ctxt->type != rule->au_ctxt.type);
break;
}
break;
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
level = ((field == AUDIT_SUBJ_SEN ||
field == AUDIT_OBJ_LEV_LOW) ?
&ctxt->range.level[0] : &ctxt->range.level[1]);
switch (op) {
case Audit_equal:
match = mls_level_eq(&rule->au_ctxt.range.level[0],
level);
break;
case Audit_not_equal:
match = !mls_level_eq(&rule->au_ctxt.range.level[0],
level);
break;
case Audit_lt:
match = (mls_level_dom(&rule->au_ctxt.range.level[0],
level) &&
!mls_level_eq(&rule->au_ctxt.range.level[0],
level));
break;
case Audit_le:
match = mls_level_dom(&rule->au_ctxt.range.level[0],
level);
break;
case Audit_gt:
match = (mls_level_dom(level,
&rule->au_ctxt.range.level[0]) &&
!mls_level_eq(level,
&rule->au_ctxt.range.level[0]));
break;
case Audit_ge:
match = mls_level_dom(level,
&rule->au_ctxt.range.level[0]);
break;
}
}
out:
read_unlock(&policy_rwlock);
return match;
}
Commit Message: SELinux: Fix kernel BUG on empty security contexts.
Setting an empty security context (length=0) on a file will
lead to incorrectly dereferencing the type and other fields
of the security context structure, yielding a kernel BUG.
As a zero-length security context is never valid, just reject
all such security contexts whether coming from userspace
via setxattr or coming from the filesystem upon a getxattr
request by SELinux.
Setting a security context value (empty or otherwise) unknown to
SELinux in the first place is only possible for a root process
(CAP_MAC_ADMIN), and, if running SELinux in enforcing mode, only
if the corresponding SELinux mac_admin permission is also granted
to the domain by policy. In Fedora policies, this is only allowed for
specific domains such as livecd for setting down security contexts
that are not defined in the build host policy.
Reproducer:
su
setenforce 0
touch foo
setfattr -n security.selinux foo
Caveat:
Relabeling or removing foo after doing the above may not be possible
without booting with SELinux disabled. Any subsequent access to foo
after doing the above will also trigger the BUG.
BUG output from Matthew Thode:
[ 473.893141] ------------[ cut here ]------------
[ 473.962110] kernel BUG at security/selinux/ss/services.c:654!
[ 473.995314] invalid opcode: 0000 [#6] SMP
[ 474.027196] Modules linked in:
[ 474.058118] CPU: 0 PID: 8138 Comm: ls Tainted: G D I
3.13.0-grsec #1
[ 474.116637] Hardware name: Supermicro X8ST3/X8ST3, BIOS 2.0
07/29/10
[ 474.149768] task: ffff8805f50cd010 ti: ffff8805f50cd488 task.ti:
ffff8805f50cd488
[ 474.183707] RIP: 0010:[<ffffffff814681c7>] [<ffffffff814681c7>]
context_struct_compute_av+0xce/0x308
[ 474.219954] RSP: 0018:ffff8805c0ac3c38 EFLAGS: 00010246
[ 474.252253] RAX: 0000000000000000 RBX: ffff8805c0ac3d94 RCX:
0000000000000100
[ 474.287018] RDX: ffff8805e8aac000 RSI: 00000000ffffffff RDI:
ffff8805e8aaa000
[ 474.321199] RBP: ffff8805c0ac3cb8 R08: 0000000000000010 R09:
0000000000000006
[ 474.357446] R10: 0000000000000000 R11: ffff8805c567a000 R12:
0000000000000006
[ 474.419191] R13: ffff8805c2b74e88 R14: 00000000000001da R15:
0000000000000000
[ 474.453816] FS: 00007f2e75220800(0000) GS:ffff88061fc00000(0000)
knlGS:0000000000000000
[ 474.489254] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 474.522215] CR2: 00007f2e74716090 CR3: 00000005c085e000 CR4:
00000000000207f0
[ 474.556058] Stack:
[ 474.584325] ffff8805c0ac3c98 ffffffff811b549b ffff8805c0ac3c98
ffff8805f1190a40
[ 474.618913] ffff8805a6202f08 ffff8805c2b74e88 00068800d0464990
ffff8805e8aac860
[ 474.653955] ffff8805c0ac3cb8 000700068113833a ffff880606c75060
ffff8805c0ac3d94
[ 474.690461] Call Trace:
[ 474.723779] [<ffffffff811b549b>] ? lookup_fast+0x1cd/0x22a
[ 474.778049] [<ffffffff81468824>] security_compute_av+0xf4/0x20b
[ 474.811398] [<ffffffff8196f419>] avc_compute_av+0x2a/0x179
[ 474.843813] [<ffffffff8145727b>] avc_has_perm+0x45/0xf4
[ 474.875694] [<ffffffff81457d0e>] inode_has_perm+0x2a/0x31
[ 474.907370] [<ffffffff81457e76>] selinux_inode_getattr+0x3c/0x3e
[ 474.938726] [<ffffffff81455cf6>] security_inode_getattr+0x1b/0x22
[ 474.970036] [<ffffffff811b057d>] vfs_getattr+0x19/0x2d
[ 475.000618] [<ffffffff811b05e5>] vfs_fstatat+0x54/0x91
[ 475.030402] [<ffffffff811b063b>] vfs_lstat+0x19/0x1b
[ 475.061097] [<ffffffff811b077e>] SyS_newlstat+0x15/0x30
[ 475.094595] [<ffffffff8113c5c1>] ? __audit_syscall_entry+0xa1/0xc3
[ 475.148405] [<ffffffff8197791e>] system_call_fastpath+0x16/0x1b
[ 475.179201] Code: 00 48 85 c0 48 89 45 b8 75 02 0f 0b 48 8b 45 a0 48
8b 3d 45 d0 b6 00 8b 40 08 89 c6 ff ce e8 d1 b0 06 00 48 85 c0 49 89 c7
75 02 <0f> 0b 48 8b 45 b8 4c 8b 28 eb 1e 49 8d 7d 08 be 80 01 00 00 e8
[ 475.255884] RIP [<ffffffff814681c7>]
context_struct_compute_av+0xce/0x308
[ 475.296120] RSP <ffff8805c0ac3c38>
[ 475.328734] ---[ end trace f076482e9d754adc ]---
Reported-by: Matthew Thode <[email protected]>
Signed-off-by: Stephen Smalley <[email protected]>
Cc: [email protected]
Signed-off-by: Paul Moore <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PrepareFrameAndViewForPrint::ResizeForPrinting() {
gfx::Size print_layout_size(web_print_params_.print_content_area.width,
web_print_params_.print_content_area.height);
print_layout_size.set_height(
ScaleAndRound(print_layout_size.height(), kPrintingMinimumShrinkFactor));
if (!frame())
return;
if (PrintingNodeOrPdfFrame(frame(), node_to_print_))
return;
blink::WebView* web_view = frame_.view();
if (blink::WebFrame* web_frame = web_view->MainFrame()) {
if (web_frame->IsWebLocalFrame())
prev_scroll_offset_ = web_frame->ToWebLocalFrame()->GetScrollOffset();
}
prev_view_size_ = web_view->Size();
web_view->Resize(print_layout_size);
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: struct vfsmount *collect_mounts(struct path *path)
{
struct mount *tree;
namespace_lock();
tree = copy_tree(real_mount(path->mnt), path->dentry,
CL_COPY_ALL | CL_PRIVATE);
namespace_unlock();
if (IS_ERR(tree))
return ERR_CAST(tree);
return &tree->mnt;
}
Commit Message: mnt: Fail collect_mounts when applied to unmounted mounts
The only users of collect_mounts are in audit_tree.c
In audit_trim_trees and audit_add_tree_rule the path passed into
collect_mounts is generated from kern_path passed an audit_tree
pathname which is guaranteed to be an absolute path. In those cases
collect_mounts is obviously intended to work on mounted paths and
if a race results in paths that are unmounted when collect_mounts
it is reasonable to fail early.
The paths passed into audit_tag_tree don't have the absolute path
check. But are used to play with fsnotify and otherwise interact with
the audit_trees, so again operating only on mounted paths appears
reasonable.
Avoid having to worry about what happens when we try and audit
unmounted filesystems by restricting collect_mounts to mounts
that appear in the mount tree.
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static int jpeg_skip_variable2(Image *ifile, Image *ofile)
{
unsigned int length;
int c1,c2;
(void) ofile;
if ((c1 = ReadBlobByte(ifile)) == EOF) return M_EOI;
if ((c2 = ReadBlobByte(ifile)) == EOF) return M_EOI;
length = (((unsigned char) c1) << 8) + ((unsigned char) c2);
length -= 2;
while (length--)
if (ReadBlobByte(ifile) == EOF)
return M_EOI;
return 0;
}
Commit Message: ...
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: MirrorMockJobInterceptor(const base::FilePath& root_http,
ReportResponseHeadersOnUI report_on_ui)
: root_http_(root_http), 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 <[email protected]>
Reviewed-by: Ramin Halavati <[email protected]>
Reviewed-by: Maks Orlovich <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607652}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int mincore_unmapped_range(unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
walk->private += __mincore_unmapped_range(addr, end,
walk->vma, walk->private);
return 0;
}
Commit Message: Change mincore() to count "mapped" pages rather than "cached" pages
The semantics of what "in core" means for the mincore() system call are
somewhat unclear, but Linux has always (since 2.3.52, which is when
mincore() was initially done) treated it as "page is available in page
cache" rather than "page is mapped in the mapping".
The problem with that traditional semantic is that it exposes a lot of
system cache state that it really probably shouldn't, and that users
shouldn't really even care about.
So let's try to avoid that information leak by simply changing the
semantics to be that mincore() counts actual mapped pages, not pages
that might be cheaply mapped if they were faulted (note the "might be"
part of the old semantics: being in the cache doesn't actually guarantee
that you can access them without IO anyway, since things like network
filesystems may have to revalidate the cache before use).
In many ways the old semantics were somewhat insane even aside from the
information leak issue. From the very beginning (and that beginning is
a long time ago: 2.3.52 was released in March 2000, I think), the code
had a comment saying
Later we can get more picky about what "in core" means precisely.
and this is that "later". Admittedly it is much later than is really
comfortable.
NOTE! This is a real semantic change, and it is for example known to
change the output of "fincore", since that program literally does a
mmmap without populating it, and then doing "mincore()" on that mapping
that doesn't actually have any pages in it.
I'm hoping that nobody actually has any workflow that cares, and the
info leak is real.
We may have to do something different if it turns out that people have
valid reasons to want the old semantics, and if we can limit the
information leak sanely.
Cc: Kevin Easton <[email protected]>
Cc: Jiri Kosina <[email protected]>
Cc: Masatake YAMATO <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Greg KH <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Michal Hocko <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: void drop_collected_mounts(struct vfsmount *mnt)
{
namespace_lock();
lock_mount_hash();
umount_tree(real_mount(mnt), UMOUNT_SYNC);
unlock_mount_hash();
namespace_unlock();
}
Commit Message: mnt: Add a per mount namespace limit on the number of mounts
CAI Qian <[email protected]> pointed out that the semantics
of shared subtrees make it possible to create an exponentially
increasing number of mounts in a mount namespace.
mkdir /tmp/1 /tmp/2
mount --make-rshared /
for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done
Will create create 2^20 or 1048576 mounts, which is a practical problem
as some people have managed to hit this by accident.
As such CVE-2016-6213 was assigned.
Ian Kent <[email protected]> described the situation for autofs users
as follows:
> The number of mounts for direct mount maps is usually not very large because of
> the way they are implemented, large direct mount maps can have performance
> problems. There can be anywhere from a few (likely case a few hundred) to less
> than 10000, plus mounts that have been triggered and not yet expired.
>
> Indirect mounts have one autofs mount at the root plus the number of mounts that
> have been triggered and not yet expired.
>
> The number of autofs indirect map entries can range from a few to the common
> case of several thousand and in rare cases up to between 30000 and 50000. I've
> not heard of people with maps larger than 50000 entries.
>
> The larger the number of map entries the greater the possibility for a large
> number of active mounts so it's not hard to expect cases of a 1000 or somewhat
> more active mounts.
So I am setting the default number of mounts allowed per mount
namespace at 100,000. This is more than enough for any use case I
know of, but small enough to quickly stop an exponential increase
in mounts. Which should be perfect to catch misconfigurations and
malfunctioning programs.
For anyone who needs a higher limit this can be changed by writing
to the new /proc/sys/fs/mount-max sysctl.
Tested-by: CAI Qian <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-400
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: snd_compr_get_codec_caps(struct snd_compr_stream *stream, unsigned long arg)
{
int retval;
struct snd_compr_codec_caps *caps;
if (!stream->ops->get_codec_caps)
return -ENXIO;
caps = kmalloc(sizeof(*caps), GFP_KERNEL);
if (!caps)
return -ENOMEM;
retval = stream->ops->get_codec_caps(stream, caps);
if (retval)
goto out;
if (copy_to_user((void __user *)arg, caps, sizeof(*caps)))
retval = -EFAULT;
out:
kfree(caps);
return retval;
}
Commit Message: ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()
These are 32 bit values that come from the user, we need to check for
integer overflows or we could end up allocating a smaller buffer than
expected.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: pdf_read_old_xref(fz_context *ctx, pdf_document *doc, pdf_lexbuf *buf)
{
fz_stream *file = doc->file;
int64_t ofs;
int len;
char *s;
size_t n;
pdf_token tok;
int64_t i;
int c;
int xref_len = pdf_xref_size_from_old_trailer(ctx, doc, buf);
pdf_xref_entry *table;
int carried;
fz_skip_space(ctx, doc->file);
if (fz_skip_string(ctx, doc->file, "xref"))
fz_throw(ctx, FZ_ERROR_GENERIC, "cannot find xref marker");
fz_skip_space(ctx, doc->file);
while (1)
{
c = fz_peek_byte(ctx, file);
if (!(c >= '0' && c <= '9'))
break;
fz_read_line(ctx, file, buf->scratch, buf->size);
s = buf->scratch;
ofs = fz_atoi64(fz_strsep(&s, " "));
len = fz_atoi(fz_strsep(&s, " "));
/* broken pdfs where the section is not on a separate line */
if (s && *s != '\0')
{
fz_warn(ctx, "broken xref section. proceeding anyway.");
fz_seek(ctx, file, -(2 + (int)strlen(s)), SEEK_CUR);
}
if (ofs < 0)
fz_throw(ctx, FZ_ERROR_GENERIC, "out of range object num in xref: %d", (int)ofs);
if (ofs > INT64_MAX - len)
fz_throw(ctx, FZ_ERROR_GENERIC, "xref section object numbers too big");
/* broken pdfs where size in trailer undershoots entries in xref sections */
if (ofs + len > xref_len)
{
}
table = pdf_xref_find_subsection(ctx, doc, ofs, len);
/* Xref entries SHOULD be 20 bytes long, but we see 19 byte
* ones more frequently than we'd like (e.g. PCLm drivers).
* Cope with this by 'carrying' data forward. */
carried = 0;
for (i = ofs; i < ofs + len; i++)
{
pdf_xref_entry *entry = &table[i-ofs];
n = fz_read(ctx, file, (unsigned char *) buf->scratch + carried, 20-carried);
if (n != 20-carried)
fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected EOF in xref table");
n += carried;
if (!entry->type)
{
s = buf->scratch;
/* broken pdfs where line start with white space */
while (*s != '\0' && iswhite(*s))
s++;
entry->ofs = fz_atoi64(s);
entry->gen = fz_atoi(s + 11);
entry->num = (int)i;
entry->type = s[17];
if (s[17] != 'f' && s[17] != 'n' && s[17] != 'o')
fz_throw(ctx, FZ_ERROR_GENERIC, "unexpected xref type: 0x%x (%d %d R)", s[17], entry->num, entry->gen);
/* If the last byte of our buffer isn't an EOL (or space), carry one byte forward */
carried = s[19] > 32;
if (carried)
s[0] = s[19];
}
}
if (carried)
fz_unread_byte(ctx, file);
}
tok = pdf_lex(ctx, file, buf);
if (tok != PDF_TOK_TRAILER)
fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer marker");
tok = pdf_lex(ctx, file, buf);
if (tok != PDF_TOK_OPEN_DICT)
fz_throw(ctx, FZ_ERROR_GENERIC, "expected trailer dictionary");
return pdf_parse_dict(ctx, doc, file, buf);
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: _asn1_get_time_der (const unsigned char *der, int der_len, int *ret_len,
char *str, int str_size)
{
int len_len, str_len;
if (der_len <= 0 || str == NULL)
return ASN1_DER_ERROR;
str_len = asn1_get_length_der (der, der_len, &len_len);
if (str_len < 0 || str_size < str_len)
return ASN1_DER_ERROR;
memcpy (str, der + len_len, str_len);
str[str_len] = 0;
*ret_len = str_len + len_len;
return ASN1_SUCCESS;
}
Commit Message:
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void fpu__init_prepare_fx_sw_frame(void)
{
int size = fpu_user_xstate_size + FP_XSTATE_MAGIC2_SIZE;
fx_sw_reserved.magic1 = FP_XSTATE_MAGIC1;
fx_sw_reserved.extended_size = size;
fx_sw_reserved.xfeatures = xfeatures_mask;
fx_sw_reserved.xstate_size = fpu_user_xstate_size;
if (IS_ENABLED(CONFIG_IA32_EMULATION) ||
IS_ENABLED(CONFIG_X86_32)) {
int fsave_header_size = sizeof(struct fregs_state);
fx_sw_reserved_ia32 = fx_sw_reserved;
fx_sw_reserved_ia32.extended_size = size + fsave_header_size;
}
}
Commit Message: x86/fpu: Don't let userspace set bogus xcomp_bv
On x86, userspace can use the ptrace() or rt_sigreturn() system calls to
set a task's extended state (xstate) or "FPU" registers. ptrace() can
set them for another task using the PTRACE_SETREGSET request with
NT_X86_XSTATE, while rt_sigreturn() can set them for the current task.
In either case, registers can be set to any value, but the kernel
assumes that the XSAVE area itself remains valid in the sense that the
CPU can restore it.
However, in the case where the kernel is using the uncompacted xstate
format (which it does whenever the XSAVES instruction is unavailable),
it was possible for userspace to set the xcomp_bv field in the
xstate_header to an arbitrary value. However, all bits in that field
are reserved in the uncompacted case, so when switching to a task with
nonzero xcomp_bv, the XRSTOR instruction failed with a #GP fault. This
caused the WARN_ON_FPU(err) in copy_kernel_to_xregs() to be hit. In
addition, since the error is otherwise ignored, the FPU registers from
the task previously executing on the CPU were leaked.
Fix the bug by checking that the user-supplied value of xcomp_bv is 0 in
the uncompacted case, and returning an error otherwise.
The reason for validating xcomp_bv rather than simply overwriting it
with 0 is that we want userspace to see an error if it (incorrectly)
provides an XSAVE area in compacted format rather than in uncompacted
format.
Note that as before, in case of error we clear the task's FPU state.
This is perhaps non-ideal, especially for PTRACE_SETREGSET; it might be
better to return an error before changing anything. But it seems the
"clear on error" behavior is fine for now, and it's a little tricky to
do otherwise because it would mean we couldn't simply copy the full
userspace state into kernel memory in one __copy_from_user().
This bug was found by syzkaller, which hit the above-mentioned
WARN_ON_FPU():
WARNING: CPU: 1 PID: 0 at ./arch/x86/include/asm/fpu/internal.h:373 __switch_to+0x5b5/0x5d0
CPU: 1 PID: 0 Comm: swapper/1 Not tainted 4.13.0 #453
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
task: ffff9ba2bc8e42c0 task.stack: ffffa78cc036c000
RIP: 0010:__switch_to+0x5b5/0x5d0
RSP: 0000:ffffa78cc08bbb88 EFLAGS: 00010082
RAX: 00000000fffffffe RBX: ffff9ba2b8bf2180 RCX: 00000000c0000100
RDX: 00000000ffffffff RSI: 000000005cb10700 RDI: ffff9ba2b8bf36c0
RBP: ffffa78cc08bbbd0 R08: 00000000929fdf46 R09: 0000000000000001
R10: 0000000000000000 R11: 0000000000000000 R12: ffff9ba2bc8e42c0
R13: 0000000000000000 R14: ffff9ba2b8bf3680 R15: ffff9ba2bf5d7b40
FS: 00007f7e5cb10700(0000) GS:ffff9ba2bf400000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000004005cc CR3: 0000000079fd5000 CR4: 00000000001406e0
Call Trace:
Code: 84 00 00 00 00 00 e9 11 fd ff ff 0f ff 66 0f 1f 84 00 00 00 00 00 e9 e7 fa ff ff 0f ff 66 0f 1f 84 00 00 00 00 00 e9 c2 fa ff ff <0f> ff 66 0f 1f 84 00 00 00 00 00 e9 d4 fc ff ff 66 66 2e 0f 1f
Here is a C reproducer. The expected behavior is that the program spin
forever with no output. However, on a buggy kernel running on a
processor with the "xsave" feature but without the "xsaves" feature
(e.g. Sandy Bridge through Broadwell for Intel), within a second or two
the program reports that the xmm registers were corrupted, i.e. were not
restored correctly. With CONFIG_X86_DEBUG_FPU=y it also hits the above
kernel warning.
#define _GNU_SOURCE
#include <stdbool.h>
#include <inttypes.h>
#include <linux/elf.h>
#include <stdio.h>
#include <sys/ptrace.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int pid = fork();
uint64_t xstate[512];
struct iovec iov = { .iov_base = xstate, .iov_len = sizeof(xstate) };
if (pid == 0) {
bool tracee = true;
for (int i = 0; i < sysconf(_SC_NPROCESSORS_ONLN) && tracee; i++)
tracee = (fork() != 0);
uint32_t xmm0[4] = { [0 ... 3] = tracee ? 0x00000000 : 0xDEADBEEF };
asm volatile(" movdqu %0, %%xmm0\n"
" mov %0, %%rbx\n"
"1: movdqu %%xmm0, %0\n"
" mov %0, %%rax\n"
" cmp %%rax, %%rbx\n"
" je 1b\n"
: "+m" (xmm0) : : "rax", "rbx", "xmm0");
printf("BUG: xmm registers corrupted! tracee=%d, xmm0=%08X%08X%08X%08X\n",
tracee, xmm0[0], xmm0[1], xmm0[2], xmm0[3]);
} else {
usleep(100000);
ptrace(PTRACE_ATTACH, pid, 0, 0);
wait(NULL);
ptrace(PTRACE_GETREGSET, pid, NT_X86_XSTATE, &iov);
xstate[65] = -1;
ptrace(PTRACE_SETREGSET, pid, NT_X86_XSTATE, &iov);
ptrace(PTRACE_CONT, pid, 0, 0);
wait(NULL);
}
return 1;
}
Note: the program only tests for the bug using the ptrace() system call.
The bug can also be reproduced using the rt_sigreturn() system call, but
only when called from a 32-bit program, since for 64-bit programs the
kernel restores the FPU state from the signal frame by doing XRSTOR
directly from userspace memory (with proper error checking).
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Biggers <[email protected]>
Reviewed-by: Kees Cook <[email protected]>
Reviewed-by: Rik van Riel <[email protected]>
Acked-by: Dave Hansen <[email protected]>
Cc: <[email protected]> [v3.17+]
Cc: Andrew Morton <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Borislav Petkov <[email protected]>
Cc: Eric Biggers <[email protected]>
Cc: Fenghua Yu <[email protected]>
Cc: Kevin Hao <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Michael Halcrow <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Wanpeng Li <[email protected]>
Cc: Yu-cheng Yu <[email protected]>
Cc: [email protected]
Fixes: 0b29643a5843 ("x86/xsaves: Change compacted format xsave area header")
Link: http://lkml.kernel.org/r/[email protected]
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WtsSessionProcessDelegate::Core::KillProcess(DWORD exit_code) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
channel_.reset();
if (launch_elevated_) {
if (job_.IsValid()) {
TerminateJobObject(job_, exit_code);
}
} else {
if (worker_process_.IsValid()) {
TerminateProcess(worker_process_, exit_code);
}
}
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: int wc_ecc_import_unsigned(ecc_key* key, byte* qx, byte* qy,
byte* d, int curve_id)
{
return wc_ecc_import_raw_private(key, (const char*)qx, (const char*)qy,
(const char*)d, curve_id, ECC_TYPE_UNSIGNED_BIN);
}
Commit Message: Change ECDSA signing to use blinding.
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IW_IMPL(int) iw_get_i32le(const iw_byte *b)
{
return (iw_int32)(iw_uint32)(b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24));
}
Commit Message: Trying to fix some invalid left shift operations
Fixes issue #16
CWE ID: CWE-682
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: spnego_gss_wrap_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
ret = gss_wrap_iov(minor_status,
context_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18
Target: 1
Example 2:
Code: UWORD32 ihevcd_cabac_decode_bypass_bins_egk(cab_ctxt_t *ps_cabac,
bitstrm_t *ps_bitstrm,
WORD32 k)
{
UWORD32 u4_sym;
WORD32 numones;
WORD32 bin;
/* Sanity checks */
ASSERT((k >= 0));
numones = k;
bin = 1;
u4_sym = 0;
while(bin && (numones <= 16))
{
IHEVCD_CABAC_DECODE_BYPASS_BIN(bin, ps_cabac, ps_bitstrm);
u4_sym += bin << numones++;
}
numones -= 1;
if(numones)
{
UWORD32 u4_suffix;
IHEVCD_CABAC_DECODE_BYPASS_BINS(u4_suffix, ps_cabac, ps_bitstrm, numones);
u4_sym += u4_suffix;
}
return (u4_sym);
}
Commit Message: Return error from cabac init if offset is greater than range
When the offset was greater than range, the bitstream was read
more than the valid range in leaf-level cabac parsing modules.
Error check was added to cabac init to fix this issue. Additionally
end of slice and slice error were signalled to suppress further
parsing of current slice.
Bug: 34897036
Change-Id: I1263f1d1219684ffa6e952c76e5a08e9a933c9d2
(cherry picked from commit 3b175da88a1807d19cdd248b74bce60e57f05c6a)
(cherry picked from commit b92314c860d01d754ef579eafe55d7377962b3ba)
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: decrypt_response(struct sc_card *card, unsigned char *in, unsigned char *out, size_t * out_len)
{
size_t in_len;
size_t i;
unsigned char iv[16] = { 0 };
unsigned char plaintext[4096] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* no cipher */
if (in[0] == 0x99)
return 0;
/* parse cipher length */
if (0x01 == in[2] && 0x82 != in[1]) {
in_len = in[1];
i = 3;
}
else if (0x01 == in[3] && 0x81 == in[1]) {
in_len = in[2];
i = 4;
}
else if (0x01 == in[4] && 0x82 == in[1]) {
in_len = in[2] * 0x100;
in_len += in[3];
i = 5;
}
else {
return -1;
}
/* decrypt */
if (KEY_TYPE_AES == exdata->smtype)
aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], in_len - 1, plaintext);
else
des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], in_len - 1, plaintext);
/* unpadding */
while (0x80 != plaintext[in_len - 2] && (in_len - 2 > 0))
in_len--;
if (2 == in_len)
return -1;
memcpy(out, plaintext, in_len - 2);
*out_len = in_len - 2;
return 0;
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: raptor_libxml_getEntity(void* user_data, const xmlChar *name) {
raptor_sax2* sax2 = (raptor_sax2*)user_data;
return libxml2_getEntity(sax2->xc, name);
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200
Target: 1
Example 2:
Code: static GLenum GetGLESOverlayTransform(gfx::OverlayTransform plane_transform) {
switch (plane_transform) {
case gfx::OVERLAY_TRANSFORM_INVALID:
break;
case gfx::OVERLAY_TRANSFORM_NONE:
return GL_OVERLAY_TRANSFORM_NONE_CHROMIUM;
case gfx::OVERLAY_TRANSFORM_FLIP_HORIZONTAL:
return GL_OVERLAY_TRANSFORM_FLIP_HORIZONTAL_CHROMIUM;
case gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL:
return GL_OVERLAY_TRANSFORM_FLIP_VERTICAL_CHROMIUM;
case gfx::OVERLAY_TRANSFORM_ROTATE_90:
return GL_OVERLAY_TRANSFORM_ROTATE_90_CHROMIUM;
case gfx::OVERLAY_TRANSFORM_ROTATE_180:
return GL_OVERLAY_TRANSFORM_ROTATE_180_CHROMIUM;
case gfx::OVERLAY_TRANSFORM_ROTATE_270:
return GL_OVERLAY_TRANSFORM_ROTATE_270_CHROMIUM;
}
NOTREACHED();
return GL_OVERLAY_TRANSFORM_NONE_CHROMIUM;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void i8042_stop(struct serio *serio)
{
struct i8042_port *port = serio->port_data;
port->exists = false;
/*
* We synchronize with both AUX and KBD IRQs because there is
* a (very unlikely) chance that AUX IRQ is raised for KBD port
* and vice versa.
*/
synchronize_irq(I8042_AUX_IRQ);
synchronize_irq(I8042_KBD_IRQ);
port->serio = NULL;
}
Commit Message: Input: i8042 - fix crash at boot time
The driver checks port->exists twice in i8042_interrupt(), first when
trying to assign temporary "serio" variable, and second time when deciding
whether it should call serio_interrupt(). The value of port->exists may
change between the 2 checks, and we may end up calling serio_interrupt()
with a NULL pointer:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000050
IP: [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40
PGD 0
Oops: 0002 [#1] SMP
last sysfs file:
CPU 0
Modules linked in:
Pid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996)
RIP: 0010:[<ffffffff8150feaf>] [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40
RSP: 0018:ffff880028203cc0 EFLAGS: 00010082
RAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000
RDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050
RBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0
R10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050
R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098
FS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b
CR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
Process swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500)
Stack:
ffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000
<d> 0000000000000000 0000000000000000 0000000000000000 0000000000000098
<d> ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac
Call Trace:
<IRQ>
[<ffffffff813de186>] serio_interrupt+0x36/0xa0
[<ffffffff813e0162>] i8042_interrupt+0x132/0x3a0
[<ffffffff8103b8ac>] ? kvm_clock_read+0x1c/0x20
[<ffffffff8103b8b9>] ? kvm_clock_get_cycles+0x9/0x10
[<ffffffff810e1640>] handle_IRQ_event+0x60/0x170
[<ffffffff8103b154>] ? kvm_guest_apic_eoi_write+0x44/0x50
[<ffffffff810e3d8e>] handle_edge_irq+0xde/0x180
[<ffffffff8100de89>] handle_irq+0x49/0xa0
[<ffffffff81516c8c>] do_IRQ+0x6c/0xf0
[<ffffffff8100b9d3>] ret_from_intr+0x0/0x11
[<ffffffff81076f63>] ? __do_softirq+0x73/0x1e0
[<ffffffff8109b75b>] ? hrtimer_interrupt+0x14b/0x260
[<ffffffff8100c1cc>] ? call_softirq+0x1c/0x30
[<ffffffff8100de05>] ? do_softirq+0x65/0xa0
[<ffffffff81076d95>] ? irq_exit+0x85/0x90
[<ffffffff81516d80>] ? smp_apic_timer_interrupt+0x70/0x9b
[<ffffffff8100bb93>] ? apic_timer_interrupt+0x13/0x20
To avoid the issue let's change the second check to test whether serio is
NULL or not.
Also, let's take i8042_lock in i8042_start() and i8042_stop() instead of
trying to be overly smart and using memory barriers.
Signed-off-by: Chen Hong <[email protected]>
[dtor: take lock in i8042_start()/i8042_stop()]
Cc: [email protected]
Signed-off-by: Dmitry Torokhov <[email protected]>
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) {
struct import_t *imports;
int i, j, idx, stridx;
const char *symstr;
if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms)
return NULL;
if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) {
return NULL;
}
if (!(imports = malloc ((bin->dysymtab.nundefsym + 1) * sizeof (struct import_t)))) {
return NULL;
}
for (i = j = 0; i < bin->dysymtab.nundefsym; i++) {
idx = bin->dysymtab.iundefsym + i;
if (idx < 0 || idx >= bin->nsymtab) {
bprintf ("WARNING: Imports index out of bounds. Ignoring relocs\n");
free (imports);
return NULL;
}
stridx = bin->symtab[idx].n_strx;
if (stridx >= 0 && stridx < bin->symstrlen) {
symstr = (char *)bin->symstr + stridx;
} else {
symstr = "";
}
if (!*symstr) {
continue;
}
{
int i = 0;
int len = 0;
char *symstr_dup = NULL;
len = bin->symstrlen - stridx;
imports[j].name[0] = 0;
if (len > 0) {
for (i = 0; i < len; i++) {
if ((unsigned char)symstr[i] == 0xff || !symstr[i]) {
len = i;
break;
}
}
symstr_dup = r_str_ndup (symstr, len);
if (symstr_dup) {
r_str_ncpy (imports[j].name, symstr_dup, R_BIN_MACH0_STRING_LENGTH);
r_str_filter (imports[j].name, - 1);
imports[j].name[R_BIN_MACH0_STRING_LENGTH - 2] = 0;
free (symstr_dup);
}
}
}
imports[j].ord = i;
imports[j++].last = 0;
}
imports[j].last = 1;
if (!bin->imports_by_ord_size) {
if (j > 0) {
bin->imports_by_ord_size = j;
bin->imports_by_ord = (RBinImport**)calloc (j, sizeof (RBinImport*));
} else {
bin->imports_by_ord_size = 0;
bin->imports_by_ord = NULL;
}
}
return imports;
}
Commit Message: Fix #9970 - heap oobread in mach0 parser (#10026)
CWE ID: CWE-125
Target: 1
Example 2:
Code: void AudioMixerAlsa::RegisterPrefs(PrefService* local_state) {
if (!local_state->FindPreference(prefs::kAudioVolume))
local_state->RegisterDoublePref(prefs::kAudioVolume,
kDefaultVolumeDb,
PrefService::UNSYNCABLE_PREF);
if (!local_state->FindPreference(prefs::kAudioMute))
local_state->RegisterIntegerPref(prefs::kAudioMute,
kPrefMuteOff,
PrefService::UNSYNCABLE_PREF);
}
Commit Message: chromeos: Move audio, power, and UI files into subdirs.
This moves more files from chrome/browser/chromeos/ into
subdirectories.
BUG=chromium-os:22896
TEST=did chrome os builds both with and without aura
TBR=sky
Review URL: http://codereview.chromium.org/9125006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116746 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
colorspace[MagickPathExtent],
tuple[MagickPathExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
PixelInfo
pixel;
register const Quantum
*p;
register ssize_t
x;
ssize_t
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->alpha_trait != UndefinedPixelTrait)
(void) ConcatenateMagickString(colorspace,"a",MagickPathExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MagickPathExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,p,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g,%.20g,",(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p+=GetPixelChannels(image);
continue;
}
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MagickPathExtent);
if (pixel.colorspace == GRAYColorspace)
ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,
tuple);
else
{
ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance,
tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple);
}
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance,
tuple);
}
if (pixel.alpha_trait != UndefinedPixelTrait)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance,
tuple);
}
(void) ConcatenateMagickString(tuple,")",MagickPathExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p+=GetPixelChannels(image);
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/298
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
one=1;
image=AcquireImage(image_info);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=BitmapHeader1.HorzRes/470.0;
image->y_resolution=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->x_resolution=BitmapHeader2.HorzRes/470.0;
image->y_resolution=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(BImgBuff,i,image,bpp);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);;
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
Commit Message: Fixed out-of-bounds write reported in: https://github.com/ImageMagick/ImageMagick/issues/102
CWE ID: CWE-787
Target: 1
Example 2:
Code: void GLES2Implementation::VertexAttribIPointer(GLuint index,
GLint size,
GLenum type,
GLsizei stride,
const void* ptr) {
GPU_CLIENT_SINGLE_THREAD_CHECK();
GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glVertexAttribIPointer(" << index
<< ", " << size << ", "
<< GLES2Util::GetStringVertexAttribIType(type) << ", "
<< stride << ", " << ptr << ")");
if (!vertex_array_object_manager_->SetAttribPointer(
bound_array_buffer_, index, size, type, GL_FALSE, stride, ptr,
GL_TRUE)) {
SetGLError(GL_INVALID_OPERATION, "glVertexAttribIPointer",
"client side arrays are not allowed in vertex array objects.");
return;
}
if (!support_client_side_arrays_ || bound_array_buffer_ != 0) {
if (!ValidateOffset("glVertexAttribIPointer",
reinterpret_cast<GLintptr>(ptr))) {
return;
}
helper_->VertexAttribIPointer(index, size, type, stride, ToGLuint(ptr));
}
CheckGLError();
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: NavigateParams::NavigateParams(Browser* a_browser,
TabContentsWrapper* a_target_contents)
: target_contents(a_target_contents),
source_contents(NULL),
disposition(CURRENT_TAB),
transition(content::PAGE_TRANSITION_LINK),
tabstrip_index(-1),
tabstrip_add_types(TabStripModel::ADD_ACTIVE),
window_action(NO_ACTION),
user_gesture(true),
path_behavior(RESPECT),
ref_behavior(IGNORE_REF),
browser(a_browser),
profile(NULL) {
}
Commit Message: Fix memory error in previous CL.
BUG=100315
BUG=99016
TEST=Memory bots go green
Review URL: http://codereview.chromium.org/8302001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BluetoothDeviceChromeOS::Cancel() {
DCHECK(agent_.get());
VLOG(1) << object_path_.value() << ": Cancel";
DCHECK(pairing_delegate_);
pairing_delegate_->DismissDisplayOrConfirm();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: int pipe_to_file(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
struct splice_desc *sd)
{
struct file *file = sd->u.file;
struct address_space *mapping = file->f_mapping;
unsigned int offset, this_len;
struct page *page;
void *fsdata;
int ret;
offset = sd->pos & ~PAGE_CACHE_MASK;
this_len = sd->len;
if (this_len + offset > PAGE_CACHE_SIZE)
this_len = PAGE_CACHE_SIZE - offset;
ret = pagecache_write_begin(file, mapping, sd->pos, this_len,
AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
if (unlikely(ret))
goto out;
if (buf->page != page) {
char *src = kmap_atomic(buf->page);
char *dst = kmap_atomic(page);
memcpy(dst + offset, src + buf->offset, this_len);
flush_dcache_page(page);
kunmap_atomic(dst);
kunmap_atomic(src);
}
ret = pagecache_write_end(file, mapping, sd->pos, this_len, this_len,
page, fsdata);
out:
return ret;
}
Commit Message: ->splice_write() via ->write_iter()
iter_file_splice_write() - a ->splice_write() instance that gathers the
pipe buffers, builds a bio_vec-based iov_iter covering those and feeds
it to ->write_iter(). A bunch of simple cases coverted to that...
[AV: fixed the braino spotted by Cyrill]
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: MockQuotaManagerProxy()
: QuotaManagerProxy(nullptr, nullptr),
notify_storage_accessed_count_(0),
notify_storage_modified_count_(0),
last_delta_(0),
mock_manager_(new MockQuotaManager) {
manager_ = mock_manager_.get();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ssize_t wdm_read
(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
{
int rv, cntr;
int i = 0;
struct wdm_device *desc = file->private_data;
rv = mutex_lock_interruptible(&desc->rlock); /*concurrent reads */
if (rv < 0)
return -ERESTARTSYS;
cntr = ACCESS_ONCE(desc->length);
if (cntr == 0) {
desc->read = 0;
retry:
if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
rv = -ENODEV;
goto err;
}
i++;
if (file->f_flags & O_NONBLOCK) {
if (!test_bit(WDM_READ, &desc->flags)) {
rv = cntr ? cntr : -EAGAIN;
goto err;
}
rv = 0;
} else {
rv = wait_event_interruptible(desc->wait,
test_bit(WDM_READ, &desc->flags));
}
/* may have happened while we slept */
if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
rv = -ENODEV;
goto err;
}
if (test_bit(WDM_RESETTING, &desc->flags)) {
rv = -EIO;
goto err;
}
usb_mark_last_busy(interface_to_usbdev(desc->intf));
if (rv < 0) {
rv = -ERESTARTSYS;
goto err;
}
spin_lock_irq(&desc->iuspin);
if (desc->rerr) { /* read completed, error happened */
desc->rerr = 0;
spin_unlock_irq(&desc->iuspin);
rv = -EIO;
goto err;
}
/*
* recheck whether we've lost the race
* against the completion handler
*/
if (!test_bit(WDM_READ, &desc->flags)) { /* lost race */
spin_unlock_irq(&desc->iuspin);
goto retry;
}
if (!desc->reslength) { /* zero length read */
dev_dbg(&desc->intf->dev, "%s: zero length - clearing WDM_READ\n", __func__);
clear_bit(WDM_READ, &desc->flags);
spin_unlock_irq(&desc->iuspin);
goto retry;
}
cntr = desc->length;
spin_unlock_irq(&desc->iuspin);
}
if (cntr > count)
cntr = count;
rv = copy_to_user(buffer, desc->ubuf, cntr);
if (rv > 0) {
rv = -EFAULT;
goto err;
}
spin_lock_irq(&desc->iuspin);
for (i = 0; i < desc->length - cntr; i++)
desc->ubuf[i] = desc->ubuf[i + cntr];
desc->length -= cntr;
/* in case we had outstanding data */
if (!desc->length)
clear_bit(WDM_READ, &desc->flags);
spin_unlock_irq(&desc->iuspin);
rv = cntr;
err:
mutex_unlock(&desc->rlock);
return rv;
}
Commit Message: USB: cdc-wdm: fix buffer overflow
The buffer for responses must not overflow.
If this would happen, set a flag, drop the data and return
an error after user space has read all remaining data.
Signed-off-by: Oliver Neukum <[email protected]>
CC: [email protected]
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool ChromeContentRendererClient::WillSendRequest(WebKit::WebFrame* frame,
const GURL& url,
GURL* new_url) {
if (url.SchemeIs(chrome::kExtensionScheme) &&
!ExtensionResourceRequestPolicy::CanRequestResource(
url,
GURL(frame->document().url()),
extension_dispatcher_->extensions())) {
*new_url = GURL("chrome-extension://invalid/");
return true;
}
return false;
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PassRefPtrWillBeRawPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
{
return ensureCachedCollection<WindowNameCollection>(WindowNamedItems, name);
}
Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone.
BUG=556724,577105
Review URL: https://codereview.chromium.org/1667573002
Cr-Commit-Position: refs/heads/master@{#373642}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: exsltFuncRegisterImportFunc (exsltFuncFunctionData *data,
exsltFuncImportRegData *ch,
const xmlChar *URI, const xmlChar *name,
ATTRIBUTE_UNUSED const xmlChar *ignored) {
exsltFuncFunctionData *func=NULL;
if ((data == NULL) || (ch == NULL) || (URI == NULL) || (name == NULL))
return;
if (ch->ctxt == NULL || ch->hash == NULL)
return;
/* Check if already present */
func = (exsltFuncFunctionData*)xmlHashLookup2(ch->hash, URI, name);
if (func == NULL) { /* Not yet present - copy it in */
func = exsltFuncNewFunctionData();
memcpy(func, data, sizeof(exsltFuncFunctionData));
if (xmlHashAddEntry2(ch->hash, URI, name, func) < 0) {
xsltGenericError(xsltGenericErrorContext,
"Failed to register function {%s}%s\n",
URI, name);
} else { /* Do the registration */
xsltGenericDebug(xsltGenericDebugContext,
"exsltFuncRegisterImportFunc: register {%s}%s\n",
URI, name);
xsltRegisterExtFunction(ch->ctxt, name, URI,
exsltFuncFunctionFunction);
}
}
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int BufStream::lookChar() {
return buf[0];
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_pclr_t *pclr = &box->data.pclr;
int lutsize;
unsigned int i;
unsigned int j;
int_fast32_t x;
pclr->lutdata = 0;
if (jp2_getuint16(in, &pclr->numlutents) ||
jp2_getuint8(in, &pclr->numchans)) {
return -1;
}
lutsize = pclr->numlutents * pclr->numchans;
if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) {
return -1;
}
if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < pclr->numchans; ++i) {
if (jp2_getuint8(in, &pclr->bpc[i])) {
return -1;
}
}
for (i = 0; i < pclr->numlutents; ++i) {
for (j = 0; j < pclr->numchans; ++j) {
if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0,
(pclr->bpc[j] & 0x7f) + 1, &x)) {
return -1;
}
pclr->lutdata[i * pclr->numchans + j] = x;
}
}
return 0;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: kadm5_randkey_principal_3(void *server_handle,
krb5_principal principal,
krb5_boolean keepold,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
krb5_keyblock **keyblocks,
int *n_keys)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_int32 now;
kadm5_policy_ent_rec pol;
int ret, last_pwd;
krb5_boolean have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_kvno act_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
if (keyblocks)
*keyblocks = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto done;
if (krb5_principal_compare(handle->context, principal, hist_princ)) {
/* If changing the history entry, the new entry must have exactly one
* key. */
if (keepold)
return KADM5_PROTECT_PRINCIPAL;
new_n_ks_tuple = 1;
}
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto done;
ret = krb5_dbe_crk(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple,
keepold, kdb);
if (ret)
goto done;
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto done;
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd);
if (ret)
goto done;
#if 0
/*
* The spec says this check is overridden if the caller has
* modify privilege. The admin server therefore makes this
* check itself (in chpass_principal_wrapper, misc.c). A
* local caller implicitly has all authorization bits.
*/
if((now - last_pwd) < pol.pw_min_life &&
!(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) {
ret = KADM5_PASS_TOOSOON;
goto done;
}
#endif
if (pol.pw_max_life)
kdb->pw_expiration = now + pol.pw_max_life;
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* unlock principal on this KDC */
kdb->fail_auth_count = 0;
if (keyblocks) {
ret = decrypt_key_data(handle->context,
kdb->n_key_data, kdb->key_data,
keyblocks, n_keys);
if (ret)
goto done;
}
/* key data changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;
/* | KADM5_RANDKEY_USED */;
ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold,
new_n_ks_tuple, new_ks_tuple, NULL);
if (ret)
goto done;
if ((ret = kdb_put_entry(handle, kdb, &adb)))
goto done;
(void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, principal,
keepold, new_n_ks_tuple, new_ks_tuple, NULL);
ret = KADM5_OK;
done:
free(new_ks_tuple);
kdb_free_entry(handle, kdb, &adb);
if (have_pol)
kadm5_free_policy_ent(handle->lhandle, &pol);
return ret;
}
Commit Message: Return only new keys in randkey [CVE-2014-5351]
In kadmind's randkey operation, if a client specifies the keepold
flag, do not include the preserved old keys in the response.
CVE-2014-5351:
An authenticated remote attacker can retrieve the current keys for a
service principal when generating a new set of keys for that
principal. The attacker needs to be authenticated as a user who has
the elevated privilege for randomizing the keys of other principals.
Normally, when a Kerberos administrator randomizes the keys of a
service principal, kadmind returns only the new keys. This prevents
an administrator who lacks legitimate privileged access to a service
from forging tickets to authenticate to that service. If the
"keepold" flag to the kadmin randkey RPC operation is true, kadmind
retains the old keys in the KDC database as intended, but also
unexpectedly returns the old keys to the client, which exposes the
service to ticket forgery attacks from the administrator.
A mitigating factor is that legitimate clients of the affected service
will start failing to authenticate to the service once they begin to
receive service tickets encrypted in the new keys. The affected
service will be unable to decrypt the newly issued tickets, possibly
alerting the legitimate administrator of the affected service.
CVSSv2: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C
[[email protected]: CVE description and CVSS score]
ticket: 8018 (new)
target_version: 1.13
tags: pullup
CWE ID: CWE-255
Target: 1
Example 2:
Code: PerformTaskContext(WeakPtr<Document> document, PassOwnPtr<ExecutionContextTask> task)
: documentReference(document)
, task(task)
{
}
Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document
The member is used only in Document, thus no reason to
stay in SecurityContext.
TEST=none
BUG=none
[email protected], abarth, haraken, hayato
Review URL: https://codereview.chromium.org/27615003
git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ExtensionService::SetBrowserActionVisibility(const Extension* extension,
bool visible) {
extension_prefs_->SetBrowserActionVisibility(extension, visible);
}
Commit Message: Limit extent of webstore app to just chrome.google.com/webstore.
BUG=93497
TEST=Try installing extensions and apps from the webstore, starting both being
initially logged in, and not.
Review URL: http://codereview.chromium.org/7719003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int piv_match_card_continued(sc_card_t *card)
{
int i;
int type = -1;
piv_private_data_t *priv = NULL;
int saved_type = card->type;
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
/* piv_match_card may be called with card->type, set by opensc.conf */
/* user provide card type must be one we know */
switch (card->type) {
case -1:
case SC_CARD_TYPE_PIV_II_GENERIC:
case SC_CARD_TYPE_PIV_II_HIST:
case SC_CARD_TYPE_PIV_II_NEO:
case SC_CARD_TYPE_PIV_II_YUBIKEY4:
case SC_CARD_TYPE_PIV_II_GI_DE:
type = card->type;
break;
default:
return 0; /* can not handle the card */
}
if (type == -1) {
/*
*try to identify card by ATR or historical data in ATR
* currently all PIV card will respond to piv_find_aid
* the same. But in future may need to know card type first,
* so do it here.
*/
if (card->reader->atr_info.hist_bytes != NULL) {
if (card->reader->atr_info.hist_bytes_len == 8 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey4", 8))) {
type = SC_CARD_TYPE_PIV_II_YUBIKEY4;
}
else if (card->reader->atr_info.hist_bytes_len >= 7 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey", 7))) {
type = SC_CARD_TYPE_PIV_II_NEO;
}
/*
* https://csrc.nist.gov/csrc/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp1239.pdf
* lists 2 ATRS with historical bytes:
* 73 66 74 65 2D 63 64 30 38 30
* 73 66 74 65 20 63 64 31 34 34
* will check for 73 66 74 65
*/
else if (card->reader->atr_info.hist_bytes_len >= 4 &&
!(memcmp(card->reader->atr_info.hist_bytes, "sfte", 4))) {
type = SC_CARD_TYPE_PIV_II_GI_DE;
}
else if (card->reader->atr_info.hist_bytes[0] == 0x80u) { /* compact TLV */
size_t datalen;
const u8 *data = sc_compacttlv_find_tag(card->reader->atr_info.hist_bytes + 1,
card->reader->atr_info.hist_bytes_len - 1,
0xF0, &datalen);
if (data != NULL) {
int k;
for (k = 0; piv_aids[k].len_long != 0; k++) {
if (datalen == piv_aids[k].len_long
&& !memcmp(data, piv_aids[k].value, datalen)) {
type = SC_CARD_TYPE_PIV_II_HIST;
break;
}
}
}
}
}
if (type == -1)
type = SC_CARD_TYPE_PIV_II_GENERIC;
}
/* allocate and init basic fields */
priv = calloc(1, sizeof(piv_private_data_t));
if (!priv)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
if (card->type == -1)
card->type = type;
card->drv_data = priv; /* will free if no match, or pass on to piv_init */
priv->aid_file = sc_file_new();
priv->selected_obj = -1;
priv->pin_preference = 0x80; /* 800-73-3 part 1, table 3 */
priv->logged_in = SC_PIN_STATE_UNKNOWN;
priv->tries_left = 10; /* will assume OK at start */
priv->pstate = PIV_STATE_MATCH;
/* Some objects will only be present if History object says so */
for (i=0; i < PIV_OBJ_LAST_ENUM -1; i++)
if(piv_objects[i].flags & PIV_OBJECT_NOT_PRESENT)
priv->obj_cache[i].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
sc_lock(card);
/*
* detect if active AID is PIV. NIST 800-73 says Only one PIV application per card
* and PIV must be the default application
* This can avoid doing doing a select_aid and losing the login state on some cards
* We may get interference on some cards by other drivers trying SELECT_AID before
* we get to see if PIV application is still active.
* putting PIV driver first might help.
* This may fail if the wrong AID is active
*/
i = piv_find_discovery(card);
if (i < 0) {
/* Detect by selecting applet */
sc_file_t aidfile;
i = piv_find_aid(card, &aidfile);
}
if (i >= 0) {
/*
* We now know PIV AID is active, test DISCOVERY object
* Some CAC cards with PIV don't support DISCOVERY and return
* SC_ERROR_INCORRECT_PARAMETERS. Any error other then
* SC_ERROR_FILE_NOT_FOUND means we cannot use discovery
* to test for active AID.
*/
int i7e = piv_find_discovery(card);
if (i7e != 0 && i7e != SC_ERROR_FILE_NOT_FOUND) {
priv->card_issues |= CI_DISCOVERY_USELESS;
priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
}
}
if (i < 0) {
/* don't match. Does not have a PIV applet. */
sc_unlock(card);
piv_finish(card);
card->type = saved_type;
return 0;
}
/* Matched, caller will use or free priv and sc_lock as needed */
priv->pstate=PIV_STATE_INIT;
return 1; /* match */
}
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
Target: 1
Example 2:
Code: int crypto_ahash_finup(struct ahash_request *req)
{
return crypto_ahash_op(req, crypto_ahash_reqtfm(req)->finup);
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BluetoothSocketListenUsingRfcommFunction::CreateService(
scoped_refptr<device::BluetoothAdapter> adapter,
const device::BluetoothUUID& uuid,
std::unique_ptr<std::string> name,
const device::BluetoothAdapter::CreateServiceCallback& callback,
const device::BluetoothAdapter::CreateServiceErrorCallback&
error_callback) {
device::BluetoothAdapter::ServiceOptions service_options;
service_options.name = std::move(name);
ListenOptions* options = params_->options.get();
if (options) {
if (options->channel.get())
service_options.channel.reset(new int(*(options->channel)));
}
adapter->CreateRfcommService(uuid, service_options, callback, error_callback);
}
Commit Message: chrome.bluetoothSocket: Fix regression in send()
In https://crrev.com/c/997098, params_ was changed to a local variable,
but it needs to last longer than that since net::WrappedIOBuffer may use
the data after the local variable goes out of scope.
This CL changed it back to be an instance variable.
Bug: 851799
Change-Id: I392f8acaef4c6473d6ea4fbee7209445aa09112e
Reviewed-on: https://chromium-review.googlesource.com/1103676
Reviewed-by: Toni Barzic <[email protected]>
Commit-Queue: Sonny Sasaka <[email protected]>
Cr-Commit-Position: refs/heads/master@{#568137}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_METHOD(Phar, offsetGet)
{
char *fname, *error;
size_t fname_len;
zval zfname;
phar_entry_info *entry;
zend_string *sfname;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
return;
}
/* security is 0 here so that we can get a better error message than "entry doesn't exist" */
if (!(entry = phar_get_entry_info_dir(phar_obj->archive, fname, fname_len, 1, &error, 0))) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist%s%s", fname, error?", ":"", error?error:"");
} else {
if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get stub \".phar/stub.php\" directly in phar \"%s\", use getStub", phar_obj->archive->fname);
return;
}
if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot get alias \".phar/alias.txt\" directly in phar \"%s\", use getAlias", phar_obj->archive->fname);
return;
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot directly get any files or directories in magic \".phar\" directory", phar_obj->archive->fname);
return;
}
if (entry->is_temp_dir) {
efree(entry->filename);
efree(entry);
}
sfname = strpprintf(0, "phar://%s/%s", phar_obj->archive->fname, fname);
ZVAL_NEW_STR(&zfname, sfname);
spl_instantiate_arg_ex1(phar_obj->spl.info_class, return_value, &zfname);
zval_ptr_dtor(&zfname);
}
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int megasas_ld_get_info_submit(SCSIDevice *sdev, int lun,
MegasasCmd *cmd)
{
struct mfi_ld_info *info = cmd->iov_buf;
size_t dcmd_size = sizeof(struct mfi_ld_info);
uint8_t cdb[6];
SCSIRequest *req;
ssize_t len, resid;
uint16_t sdev_id = ((sdev->id & 0xFF) << 8) | (lun & 0xFF);
uint64_t ld_size;
if (!cmd->iov_buf) {
cmd->iov_buf = g_malloc0(dcmd_size);
info = cmd->iov_buf;
megasas_setup_inquiry(cdb, 0x83, sizeof(info->vpd_page83));
req = scsi_req_new(sdev, cmd->index, lun, cdb, cmd);
if (!req) {
trace_megasas_dcmd_req_alloc_failed(cmd->index,
"LD get info vpd inquiry");
g_free(cmd->iov_buf);
cmd->iov_buf = NULL;
return MFI_STAT_FLASH_ALLOC_FAIL;
}
trace_megasas_dcmd_internal_submit(cmd->index,
"LD get info vpd inquiry", lun);
len = scsi_req_enqueue(req);
if (len > 0) {
cmd->iov_size = len;
scsi_req_continue(req);
}
return MFI_STAT_INVALID_STATUS;
}
info->ld_config.params.state = MFI_LD_STATE_OPTIMAL;
info->ld_config.properties.ld.v.target_id = lun;
info->ld_config.params.stripe_size = 3;
info->ld_config.params.num_drives = 1;
info->ld_config.params.is_consistent = 1;
/* Logical device size is in blocks */
blk_get_geometry(sdev->conf.blk, &ld_size);
info->size = cpu_to_le64(ld_size);
memset(info->ld_config.span, 0, sizeof(info->ld_config.span));
info->ld_config.span[0].start_block = 0;
info->ld_config.span[0].num_blocks = info->size;
info->ld_config.span[0].array_ref = cpu_to_le16(sdev_id);
resid = dma_buf_read(cmd->iov_buf, dcmd_size, &cmd->qsg);
g_free(cmd->iov_buf);
cmd->iov_size = dcmd_size - resid;
cmd->iov_buf = NULL;
return MFI_STAT_OK;
}
Commit Message:
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FetchManager::OnLoaderFinished(Loader* loader) {
loaders_.erase(loader);
loader->Dispose();
}
Commit Message: [Fetch API] Fix redirect leak on "no-cors" requests
The spec issue is now fixed, and this CL follows the spec change[1].
1: https://github.com/whatwg/fetch/commit/14858d3e9402285a7ff3b5e47a22896ff3adc95d
Bug: 791324
Change-Id: Ic3e3955f43578b38fc44a5a6b2a1b43d56a2becb
Reviewed-on: https://chromium-review.googlesource.com/1023613
Reviewed-by: Tsuyoshi Horo <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#552964}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,
char *text,ExceptionInfo *exception)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent],
*p;
DrawInfo
*draw_info;
Image
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->x_resolution)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->y_resolution)/
delta.y)+0.5);
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MaxTextExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x,
(long) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x,
(long) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MaxTextExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,offset,image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
(void) SetImageBackgroundColor(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void hugetlb_vm_op_open(struct vm_area_struct *vma)
{
struct resv_map *reservations = vma_resv_map(vma);
/*
* This new VMA should share its siblings reservation map if present.
* The VMA will only ever have a valid reservation map pointer where
* it is being copied for another still existing VMA. As that VMA
* has a reference to the reservation map it cannot disappear until
* after this open call completes. It is therefore safe to take a
* new reference here without additional locking.
*/
if (reservations)
kref_get(&reservations->refs);
}
Commit Message: hugepages: fix use after free bug in "quota" handling
hugetlbfs_{get,put}_quota() are badly named. They don't interact with the
general quota handling code, and they don't much resemble its behaviour.
Rather than being about maintaining limits on on-disk block usage by
particular users, they are instead about maintaining limits on in-memory
page usage (including anonymous MAP_PRIVATE copied-on-write pages)
associated with a particular hugetlbfs filesystem instance.
Worse, they work by having callbacks to the hugetlbfs filesystem code from
the low-level page handling code, in particular from free_huge_page().
This is a layering violation of itself, but more importantly, if the
kernel does a get_user_pages() on hugepages (which can happen from KVM
amongst others), then the free_huge_page() can be delayed until after the
associated inode has already been freed. If an unmount occurs at the
wrong time, even the hugetlbfs superblock where the "quota" limits are
stored may have been freed.
Andrew Barry proposed a patch to fix this by having hugepages, instead of
storing a pointer to their address_space and reaching the superblock from
there, had the hugepages store pointers directly to the superblock,
bumping the reference count as appropriate to avoid it being freed.
Andrew Morton rejected that version, however, on the grounds that it made
the existing layering violation worse.
This is a reworked version of Andrew's patch, which removes the extra, and
some of the existing, layering violation. It works by introducing the
concept of a hugepage "subpool" at the lower hugepage mm layer - that is a
finite logical pool of hugepages to allocate from. hugetlbfs now creates
a subpool for each filesystem instance with a page limit set, and a
pointer to the subpool gets added to each allocated hugepage, instead of
the address_space pointer used now. The subpool has its own lifetime and
is only freed once all pages in it _and_ all other references to it (i.e.
superblocks) are gone.
subpools are optional - a NULL subpool pointer is taken by the code to
mean that no subpool limits are in effect.
Previous discussion of this bug found in: "Fix refcounting in hugetlbfs
quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or
http://marc.info/?l=linux-mm&m=126928970510627&w=1
v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to
alloc_huge_page() - since it already takes the vma, it is not necessary.
Signed-off-by: Andrew Barry <[email protected]>
Signed-off-by: David Gibson <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Minchan Kim <[email protected]>
Cc: Hillf Danton <[email protected]>
Cc: Paul Mackerras <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PrintPreviewUI::GetPrintPreviewDataForIndex(
int index,
scoped_refptr<base::RefCountedBytes>* data) {
print_preview_data_service()->GetDataEntry(preview_ui_addr_str_, index, data);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void OMXNodeInstance::onEvent(
OMX_EVENTTYPE event, OMX_U32 arg1, OMX_U32 arg2) {
const char *arg1String = "??";
const char *arg2String = "??";
ADebug::Level level = ADebug::kDebugInternalState;
switch (event) {
case OMX_EventCmdComplete:
arg1String = asString((OMX_COMMANDTYPE)arg1);
switch (arg1) {
case OMX_CommandStateSet:
arg2String = asString((OMX_STATETYPE)arg2);
level = ADebug::kDebugState;
break;
case OMX_CommandFlush:
case OMX_CommandPortEnable:
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
default:
arg2String = portString(arg2);
}
break;
case OMX_EventError:
arg1String = asString((OMX_ERRORTYPE)arg1);
level = ADebug::kDebugLifeCycle;
break;
case OMX_EventPortSettingsChanged:
arg2String = asString((OMX_INDEXEXTTYPE)arg2);
default:
arg1String = portString(arg1);
}
CLOGI_(level, onEvent, "%s(%x), %s(%x), %s(%x)",
asString(event), event, arg1String, arg1, arg2String, arg2);
const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource());
if (bufferSource != NULL
&& event == OMX_EventCmdComplete
&& arg1 == OMX_CommandStateSet
&& arg2 == OMX_StateExecuting) {
bufferSource->omxExecuting();
}
}
Commit Message: IOMX: allow configuration after going to loaded state
This was disallowed recently but we still use it as MediaCodcec.stop
only goes to loaded state, and does not free component.
Bug: 31450460
Change-Id: I72e092e4e55c9f23b1baee3e950d76e84a5ef28d
(cherry picked from commit e03b22839d78c841ce0a1a0a1ee1960932188b0b)
CWE ID: CWE-200
Target: 1
Example 2:
Code: void StubOfflinePageModel::DeletePagesByOfflineId(
const std::vector<int64_t>& offline_ids,
const DeletePageCallback& callback) {}
Commit Message: Add the method to check if offline archive is in internal dir
Bug: 758690
Change-Id: I8bb4283fc40a87fa7a87df2c7e513e2e16903290
Reviewed-on: https://chromium-review.googlesource.com/828049
Reviewed-by: Filip Gorski <[email protected]>
Commit-Queue: Jian Li <[email protected]>
Cr-Commit-Position: refs/heads/master@{#524232}
CWE ID: CWE-787
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CheckValueType(const Value::ValueType expected,
const Value* const actual) {
DCHECK(actual != NULL) << "Expected value to be non-NULL";
DCHECK(expected == actual->GetType())
<< "Expected " << print_valuetype(expected)
<< ", but was " << print_valuetype(actual->GetType());
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: fifo_open(notify_fifo_t* fifo, int (*script_exit)(thread_t *), const char *type)
{
int ret;
int sav_errno;
if (fifo->name) {
sav_errno = 0;
if (!(ret = mkfifo(fifo->name, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)))
fifo->created_fifo = true;
else {
sav_errno = errno;
if (sav_errno != EEXIST)
log_message(LOG_INFO, "Unable to create %snotify fifo %s", type, fifo->name);
}
if (!sav_errno || sav_errno == EEXIST) {
/* Run the notify script if there is one */
if (fifo->script)
notify_fifo_exec(master, script_exit, fifo, fifo->script);
/* Now open the fifo */
if ((fifo->fd = open(fifo->name, O_RDWR | O_CLOEXEC | O_NONBLOCK)) == -1) {
log_message(LOG_INFO, "Unable to open %snotify fifo %s - errno %d", type, fifo->name, errno);
if (fifo->created_fifo) {
unlink(fifo->name);
fifo->created_fifo = false;
}
}
}
if (fifo->fd == -1) {
FREE(fifo->name);
fifo->name = NULL;
}
}
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59
Target: 1
Example 2:
Code: static int __check_block_validity(struct inode *inode, const char *func,
unsigned int line,
struct ext4_map_blocks *map)
{
if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
map->m_len)) {
ext4_error_inode(inode, func, line, map->m_pblk,
"lblock %lu mapped to illegal pblock "
"(length %d)", (unsigned long) map->m_lblk,
map->m_len);
return -EFSCORRUPTED;
}
return 0;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void sas_probe_devices(struct work_struct *work)
{
struct domain_device *dev, *n;
struct sas_discovery_event *ev = to_sas_discovery_event(work);
struct asd_sas_port *port = ev->port;
clear_bit(DISCE_PROBE, &port->disc.pending);
/* devices must be domain members before link recovery and probe */
list_for_each_entry(dev, &port->disco_list, disco_list_node) {
spin_lock_irq(&port->dev_list_lock);
list_add_tail(&dev->dev_list_node, &port->dev_list);
spin_unlock_irq(&port->dev_list_lock);
}
sas_probe_sata(port);
list_for_each_entry_safe(dev, n, &port->disco_list, disco_list_node) {
int err;
err = sas_rphy_add(dev->rphy);
if (err)
sas_fail_probe(dev, __func__, err);
else
list_del_init(&dev->disco_list_node);
}
}
Commit Message: scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void sas_scsi_clear_queue_lu(struct list_head *error_q, struct scsi_cmnd *my_cmd)
{
struct scsi_cmnd *cmd, *n;
list_for_each_entry_safe(cmd, n, error_q, eh_entry) {
if (cmd->device->sdev_target == my_cmd->device->sdev_target &&
cmd->device->lun == my_cmd->device->lun)
sas_eh_defer_cmd(cmd);
}
}
Commit Message: scsi: libsas: defer ata device eh commands to libata
When ata device doing EH, some commands still attached with tasks are
not passed to libata when abort failed or recover failed, so libata did
not handle these commands. After these commands done, sas task is freed,
but ata qc is not freed. This will cause ata qc leak and trigger a
warning like below:
WARNING: CPU: 0 PID: 28512 at drivers/ata/libata-eh.c:4037
ata_eh_finish+0xb4/0xcc
CPU: 0 PID: 28512 Comm: kworker/u32:2 Tainted: G W OE 4.14.0#1
......
Call trace:
[<ffff0000088b7bd0>] ata_eh_finish+0xb4/0xcc
[<ffff0000088b8420>] ata_do_eh+0xc4/0xd8
[<ffff0000088b8478>] ata_std_error_handler+0x44/0x8c
[<ffff0000088b8068>] ata_scsi_port_error_handler+0x480/0x694
[<ffff000008875fc4>] async_sas_ata_eh+0x4c/0x80
[<ffff0000080f6be8>] async_run_entry_fn+0x4c/0x170
[<ffff0000080ebd70>] process_one_work+0x144/0x390
[<ffff0000080ec100>] worker_thread+0x144/0x418
[<ffff0000080f2c98>] kthread+0x10c/0x138
[<ffff0000080855dc>] ret_from_fork+0x10/0x18
If ata qc leaked too many, ata tag allocation will fail and io blocked
for ever.
As suggested by Dan Williams, defer ata device commands to libata and
merge sas_eh_finish_cmd() with sas_eh_defer_cmd(). libata will handle
ata qcs correctly after this.
Signed-off-by: Jason Yan <[email protected]>
CC: Xiaofei Tan <[email protected]>
CC: John Garry <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Dan Williams <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static void ImplementedAsVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
TestObject* impl = V8TestObject::ToImpl(info.Holder());
impl->implementedAsMethodName();
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: xsltVariableLookup(xsltTransformContextPtr ctxt, const xmlChar *name,
const xmlChar *ns_uri) {
xsltStackElemPtr elem;
if (ctxt == NULL)
return(NULL);
elem = xsltStackLookup(ctxt, name, ns_uri);
if (elem == NULL) {
return(xsltGlobalVariableLookup(ctxt, name, ns_uri));
}
if (elem->computed == 0) {
#ifdef WITH_XSLT_DEBUG_VARIABLE
XSLT_TRACE(ctxt,XSLT_TRACE_VARIABLES,xsltGenericDebug(xsltGenericDebugContext,
"uncomputed variable %s\n", name));
#endif
elem->value = xsltEvalVariable(ctxt, elem, NULL);
elem->computed = 1;
}
if (elem->value != NULL)
return(xmlXPathObjectCopy(elem->value));
#ifdef WITH_XSLT_DEBUG_VARIABLE
XSLT_TRACE(ctxt,XSLT_TRACE_VARIABLES,xsltGenericDebug(xsltGenericDebugContext,
"variable not found %s\n", name));
#endif
return(NULL);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ContentEncoding::ContentCompression::~ContentCompression() {
delete [] settings;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Target: 1
Example 2:
Code: int ip_route_input_noref(struct sk_buff *skb, __be32 daddr, __be32 saddr,
u8 tos, struct net_device *dev)
{
struct fib_result res;
int err;
tos &= IPTOS_RT_MASK;
rcu_read_lock();
err = ip_route_input_rcu(skb, daddr, saddr, tos, dev, &res);
rcu_read_unlock();
return err;
}
Commit Message: net: check and errout if res->fi is NULL when RTM_F_FIB_MATCH is set
Syzkaller hit 'general protection fault in fib_dump_info' bug on
commit 4.13-rc5..
Guilty file: net/ipv4/fib_semantics.c
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN
Modules linked in:
CPU: 0 PID: 2808 Comm: syz-executor0 Not tainted 4.13.0-rc5 #1
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS
Ubuntu-1.8.2-1ubuntu1 04/01/2014
task: ffff880078562700 task.stack: ffff880078110000
RIP: 0010:fib_dump_info+0x388/0x1170 net/ipv4/fib_semantics.c:1314
RSP: 0018:ffff880078117010 EFLAGS: 00010206
RAX: dffffc0000000000 RBX: 00000000000000fe RCX: 0000000000000002
RDX: 0000000000000006 RSI: ffff880078117084 RDI: 0000000000000030
RBP: ffff880078117268 R08: 000000000000000c R09: ffff8800780d80c8
R10: 0000000058d629b4 R11: 0000000067fce681 R12: 0000000000000000
R13: ffff8800784bd540 R14: ffff8800780d80b5 R15: ffff8800780d80a4
FS: 00000000022fa940(0000) GS:ffff88007fc00000(0000)
knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000004387d0 CR3: 0000000079135000 CR4: 00000000000006f0
Call Trace:
inet_rtm_getroute+0xc89/0x1f50 net/ipv4/route.c:2766
rtnetlink_rcv_msg+0x288/0x680 net/core/rtnetlink.c:4217
netlink_rcv_skb+0x340/0x470 net/netlink/af_netlink.c:2397
rtnetlink_rcv+0x28/0x30 net/core/rtnetlink.c:4223
netlink_unicast_kernel net/netlink/af_netlink.c:1265 [inline]
netlink_unicast+0x4c4/0x6e0 net/netlink/af_netlink.c:1291
netlink_sendmsg+0x8c4/0xca0 net/netlink/af_netlink.c:1854
sock_sendmsg_nosec net/socket.c:633 [inline]
sock_sendmsg+0xca/0x110 net/socket.c:643
___sys_sendmsg+0x779/0x8d0 net/socket.c:2035
__sys_sendmsg+0xd1/0x170 net/socket.c:2069
SYSC_sendmsg net/socket.c:2080 [inline]
SyS_sendmsg+0x2d/0x50 net/socket.c:2076
entry_SYSCALL_64_fastpath+0x1a/0xa5
RIP: 0033:0x4512e9
RSP: 002b:00007ffc75584cc8 EFLAGS: 00000216 ORIG_RAX:
000000000000002e
RAX: ffffffffffffffda RBX: 0000000000000002 RCX: 00000000004512e9
RDX: 0000000000000000 RSI: 0000000020f2cfc8 RDI: 0000000000000003
RBP: 000000000000000e R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000216 R12: fffffffffffffffe
R13: 0000000000718000 R14: 0000000020c44ff0 R15: 0000000000000000
Code: 00 0f b6 8d ec fd ff ff 48 8b 85 f0 fd ff ff 88 48 17 48 8b 45
28 48 8d 78 30 48 b8 00 00 00 00 00 fc ff df 48 89 fa 48 c1 ea 03
<0f>
b6 04 02 84 c0 74 08 3c 03 0f 8e cb 0c 00 00 48 8b 45 28 44
RIP: fib_dump_info+0x388/0x1170 net/ipv4/fib_semantics.c:1314 RSP:
ffff880078117010
---[ end trace 254a7af28348f88b ]---
This patch adds a res->fi NULL check.
example run:
$ip route get 0.0.0.0 iif virt1-0
broadcast 0.0.0.0 dev lo
cache <local,brd> iif virt1-0
$ip route get 0.0.0.0 iif virt1-0 fibmatch
RTNETLINK answers: No route to host
Reported-by: idaifish <[email protected]>
Reported-by: Dmitry Vyukov <[email protected]>
Fixes: b61798130f1b ("net: ipv4: RTM_GETROUTE: return matched fib result when requested")
Signed-off-by: Roopa Prabhu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ewk_frame_view_create_for_view(Evas_Object* ewkFrame, Evas_Object* view)
{
DBG("ewkFrame=%p, view=%p", ewkFrame, view);
EWK_FRAME_SD_GET_OR_RETURN(ewkFrame, smartData);
EINA_SAFETY_ON_NULL_RETURN(smartData->frame);
Evas_Coord width, height;
evas_object_geometry_get(view, 0, 0, &width, &height);
WebCore::IntSize size(width, height);
int red, green, blue, alpha;
WebCore::Color background;
ewk_view_bg_color_get(view, &red, &green, &blue, &alpha);
if (!alpha)
background = WebCore::Color(0, 0, 0, 0);
else if (alpha == 255)
background = WebCore::Color(red, green, blue, alpha);
else
background = WebCore::Color(red * 255 / alpha, green * 255 / alpha, blue * 255 / alpha, alpha);
smartData->frame->createView(size, background, !alpha, WebCore::IntSize(), false);
if (!smartData->frame->view())
return;
const char* theme = ewk_view_theme_get(view);
smartData->frame->view()->setEdjeTheme(theme);
smartData->frame->view()->setEvasObject(ewkFrame);
ewk_frame_mixed_content_displayed_set(ewkFrame, false);
ewk_frame_mixed_content_run_set(ewkFrame, false);
}
Commit Message: [EFL] fast/frames/frame-crash-with-page-cache.html is crashing
https://bugs.webkit.org/show_bug.cgi?id=85879
Patch by Mikhail Pozdnyakov <[email protected]> on 2012-05-17
Reviewed by Noam Rosenthal.
Source/WebKit/efl:
_ewk_frame_smart_del() is considering now that the frame can be present in cache.
loader()->detachFromParent() is only applied for the main frame.
loader()->cancelAndClear() is not used anymore.
* ewk/ewk_frame.cpp:
(_ewk_frame_smart_del):
LayoutTests:
* platform/efl/test_expectations.txt: Removed fast/frames/frame-crash-with-page-cache.html.
git-svn-id: svn://svn.chromium.org/blink/trunk@117409 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool AXNodeObject::canSetValueAttribute() const {
if (equalIgnoringCase(getAttribute(aria_readonlyAttr), "true"))
return false;
if (isProgressIndicator() || isSlider())
return true;
if (isTextControl() && !isNativeTextControl())
return true;
return !isReadOnly();
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
Target: 1
Example 2:
Code: void Layer::SetScrollOffsetFromImplSide(const gfx::Vector2d& scroll_offset) {
DCHECK(IsPropertyChangeAllowed());
DCHECK(layer_tree_host_ && layer_tree_host_->CommitRequested());
if (scroll_offset_ == scroll_offset)
return;
scroll_offset_ = scroll_offset;
SetNeedsPushProperties();
if (!did_scroll_callback_.is_null())
did_scroll_callback_.Run();
}
Commit Message: Removed pinch viewport scroll offset distribution
The associated change in Blink makes the pinch viewport a proper
ScrollableArea meaning the normal path for synchronizing layer scroll
offsets is used.
This is a 2 sided patch, the other CL:
https://codereview.chromium.org/199253002/
BUG=349941
Review URL: https://codereview.chromium.org/210543002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260105 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool Document::hasSVGRootNode() const
{
return documentElement() && documentElement()->hasTagName(SVGNames::svgTag);
}
Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document
The member is used only in Document, thus no reason to
stay in SecurityContext.
TEST=none
BUG=none
[email protected], abarth, haraken, hayato
Review URL: https://codereview.chromium.org/27615003
git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void upnp_event_prepare(struct upnp_event_notify * obj)
{
static const char notifymsg[] =
"NOTIFY %s HTTP/1.1\r\n"
"Host: %s%s\r\n"
#if (UPNP_VERSION_MAJOR == 1) && (UPNP_VERSION_MINOR == 0)
"Content-Type: text/xml\r\n" /* UDA v1.0 */
#else
"Content-Type: text/xml; charset=\"utf-8\"\r\n" /* UDA v1.1 or later */
#endif
"Content-Length: %d\r\n"
"NT: upnp:event\r\n"
"NTS: upnp:propchange\r\n"
"SID: %s\r\n"
"SEQ: %u\r\n"
"Connection: close\r\n"
"Cache-Control: no-cache\r\n"
"\r\n"
"%.*s\r\n";
char * xml;
int l;
if(obj->sub == NULL) {
obj->state = EError;
return;
}
switch(obj->sub->service) {
case EWanCFG:
xml = getVarsWANCfg(&l);
break;
case EWanIPC:
xml = getVarsWANIPCn(&l);
break;
#ifdef ENABLE_L3F_SERVICE
case EL3F:
xml = getVarsL3F(&l);
break;
#endif
#ifdef ENABLE_6FC_SERVICE
case E6FC:
xml = getVars6FC(&l);
break;
#endif
#ifdef ENABLE_DP_SERVICE
case EDP:
xml = getVarsDP(&l);
break;
#endif
default:
xml = NULL;
l = 0;
}
obj->buffersize = 1024;
obj->buffer = malloc(obj->buffersize);
if(!obj->buffer) {
syslog(LOG_ERR, "%s: malloc returned NULL", "upnp_event_prepare");
if(xml) {
free(xml);
}
obj->state = EError;
return;
}
obj->tosend = snprintf(obj->buffer, obj->buffersize, notifymsg,
obj->path, obj->addrstr, obj->portstr, l+2,
obj->sub->uuid, obj->sub->seq,
l, xml);
if(xml) {
free(xml);
xml = NULL;
}
obj->state = ESending;
}
Commit Message: upnp_event_prepare(): check the return value of snprintf()
CWE ID: CWE-200
Target: 1
Example 2:
Code: sk_deep_copy(void *sk_void, void *copy_func_void, void *free_func_void)
{
_STACK *sk = sk_void;
void *(*copy_func)(void *) = copy_func_void;
void (*free_func)(void *) = free_func_void;
_STACK *ret = sk_dup(sk);
size_t i;
if (ret == NULL)
return NULL;
for (i = 0; i < ret->num; i++) {
if (ret->data[i] == NULL)
continue;
ret->data[i] = copy_func(ret->data[i]);
if (ret->data[i] == NULL) {
size_t j;
for (j = 0; j < i; j++) {
if (ret->data[j] != NULL)
free_func(ret->data[j]);
}
sk_free(ret);
return NULL;
}
}
return ret;
}
Commit Message: Call strlen() if name length provided is 0, like OpenSSL does.
Issue notice by Christian Heimes <[email protected]>
ok deraadt@ jsing@
CWE ID: CWE-295
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t SoftMPEG2::setFlushMode() {
IV_API_CALL_STATUS_T status;
ivd_ctl_flush_ip_t s_video_flush_ip;
ivd_ctl_flush_op_t s_video_flush_op;
s_video_flush_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_video_flush_ip.e_sub_cmd = IVD_CMD_CTL_FLUSH;
s_video_flush_ip.u4_size = sizeof(ivd_ctl_flush_ip_t);
s_video_flush_op.u4_size = sizeof(ivd_ctl_flush_op_t);
/* Set the decoder in Flush mode, subsequent decode() calls will flush */
status = ivdec_api_function(
mCodecCtx, (void *)&s_video_flush_ip, (void *)&s_video_flush_op);
if (status != IV_SUCCESS) {
ALOGE("Error in setting the decoder in flush mode: (%d) 0x%x", status,
s_video_flush_op.u4_error_code);
return UNKNOWN_ERROR;
}
mWaitForI = true;
mIsInFlush = true;
return OK;
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct)
{
int c, dc;
int x, y;
int tox, toy;
int ncR, ncG, ncB;
toy = dstY;
for (y = srcY; y < (srcY + h); y++) {
tox = dstX;
for (x = srcX; x < (srcX + w); x++) {
int nc;
c = gdImageGetPixel(src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent(src) == c) {
tox++;
continue;
}
/* If it's the same image, mapping is trivial */
if (dst == src) {
nc = c;
} else {
dc = gdImageGetPixel(dst, tox, toy);
ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0));
ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0));
ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0));
/* Find a reasonable color */
nc = gdImageColorResolve (dst, ncR, ncG, ncB);
}
gdImageSetPixel (dst, tox, toy, nc);
tox++;
}
toy++;
}
}
Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int evm_find_protected_xattrs(struct dentry *dentry)
{
struct inode *inode = d_backing_inode(dentry);
char **xattr;
int error;
int count = 0;
if (!inode->i_op->getxattr)
return -EOPNOTSUPP;
for (xattr = evm_config_xattrnames; *xattr != NULL; xattr++) {
error = inode->i_op->getxattr(dentry, *xattr, NULL, 0);
if (error < 0) {
if (error == -ENODATA)
continue;
return error;
}
count++;
}
return count;
}
Commit Message: EVM: Use crypto_memneq() for digest comparisons
This patch fixes vulnerability CVE-2016-2085. The problem exists
because the vm_verify_hmac() function includes a use of memcmp().
Unfortunately, this allows timing side channel attacks; specifically
a MAC forgery complexity drop from 2^128 to 2^12. This patch changes
the memcmp() to the cryptographically safe crypto_memneq().
Reported-by: Xiaofei Rex Guo <[email protected]>
Signed-off-by: Ryan Ware <[email protected]>
Cc: [email protected]
Signed-off-by: Mimi Zohar <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-19
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void StartExtractFileFeatures() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(item_); // Called directly from Start(), item should still exist.
BrowserThread::GetBlockingPool()->PostWorkerTaskWithShutdownBehavior(
FROM_HERE,
base::Bind(&CheckClientDownloadRequest::ExtractFileFeatures,
this, item_->GetFullPath()),
base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN);
}
Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService.
BUG=496898,464083
[email protected], [email protected], [email protected], [email protected]
Review URL: https://codereview.chromium.org/1299223006 .
Cr-Commit-Position: refs/heads/master@{#344876}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DCTStream::init()
{
jpeg_std_error(&jerr);
jerr.error_exit = &exitErrorHandler;
src.pub.init_source = str_init_source;
src.pub.fill_input_buffer = str_fill_input_buffer;
src.pub.skip_input_data = str_skip_input_data;
src.pub.resync_to_restart = jpeg_resync_to_restart;
src.pub.term_source = str_term_source;
src.pub.next_input_byte = NULL;
src.str = str;
src.index = 0;
src.abort = false;
current = NULL;
limit = NULL;
limit = NULL;
cinfo.err = &jerr;
jpeg_create_decompress(&cinfo);
cinfo.src = (jpeg_source_mgr *)&src;
row_buffer = NULL;
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: tt_cmap0_char_index( TT_CMap cmap,
FT_UInt32 char_code )
{
FT_Byte* table = cmap->data;
return char_code < 256 ? table[6 + char_code] : 0;
}
Commit Message:
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: WebsiteSettings::~WebsiteSettings() {
}
Commit Message: Fix UAF in Origin Info Bubble and permission settings UI.
In addition to fixing the UAF, will this also fix the problem of the bubble
showing over the previous tab (if the bubble is open when the tab it was opened
for closes).
BUG=490492
TBR=tedchoc
Review URL: https://codereview.chromium.org/1317443002
Cr-Commit-Position: refs/heads/master@{#346023}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DocumentLoader::responseReceived(CachedResource* resource, const ResourceResponse& response)
{
ASSERT_UNUSED(resource, m_mainResource == resource);
RefPtr<DocumentLoader> protect(this);
bool willLoadFallback = m_applicationCacheHost->maybeLoadFallbackForMainResponse(request(), response);
bool shouldRemoveResourceFromCache = willLoadFallback;
#if PLATFORM(CHROMIUM)
if (response.appCacheID())
shouldRemoveResourceFromCache = true;
#endif
if (shouldRemoveResourceFromCache)
memoryCache()->remove(m_mainResource.get());
if (willLoadFallback)
return;
DEFINE_STATIC_LOCAL(AtomicString, xFrameOptionHeader, ("x-frame-options", AtomicString::ConstructFromLiteral));
HTTPHeaderMap::const_iterator it = response.httpHeaderFields().find(xFrameOptionHeader);
if (it != response.httpHeaderFields().end()) {
String content = it->value;
ASSERT(m_mainResource);
unsigned long identifier = m_identifierForLoadWithoutResourceLoader ? m_identifierForLoadWithoutResourceLoader : m_mainResource->identifier();
ASSERT(identifier);
if (frameLoader()->shouldInterruptLoadForXFrameOptions(content, response.url(), identifier)) {
InspectorInstrumentation::continueAfterXFrameOptionsDenied(m_frame, this, identifier, response);
String message = "Refused to display '" + response.url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
frame()->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, identifier);
frame()->document()->enforceSandboxFlags(SandboxOrigin);
if (HTMLFrameOwnerElement* ownerElement = frame()->ownerElement())
ownerElement->dispatchEvent(Event::create(eventNames().loadEvent, false, false));
cancelMainResourceLoad(frameLoader()->cancelledError(m_request));
return;
}
}
#if !USE(CF)
ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading());
#endif
if (m_isLoadingMultipartContent) {
setupForReplace();
m_mainResource->clear();
} else if (response.isMultipart()) {
FeatureObserver::observe(m_frame->document(), FeatureObserver::MultipartMainResource);
m_isLoadingMultipartContent = true;
}
m_response = response;
if (m_identifierForLoadWithoutResourceLoader)
frameLoader()->notifier()->dispatchDidReceiveResponse(this, m_identifierForLoadWithoutResourceLoader, m_response, 0);
ASSERT(!m_waitingForContentPolicy);
m_waitingForContentPolicy = true;
if (m_substituteData.isValid()) {
continueAfterContentPolicy(PolicyUse);
return;
}
#if ENABLE(FTPDIR)
Settings* settings = m_frame->settings();
if (settings && settings->forceFTPDirectoryListings() && m_response.mimeType() == "application/x-ftp-directory") {
continueAfterContentPolicy(PolicyUse);
return;
}
#endif
#if USE(CONTENT_FILTERING)
if (response.url().protocolIs("https") && ContentFilter::isEnabled())
m_contentFilter = ContentFilter::create(response);
#endif
frameLoader()->policyChecker()->checkContentPolicy(m_response, callContinueAfterContentPolicy, this);
}
Commit Message: Unreviewed, rolling out r147402.
http://trac.webkit.org/changeset/147402
https://bugs.webkit.org/show_bug.cgi?id=112903
Source/WebCore:
* dom/Document.cpp:
(WebCore::Document::processHttpEquiv):
* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::responseReceived):
LayoutTests:
* http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html:
* http/tests/security/XFrameOptions/x-frame-options-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool InputType::CanBeSuccessfulSubmitButton() {
return false;
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void smp_process_keypress_notification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
uint8_t* p = (uint8_t*)p_data;
uint8_t reason = SMP_INVALID_PARAMETERS;
SMP_TRACE_DEBUG("%s", __func__);
p_cb->status = *(uint8_t*)p_data;
if (smp_command_has_invalid_parameters(p_cb)) {
smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason);
return;
}
if (p != NULL) {
STREAM_TO_UINT8(p_cb->peer_keypress_notification, p);
} else {
p_cb->peer_keypress_notification = BTM_SP_KEY_OUT_OF_RANGE;
}
p_cb->cb_evt = SMP_PEER_KEYPR_NOT_EVT;
}
Commit Message: DO NOT MERGE Fix OOB read before buffer length check
Bug: 111936834
Test: manual
Change-Id: Ib98528fb62db0d724ebd9112d071e367f78e369d
(cherry picked from commit 4548f34c90803c6544f6bed03399f2eabeab2a8e)
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ocfs2_setattr(struct dentry *dentry, struct iattr *attr)
{
int status = 0, size_change;
int inode_locked = 0;
struct inode *inode = d_inode(dentry);
struct super_block *sb = inode->i_sb;
struct ocfs2_super *osb = OCFS2_SB(sb);
struct buffer_head *bh = NULL;
handle_t *handle = NULL;
struct dquot *transfer_to[MAXQUOTAS] = { };
int qtype;
int had_lock;
struct ocfs2_lock_holder oh;
trace_ocfs2_setattr(inode, dentry,
(unsigned long long)OCFS2_I(inode)->ip_blkno,
dentry->d_name.len, dentry->d_name.name,
attr->ia_valid, attr->ia_mode,
from_kuid(&init_user_ns, attr->ia_uid),
from_kgid(&init_user_ns, attr->ia_gid));
/* ensuring we don't even attempt to truncate a symlink */
if (S_ISLNK(inode->i_mode))
attr->ia_valid &= ~ATTR_SIZE;
#define OCFS2_VALID_ATTRS (ATTR_ATIME | ATTR_MTIME | ATTR_CTIME | ATTR_SIZE \
| ATTR_GID | ATTR_UID | ATTR_MODE)
if (!(attr->ia_valid & OCFS2_VALID_ATTRS))
return 0;
status = setattr_prepare(dentry, attr);
if (status)
return status;
if (is_quota_modification(inode, attr)) {
status = dquot_initialize(inode);
if (status)
return status;
}
size_change = S_ISREG(inode->i_mode) && attr->ia_valid & ATTR_SIZE;
if (size_change) {
status = ocfs2_rw_lock(inode, 1);
if (status < 0) {
mlog_errno(status);
goto bail;
}
}
had_lock = ocfs2_inode_lock_tracker(inode, &bh, 1, &oh);
if (had_lock < 0) {
status = had_lock;
goto bail_unlock_rw;
} else if (had_lock) {
/*
* As far as we know, ocfs2_setattr() could only be the first
* VFS entry point in the call chain of recursive cluster
* locking issue.
*
* For instance:
* chmod_common()
* notify_change()
* ocfs2_setattr()
* posix_acl_chmod()
* ocfs2_iop_get_acl()
*
* But, we're not 100% sure if it's always true, because the
* ordering of the VFS entry points in the call chain is out
* of our control. So, we'd better dump the stack here to
* catch the other cases of recursive locking.
*/
mlog(ML_ERROR, "Another case of recursive locking:\n");
dump_stack();
}
inode_locked = 1;
if (size_change) {
status = inode_newsize_ok(inode, attr->ia_size);
if (status)
goto bail_unlock;
inode_dio_wait(inode);
if (i_size_read(inode) >= attr->ia_size) {
if (ocfs2_should_order_data(inode)) {
status = ocfs2_begin_ordered_truncate(inode,
attr->ia_size);
if (status)
goto bail_unlock;
}
status = ocfs2_truncate_file(inode, bh, attr->ia_size);
} else
status = ocfs2_extend_file(inode, bh, attr->ia_size);
if (status < 0) {
if (status != -ENOSPC)
mlog_errno(status);
status = -ENOSPC;
goto bail_unlock;
}
}
if ((attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
(attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
/*
* Gather pointers to quota structures so that allocation /
* freeing of quota structures happens here and not inside
* dquot_transfer() where we have problems with lock ordering
*/
if (attr->ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)
&& OCFS2_HAS_RO_COMPAT_FEATURE(sb,
OCFS2_FEATURE_RO_COMPAT_USRQUOTA)) {
transfer_to[USRQUOTA] = dqget(sb, make_kqid_uid(attr->ia_uid));
if (IS_ERR(transfer_to[USRQUOTA])) {
status = PTR_ERR(transfer_to[USRQUOTA]);
goto bail_unlock;
}
}
if (attr->ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid)
&& OCFS2_HAS_RO_COMPAT_FEATURE(sb,
OCFS2_FEATURE_RO_COMPAT_GRPQUOTA)) {
transfer_to[GRPQUOTA] = dqget(sb, make_kqid_gid(attr->ia_gid));
if (IS_ERR(transfer_to[GRPQUOTA])) {
status = PTR_ERR(transfer_to[GRPQUOTA]);
goto bail_unlock;
}
}
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS +
2 * ocfs2_quota_trans_credits(sb));
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto bail_unlock;
}
status = __dquot_transfer(inode, transfer_to);
if (status < 0)
goto bail_commit;
} else {
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto bail_unlock;
}
}
setattr_copy(inode, attr);
mark_inode_dirty(inode);
status = ocfs2_mark_inode_dirty(handle, inode, bh);
if (status < 0)
mlog_errno(status);
bail_commit:
ocfs2_commit_trans(osb, handle);
bail_unlock:
if (status && inode_locked) {
ocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock);
inode_locked = 0;
}
bail_unlock_rw:
if (size_change)
ocfs2_rw_unlock(inode, 1);
bail:
/* Release quota pointers in case we acquired them */
for (qtype = 0; qtype < OCFS2_MAXQUOTAS; qtype++)
dqput(transfer_to[qtype]);
if (!status && attr->ia_valid & ATTR_MODE) {
status = ocfs2_acl_chmod(inode, bh);
if (status < 0)
mlog_errno(status);
}
if (inode_locked)
ocfs2_inode_unlock_tracker(inode, 1, &oh, had_lock);
brelse(bh);
return status;
}
Commit Message: ocfs2: should wait dio before inode lock in ocfs2_setattr()
we should wait dio requests to finish before inode lock in
ocfs2_setattr(), otherwise the following deadlock will happen:
process 1 process 2 process 3
truncate file 'A' end_io of writing file 'A' receiving the bast messages
ocfs2_setattr
ocfs2_inode_lock_tracker
ocfs2_inode_lock_full
inode_dio_wait
__inode_dio_wait
-->waiting for all dio
requests finish
dlm_proxy_ast_handler
dlm_do_local_bast
ocfs2_blocking_ast
ocfs2_generic_handle_bast
set OCFS2_LOCK_BLOCKED flag
dio_end_io
dio_bio_end_aio
dio_complete
ocfs2_dio_end_io
ocfs2_dio_end_io_write
ocfs2_inode_lock
__ocfs2_cluster_lock
ocfs2_wait_for_mask
-->waiting for OCFS2_LOCK_BLOCKED
flag to be cleared, that is waiting
for 'process 1' unlocking the inode lock
inode_dio_end
-->here dec the i_dio_count, but will never
be called, so a deadlock happened.
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Alex Chen <[email protected]>
Reviewed-by: Jun Piao <[email protected]>
Reviewed-by: Joseph Qi <[email protected]>
Acked-by: Changwei Ge <[email protected]>
Cc: Mark Fasheh <[email protected]>
Cc: Joel Becker <[email protected]>
Cc: Junxiao Bi <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: void WebContentsImpl::SetUserAgentOverride(const std::string& override) {
if (GetUserAgentOverride() == override)
return;
renderer_preferences_.user_agent_override = override;
RenderViewHost* host = GetRenderViewHost();
if (host)
host->SyncRendererPrefs();
NavigationEntry* entry = controller_.GetVisibleEntry();
if (IsLoading() && entry != NULL && entry->GetIsOverridingUserAgent())
controller_.Reload(ReloadType::BYPASSING_CACHE, true);
for (auto& observer : observers_)
observer.UserAgentOverrideSet(override);
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void StackDumpSignalHandler(int signal, siginfo_t* info, void* void_context) {
in_signal_handler = 1;
if (BeingDebugged())
BreakDebugger();
PrintToStderr("Received signal ");
char buf[1024] = { 0 };
internal::itoa_r(signal, buf, sizeof(buf), 10, 0);
PrintToStderr(buf);
if (signal == SIGBUS) {
if (info->si_code == BUS_ADRALN)
PrintToStderr(" BUS_ADRALN ");
else if (info->si_code == BUS_ADRERR)
PrintToStderr(" BUS_ADRERR ");
else if (info->si_code == BUS_OBJERR)
PrintToStderr(" BUS_OBJERR ");
else
PrintToStderr(" <unknown> ");
} else if (signal == SIGFPE) {
if (info->si_code == FPE_FLTDIV)
PrintToStderr(" FPE_FLTDIV ");
else if (info->si_code == FPE_FLTINV)
PrintToStderr(" FPE_FLTINV ");
else if (info->si_code == FPE_FLTOVF)
PrintToStderr(" FPE_FLTOVF ");
else if (info->si_code == FPE_FLTRES)
PrintToStderr(" FPE_FLTRES ");
else if (info->si_code == FPE_FLTSUB)
PrintToStderr(" FPE_FLTSUB ");
else if (info->si_code == FPE_FLTUND)
PrintToStderr(" FPE_FLTUND ");
else if (info->si_code == FPE_INTDIV)
PrintToStderr(" FPE_INTDIV ");
else if (info->si_code == FPE_INTOVF)
PrintToStderr(" FPE_INTOVF ");
else
PrintToStderr(" <unknown> ");
} else if (signal == SIGILL) {
if (info->si_code == ILL_BADSTK)
PrintToStderr(" ILL_BADSTK ");
else if (info->si_code == ILL_COPROC)
PrintToStderr(" ILL_COPROC ");
else if (info->si_code == ILL_ILLOPN)
PrintToStderr(" ILL_ILLOPN ");
else if (info->si_code == ILL_ILLADR)
PrintToStderr(" ILL_ILLADR ");
else if (info->si_code == ILL_ILLTRP)
PrintToStderr(" ILL_ILLTRP ");
else if (info->si_code == ILL_PRVOPC)
PrintToStderr(" ILL_PRVOPC ");
else if (info->si_code == ILL_PRVREG)
PrintToStderr(" ILL_PRVREG ");
else
PrintToStderr(" <unknown> ");
} else if (signal == SIGSEGV) {
if (info->si_code == SEGV_MAPERR)
PrintToStderr(" SEGV_MAPERR ");
else if (info->si_code == SEGV_ACCERR)
PrintToStderr(" SEGV_ACCERR ");
else
PrintToStderr(" <unknown> ");
}
if (signal == SIGBUS || signal == SIGFPE ||
signal == SIGILL || signal == SIGSEGV) {
internal::itoa_r(reinterpret_cast<intptr_t>(info->si_addr),
buf, sizeof(buf), 16, 12);
PrintToStderr(buf);
}
PrintToStderr("\n");
debug::StackTrace().Print();
#if defined(OS_LINUX)
#if ARCH_CPU_X86_FAMILY
ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
const struct {
const char* label;
greg_t value;
} registers[] = {
#if ARCH_CPU_32_BITS
{ " gs: ", context->uc_mcontext.gregs[REG_GS] },
{ " fs: ", context->uc_mcontext.gregs[REG_FS] },
{ " es: ", context->uc_mcontext.gregs[REG_ES] },
{ " ds: ", context->uc_mcontext.gregs[REG_DS] },
{ " edi: ", context->uc_mcontext.gregs[REG_EDI] },
{ " esi: ", context->uc_mcontext.gregs[REG_ESI] },
{ " ebp: ", context->uc_mcontext.gregs[REG_EBP] },
{ " esp: ", context->uc_mcontext.gregs[REG_ESP] },
{ " ebx: ", context->uc_mcontext.gregs[REG_EBX] },
{ " edx: ", context->uc_mcontext.gregs[REG_EDX] },
{ " ecx: ", context->uc_mcontext.gregs[REG_ECX] },
{ " eax: ", context->uc_mcontext.gregs[REG_EAX] },
{ " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
{ " err: ", context->uc_mcontext.gregs[REG_ERR] },
{ " ip: ", context->uc_mcontext.gregs[REG_EIP] },
{ " cs: ", context->uc_mcontext.gregs[REG_CS] },
{ " efl: ", context->uc_mcontext.gregs[REG_EFL] },
{ " usp: ", context->uc_mcontext.gregs[REG_UESP] },
{ " ss: ", context->uc_mcontext.gregs[REG_SS] },
#elif ARCH_CPU_64_BITS
{ " r8: ", context->uc_mcontext.gregs[REG_R8] },
{ " r9: ", context->uc_mcontext.gregs[REG_R9] },
{ " r10: ", context->uc_mcontext.gregs[REG_R10] },
{ " r11: ", context->uc_mcontext.gregs[REG_R11] },
{ " r12: ", context->uc_mcontext.gregs[REG_R12] },
{ " r13: ", context->uc_mcontext.gregs[REG_R13] },
{ " r14: ", context->uc_mcontext.gregs[REG_R14] },
{ " r15: ", context->uc_mcontext.gregs[REG_R15] },
{ " di: ", context->uc_mcontext.gregs[REG_RDI] },
{ " si: ", context->uc_mcontext.gregs[REG_RSI] },
{ " bp: ", context->uc_mcontext.gregs[REG_RBP] },
{ " bx: ", context->uc_mcontext.gregs[REG_RBX] },
{ " dx: ", context->uc_mcontext.gregs[REG_RDX] },
{ " ax: ", context->uc_mcontext.gregs[REG_RAX] },
{ " cx: ", context->uc_mcontext.gregs[REG_RCX] },
{ " sp: ", context->uc_mcontext.gregs[REG_RSP] },
{ " ip: ", context->uc_mcontext.gregs[REG_RIP] },
{ " efl: ", context->uc_mcontext.gregs[REG_EFL] },
{ " cgf: ", context->uc_mcontext.gregs[REG_CSGSFS] },
{ " erf: ", context->uc_mcontext.gregs[REG_ERR] },
{ " trp: ", context->uc_mcontext.gregs[REG_TRAPNO] },
{ " msk: ", context->uc_mcontext.gregs[REG_OLDMASK] },
{ " cr2: ", context->uc_mcontext.gregs[REG_CR2] },
#endif
};
#if ARCH_CPU_32_BITS
const int kRegisterPadding = 8;
#elif ARCH_CPU_64_BITS
const int kRegisterPadding = 16;
#endif
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(registers); i++) {
PrintToStderr(registers[i].label);
internal::itoa_r(registers[i].value, buf, sizeof(buf),
16, kRegisterPadding);
PrintToStderr(buf);
if ((i + 1) % 4 == 0)
PrintToStderr("\n");
}
PrintToStderr("\n");
#endif
#elif defined(OS_MACOSX)
#if ARCH_CPU_X86_FAMILY && ARCH_CPU_32_BITS
ucontext_t* context = reinterpret_cast<ucontext_t*>(void_context);
size_t len;
len = static_cast<size_t>(
snprintf(buf, sizeof(buf),
"ax: %x, bx: %x, cx: %x, dx: %x\n",
context->uc_mcontext->__ss.__eax,
context->uc_mcontext->__ss.__ebx,
context->uc_mcontext->__ss.__ecx,
context->uc_mcontext->__ss.__edx));
write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
len = static_cast<size_t>(
snprintf(buf, sizeof(buf),
"di: %x, si: %x, bp: %x, sp: %x, ss: %x, flags: %x\n",
context->uc_mcontext->__ss.__edi,
context->uc_mcontext->__ss.__esi,
context->uc_mcontext->__ss.__ebp,
context->uc_mcontext->__ss.__esp,
context->uc_mcontext->__ss.__ss,
context->uc_mcontext->__ss.__eflags));
write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
len = static_cast<size_t>(
snprintf(buf, sizeof(buf),
"ip: %x, cs: %x, ds: %x, es: %x, fs: %x, gs: %x\n",
context->uc_mcontext->__ss.__eip,
context->uc_mcontext->__ss.__cs,
context->uc_mcontext->__ss.__ds,
context->uc_mcontext->__ss.__es,
context->uc_mcontext->__ss.__fs,
context->uc_mcontext->__ss.__gs));
write(STDERR_FILENO, buf, std::min(len, sizeof(buf) - 1));
#endif // ARCH_CPU_32_BITS
#endif // defined(OS_MACOSX)
_exit(1);
}
Commit Message: Convert ARRAYSIZE_UNSAFE -> arraysize in base/.
[email protected]
BUG=423134
Review URL: https://codereview.chromium.org/656033009
Cr-Commit-Position: refs/heads/master@{#299835}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
int dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, *iter, *iteriter, *regexiter = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
MAKE_STD_ZVAL(iter);
if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg);
ZVAL_STRINGL(&arg, dir, dir_len, 0);
INIT_PZVAL(&arg2);
#if PHP_VERSION_ID < 50300
ZVAL_LONG(&arg2, 0);
#else
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
#endif
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
MAKE_STD_ZVAL(iteriter);
if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
MAKE_STD_ZVAL(regexiter);
if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(regexiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg2);
ZVAL_STRINGL(&arg2, regex, regex_len, 0);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: static MagickBooleanType WriteBGRImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Allocate memory for pixels.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image_info->interlace != PartitionInterlace)
{
/*
Open output image file.
*/
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
}
quantum_type=BGRQuantum;
if (LocaleCompare(image_info->magick,"BGRA") == 0)
{
quantum_type=BGRAQuantum;
image->matte=MagickTrue;
}
scene=0;
do
{
/*
Convert MIFF to BGR raster pixels.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
if ((LocaleCompare(image_info->magick,"BGRA") == 0) &&
(image->matte == MagickFalse))
(void) SetImageAlphaChannel(image,ResetAlphaChannel);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
switch (image_info->interlace)
{
case NoInterlace:
default:
{
/*
No interlacing: BGRBGRBGRBGRBGRBGR...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case LineInterlace:
{
/*
Line interlacing: BBB...GGG...RRR...RRR...GGG...BBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
if (quantum_type == BGRAQuantum)
{
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,1,6);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,2,6);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,3,6);
if (status == MagickFalse)
break;
}
if (quantum_type == BGRAQuantum)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,5,6);
if (status == MagickFalse)
break;
}
}
if (image_info->interlace == PartitionInterlace)
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,6,6);
if (status == MagickFalse)
break;
}
break;
}
case PartitionInterlace:
{
/*
Partition interlacing: BBBBBB..., GGGGGG..., RRRRRR...
*/
AppendImageFormat("B",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,1,6);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
AppendImageFormat("G",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,2,6);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
AppendImageFormat("R",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,3,6);
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
if (quantum_type == BGRAQuantum)
{
(void) CloseBlob(image);
AppendImageFormat("A",image->filename);
status=OpenBlob(image_info,image,scene == 0 ? WriteBinaryBlobMode :
AppendBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
length=ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
count=WriteBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,5,6);
if (status == MagickFalse)
break;
}
}
(void) CloseBlob(image);
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,6,6);
if (status == MagickFalse)
break;
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderFrameImpl::SendUpdateState() {
if (current_history_item_.IsNull())
return;
Send(new FrameHostMsg_UpdateState(
routing_id_, SingleHistoryItemToPageState(current_history_item_)));
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
format,
magick[MagickPathExtent];
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
Quantum
index;
QuantumAny
pixel;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register unsigned char
*q;
size_t
extent,
imageListLength,
packet_size;
ssize_t
count,
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
imageListLength=GetImageListLength(image);
do
{
QuantumAny
max_value;
/*
Write PNM file header.
*/
packet_size=3;
quantum_type=RGBQuantum;
(void) CopyMagickString(magick,image_info->magick,MagickPathExtent);
max_value=GetQuantumRange(image->depth);
switch (magick[1])
{
case 'A':
case 'a':
{
format='7';
break;
}
case 'B':
case 'b':
{
format='4';
if (image_info->compression == NoCompression)
format='1';
break;
}
case 'F':
case 'f':
{
format='F';
if (SetImageGray(image,exception) != MagickFalse)
format='f';
break;
}
case 'G':
case 'g':
{
format='5';
if (image_info->compression == NoCompression)
format='2';
break;
}
case 'N':
case 'n':
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
format='5';
if (image_info->compression == NoCompression)
format='2';
if (SetImageMonochrome(image,exception) != MagickFalse)
{
format='4';
if (image_info->compression == NoCompression)
format='1';
}
break;
}
}
default:
{
format='6';
if (image_info->compression == NoCompression)
format='3';
break;
}
}
(void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,"comment",exception);
if (value != (const char *) NULL)
{
register const char
*p;
/*
Write comments to file.
*/
(void) WriteBlobByte(image,'#');
for (p=value; *p != '\0'; p++)
{
(void) WriteBlobByte(image,(unsigned char) *p);
if ((*p == '\n') || (*p == '\r'))
(void) WriteBlobByte(image,'#');
}
(void) WriteBlobByte(image,'\n');
}
if (format != '7')
{
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n",
(double) image->columns,(double) image->rows);
(void) WriteBlobString(image,buffer);
}
else
{
char
type[MagickPathExtent];
/*
PAM header.
*/
(void) FormatLocaleString(buffer,MagickPathExtent,
"WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double)
image->rows);
(void) WriteBlobString(image,buffer);
quantum_type=GetQuantumType(image,exception);
switch (quantum_type)
{
case CMYKQuantum:
case CMYKAQuantum:
{
packet_size=4;
(void) CopyMagickString(type,"CMYK",MagickPathExtent);
break;
}
case GrayQuantum:
case GrayAlphaQuantum:
{
packet_size=1;
(void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent);
if (IdentifyImageMonochrome(image,exception) != MagickFalse)
(void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent);
break;
}
default:
{
quantum_type=RGBQuantum;
if (image->alpha_trait != UndefinedPixelTrait)
quantum_type=RGBAQuantum;
packet_size=3;
(void) CopyMagickString(type,"RGB",MagickPathExtent);
break;
}
}
if (image->alpha_trait != UndefinedPixelTrait)
{
packet_size++;
(void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent);
}
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,
"DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MagickPathExtent,
"TUPLTYPE %s\nENDHDR\n",type);
(void) WriteBlobString(image,buffer);
}
/*
Convert runextent encoded to PNM raster pixels.
*/
switch (format)
{
case '1':
{
unsigned char
pixels[2048];
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ?
'0' : '1');
*q++=' ';
if ((q-pixels+1) >= (ssize_t) sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '2':
{
unsigned char
pixels[2048];
/*
Convert image to a PGM image.
*/
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ClampToQuantum(GetPixelLuma(image,p));
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ",
ScaleQuantumToChar(index));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToShort(index));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u ",ScaleQuantumToLong(index));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '3':
{
unsigned char
pixels[2048];
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth <= 8)
(void) WriteBlobString(image,"255\n");
else
if (image->depth <= 16)
(void) WriteBlobString(image,"65535\n");
else
(void) WriteBlobString(image,"4294967295\n");
q=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->depth <= 8)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)),
ScaleQuantumToChar(GetPixelGreen(image,p)),
ScaleQuantumToChar(GetPixelBlue(image,p)));
else
if (image->depth <= 16)
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)),
ScaleQuantumToShort(GetPixelGreen(image,p)),
ScaleQuantumToShort(GetPixelBlue(image,p)));
else
count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,
"%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)),
ScaleQuantumToLong(GetPixelGreen(image,p)),
ScaleQuantumToLong(GetPixelBlue(image,p)));
extent=(size_t) count;
(void) strncpy((char *) q,buffer,extent);
q+=extent;
if ((q-pixels+extent+2) >= sizeof(pixels))
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
}
p+=GetPixelChannels(image);
}
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
q=pixels;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (q != pixels)
{
*q++='\n';
(void) WriteBlob(image,q-pixels,pixels);
}
break;
}
case '4':
{
register unsigned char
*pixels;
/*
Convert image to a PBM image.
*/
(void) SetImageType(image,BilevelType,exception);
image->depth=1;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '5':
{
register unsigned char
*pixels;
/*
Convert image to a PGM image.
*/
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
quantum_info->min_is_white=MagickTrue;
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,GrayQuantum);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
else
{
if (image->depth == 8)
pixel=ScaleQuantumToChar(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToShort(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),
max_value);
}
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsPixelGray(image,p) == MagickFalse)
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)),
max_value);
else
{
if (image->depth == 16)
pixel=ScaleQuantumToLong(GetPixelRed(image,p));
else
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
}
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '6':
{
register unsigned char
*pixels;
/*
Convert image to a PNM image.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if (image->depth > 32)
image->depth=32;
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double)
((MagickOffsetType) GetQuantumRange(image->depth)));
(void) WriteBlobString(image,buffer);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
p+=GetPixelChannels(image);
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case '7':
{
register unsigned char
*pixels;
/*
Convert image to a PAM.
*/
if (image->depth > 32)
image->depth=32;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
switch (image->depth)
{
case 8:
case 16:
case 32:
{
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
break;
}
default:
{
switch (quantum_type)
{
case GrayQuantum:
case GrayAlphaQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(
image,p)),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,
p)),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=(unsigned char) ScaleQuantumToAny(
GetPixelAlpha(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
case CMYKQuantum:
case CMYKAQuantum:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
default:
{
if (image->depth <= 8)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopCharPixel((unsigned char) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
if (image->depth <= 16)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopShortPixel(MSBEndian,(unsigned short) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
pixel=ScaleQuantumToAny(GetPixelAlpha(image,p),
max_value);
q=PopLongPixel(MSBEndian,(unsigned int) pixel,q);
}
p+=GetPixelChannels(image);
}
break;
}
}
extent=(size_t) (q-pixels);
break;
}
}
count=WriteBlob(image,extent,pixels);
if (count != (ssize_t) extent)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
case 'F':
case 'f':
{
register unsigned char
*pixels;
(void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" :
"1.0\n");
image->depth=32;
quantum_type=format == 'f' ? GrayQuantum : RGBQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
register const Quantum
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
(void) WriteBlob(image,extent,pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
break;
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1613
CWE ID: CWE-119
Target: 1
Example 2:
Code: select_dh_group(krb5_context context, DH *dh, unsigned long bits,
struct krb5_dh_moduli **moduli)
{
const struct krb5_dh_moduli *m;
if (bits == 0) {
m = moduli[1]; /* XXX */
if (m == NULL)
m = moduli[0]; /* XXX */
} else {
int i;
for (i = 0; moduli[i] != NULL; i++) {
if (bits < moduli[i]->bits)
break;
}
if (moduli[i] == NULL) {
krb5_set_error_message(context, EINVAL,
N_("Did not find a DH group parameter "
"matching requirement of %lu bits", ""),
bits);
return EINVAL;
}
m = moduli[i];
}
dh->p = integer_to_BN(context, "p", &m->p);
if (dh->p == NULL)
return ENOMEM;
dh->g = integer_to_BN(context, "g", &m->g);
if (dh->g == NULL)
return ENOMEM;
dh->q = integer_to_BN(context, "q", &m->q);
if (dh->q == NULL)
return ENOMEM;
return 0;
}
Commit Message: CVE-2019-12098: krb5: always confirm PA-PKINIT-KX for anon PKINIT
RFC8062 Section 7 requires verification of the PA-PKINIT-KX key excahnge
when anonymous PKINIT is used. Failure to do so can permit an active
attacker to become a man-in-the-middle.
Introduced by a1ef548600c5bb51cf52a9a9ea12676506ede19f. First tagged
release Heimdal 1.4.0.
CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N (4.8)
Change-Id: I6cc1c0c24985936468af08693839ac6c3edda133
Signed-off-by: Jeffrey Altman <[email protected]>
Approved-by: Jeffrey Altman <[email protected]>
(cherry picked from commit 38c797e1ae9b9c8f99ae4aa2e73957679031fd2b)
CWE ID: CWE-320
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len)
{
struct inet_sock *inet = inet_sk(sk);
struct udp_sock *up = udp_sk(sk);
struct flowi4 *fl4;
int ulen = len;
struct ipcm_cookie ipc;
struct rtable *rt = NULL;
int free = 0;
int connected = 0;
__be32 daddr, faddr, saddr;
__be16 dport;
u8 tos;
int err, is_udplite = IS_UDPLITE(sk);
int corkreq = up->corkflag || msg->msg_flags&MSG_MORE;
int (*getfrag)(void *, char *, int, int, int, struct sk_buff *);
struct sk_buff *skb;
if (len > 0xFFFF)
return -EMSGSIZE;
/*
* Check the flags.
*/
if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */
return -EOPNOTSUPP;
ipc.opt = NULL;
ipc.tx_flags = 0;
getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag;
if (up->pending) {
/*
* There are pending frames.
* The socket lock must be held while it's corked.
*/
lock_sock(sk);
if (likely(up->pending)) {
if (unlikely(up->pending != AF_INET)) {
release_sock(sk);
return -EINVAL;
}
goto do_append_data;
}
release_sock(sk);
}
ulen += sizeof(struct udphdr);
/*
* Get and verify the address.
*/
if (msg->msg_name) {
struct sockaddr_in * usin = (struct sockaddr_in *)msg->msg_name;
if (msg->msg_namelen < sizeof(*usin))
return -EINVAL;
if (usin->sin_family != AF_INET) {
if (usin->sin_family != AF_UNSPEC)
return -EAFNOSUPPORT;
}
daddr = usin->sin_addr.s_addr;
dport = usin->sin_port;
if (dport == 0)
return -EINVAL;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
daddr = inet->inet_daddr;
dport = inet->inet_dport;
/* Open fast path for connected socket.
Route will not be used, if at least one option is set.
*/
connected = 1;
}
ipc.addr = inet->inet_saddr;
ipc.oif = sk->sk_bound_dev_if;
err = sock_tx_timestamp(sk, &ipc.tx_flags);
if (err)
return err;
if (msg->msg_controllen) {
err = ip_cmsg_send(sock_net(sk), msg, &ipc);
if (err)
return err;
if (ipc.opt)
free = 1;
connected = 0;
}
if (!ipc.opt)
ipc.opt = inet->opt;
saddr = ipc.addr;
ipc.addr = faddr = daddr;
if (ipc.opt && ipc.opt->srr) {
if (!daddr)
return -EINVAL;
faddr = ipc.opt->faddr;
connected = 0;
}
tos = RT_TOS(inet->tos);
if (sock_flag(sk, SOCK_LOCALROUTE) ||
(msg->msg_flags & MSG_DONTROUTE) ||
(ipc.opt && ipc.opt->is_strictroute)) {
tos |= RTO_ONLINK;
connected = 0;
}
if (ipv4_is_multicast(daddr)) {
if (!ipc.oif)
ipc.oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
connected = 0;
}
if (connected)
rt = (struct rtable *)sk_dst_check(sk, 0);
if (rt == NULL) {
struct flowi4 fl4;
struct net *net = sock_net(sk);
flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos,
RT_SCOPE_UNIVERSE, sk->sk_protocol,
inet_sk_flowi_flags(sk)|FLOWI_FLAG_CAN_SLEEP,
faddr, saddr, dport, inet->inet_sport);
security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
rt = ip_route_output_flow(net, &fl4, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
if (err == -ENETUNREACH)
IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
goto out;
}
err = -EACCES;
if ((rt->rt_flags & RTCF_BROADCAST) &&
!sock_flag(sk, SOCK_BROADCAST))
goto out;
if (connected)
sk_dst_set(sk, dst_clone(&rt->dst));
}
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
saddr = rt->rt_src;
if (!ipc.addr)
daddr = ipc.addr = rt->rt_dst;
/* Lockless fast path for the non-corking case. */
if (!corkreq) {
skb = ip_make_skb(sk, getfrag, msg->msg_iov, ulen,
sizeof(struct udphdr), &ipc, &rt,
msg->msg_flags);
err = PTR_ERR(skb);
if (skb && !IS_ERR(skb))
err = udp_send_skb(skb, daddr, dport);
goto out;
}
lock_sock(sk);
if (unlikely(up->pending)) {
/* The socket is already corked while preparing it. */
/* ... which is an evident application bug. --ANK */
release_sock(sk);
LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n");
err = -EINVAL;
goto out;
}
/*
* Now cork the socket to pend data.
*/
fl4 = &inet->cork.fl.u.ip4;
fl4->daddr = daddr;
fl4->saddr = saddr;
fl4->fl4_dport = dport;
fl4->fl4_sport = inet->inet_sport;
up->pending = AF_INET;
do_append_data:
up->len += ulen;
err = ip_append_data(sk, getfrag, msg->msg_iov, ulen,
sizeof(struct udphdr), &ipc, &rt,
corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags);
if (err)
udp_flush_pending_frames(sk);
else if (!corkreq)
err = udp_push_pending_frames(sk);
else if (unlikely(skb_queue_empty(&sk->sk_write_queue)))
up->pending = 0;
release_sock(sk);
out:
ip_rt_put(rt);
if (free)
kfree(ipc.opt);
if (!err)
return len;
/*
* ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting
* ENOBUFS might not be good (it's not tunable per se), but otherwise
* we don't have a good statistic (IpOutDiscards but it can be too many
* things). We could add another new stat but at least for now that
* seems like overkill.
*/
if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_SNDBUFERRORS, is_udplite);
}
return err;
do_confirm:
dst_confirm(&rt->dst);
if (!(msg->msg_flags&MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto out;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
line += PKT_LEN_SIZE;
/*
* TODO: How do we deal with empty lines? Try again? with the next
* line?
*/
if (len == PKT_LEN_SIZE) {
*head = NULL;
*out = line;
return 0;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
Commit Message: smart_pkt: verify packet length exceeds PKT_LEN_SIZE
Each packet line in the Git protocol is prefixed by a four-byte
length of how much data will follow, which we parse in
`git_pkt_parse_line`. The transmitted length can either be equal
to zero in case of a flush packet or has to be at least of length
four, as it also includes the encoded length itself. Not
checking this may result in a buffer overflow as we directly pass
the length to functions which accept a `size_t` length as
parameter.
Fix the issue by verifying that non-flush packets have at least a
length of `PKT_LEN_SIZE`.
CWE ID: CWE-119
Target: 1
Example 2:
Code: static MagickBooleanType IsIPL(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"data",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
Commit Message: ...
CWE ID: CWE-284
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nfs4_setup_session_slot_tables(struct nfs4_session *ses)
{
struct nfs4_slot_table *tbl;
int status;
dprintk("--> %s\n", __func__);
/* Fore channel */
tbl = &ses->fc_slot_table;
status = nfs4_realloc_slot_table(tbl, ses->fc_attrs.max_reqs, 1);
if (status) /* -ENOMEM */
return status;
/* Back channel */
tbl = &ses->bc_slot_table;
status = nfs4_realloc_slot_table(tbl, ses->bc_attrs.max_reqs, 0);
if (status && tbl->slots == NULL)
/* Fore and back channel share a connection so get
* both slot tables or neither */
nfs4_destroy_slot_tables(ses);
return status;
}
Commit Message: Fix length of buffer copied in __nfs4_get_acl_uncached
_copy_from_pages() used to copy data from the temporary buffer to the
user passed buffer is passed the wrong size parameter when copying
data. res.acl_len contains both the bitmap and acl lenghts while
acl_len contains the acl length after adjusting for the bitmap size.
Signed-off-by: Sachin Prabhu <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */
{
/*
This is how the time string is formatted:
snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100,
ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec);
*/
time_t ret;
struct tm thetime;
char * strbuf;
char * thestr;
long gmadjust = 0;
if (timestr->length < 13) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "extension author too lazy to parse %s correctly", timestr->data);
return (time_t)-1;
}
strbuf = estrdup((char *)timestr->data);
memset(&thetime, 0, sizeof(thetime));
/* we work backwards so that we can use atoi more easily */
thestr = strbuf + timestr->length - 3;
thetime.tm_sec = atoi(thestr);
*thestr = '\0';
thetime.tm_mon = atoi(thestr)-1;
*thestr = '\0';
thestr -= 2;
thetime.tm_year = atoi(thestr);
if (thetime.tm_year < 68) {
thetime.tm_year += 100;
}
thetime.tm_isdst = -1;
ret = mktime(&thetime);
#if HAVE_TM_GMTOFF
gmadjust = thetime.tm_gmtoff;
#else
/*
** If correcting for daylight savings time, we set the adjustment to
** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and
** set the adjustment to the main timezone + 3600 seconds.
*/
gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600);
#endif
ret += gmadjust;
efree(strbuf);
return ret;
}
/* }}} */
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool HTMLCanvasElement::IsSupportedInteractiveCanvasFallback(
const Element& element) {
if (!element.IsDescendantOf(this))
return false;
if (IsHTMLAnchorElement(element))
return !Traversal<HTMLImageElement>::FirstWithin(element);
if (IsHTMLButtonElement(element))
return true;
if (auto* input_element = ToHTMLInputElementOrNull(element)) {
if (input_element->type() == input_type_names::kCheckbox ||
input_element->type() == input_type_names::kRadio ||
input_element->IsTextButton()) {
return true;
}
}
if (auto* select_element = ToHTMLSelectElementOrNull(element)) {
if (select_element->IsMultiple() || select_element->size() > 1)
return true;
}
if (IsHTMLOptionElement(element) && element.parentNode() &&
IsHTMLSelectElement(*element.parentNode())) {
const HTMLSelectElement& select_element =
ToHTMLSelectElement(*element.parentNode());
if (select_element.IsMultiple() || select_element.size() > 1)
return true;
}
if (element.FastHasAttribute(html_names::kTabindexAttr))
return true;
if (IsHTMLTableElement(element) ||
element.HasTagName(html_names::kCaptionTag) ||
element.HasTagName(html_names::kTheadTag) ||
element.HasTagName(html_names::kTbodyTag) ||
element.HasTagName(html_names::kTfootTag) ||
element.HasTagName(html_names::kTrTag) ||
element.HasTagName(html_names::kTdTag) ||
element.HasTagName(html_names::kThTag))
return true;
return false;
}
Commit Message: Clean up CanvasResourceDispatcher on finalizer
We may have pending mojo messages after GC, so we want to drop the
dispatcher as soon as possible.
Bug: 929757,913964
Change-Id: I5789bcbb55aada4a74c67a28758f07686f8911c0
Reviewed-on: https://chromium-review.googlesource.com/c/1489175
Reviewed-by: Ken Rockot <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Auto-Submit: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#635833}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_hash rhash;
snprintf(rhash.type, CRYPTO_MAX_ALG_NAME, "%s", "ahash");
rhash.blocksize = alg->cra_blocksize;
rhash.digestsize = __crypto_hash_alg_common(alg)->digestsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_HASH,
sizeof(struct crypto_report_hash), &rhash))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void audit_log_execve_info(struct audit_context *context,
struct audit_buffer **ab)
{
int i, len;
size_t len_sent = 0;
const char __user *p;
char *buf;
p = (const char __user *)current->mm->arg_start;
audit_log_format(*ab, "argc=%d", context->execve.argc);
/*
* we need some kernel buffer to hold the userspace args. Just
* allocate one big one rather than allocating one of the right size
* for every single argument inside audit_log_single_execve_arg()
* should be <8k allocation so should be pretty safe.
*/
buf = kmalloc(MAX_EXECVE_AUDIT_LEN + 1, GFP_KERNEL);
if (!buf) {
audit_panic("out of memory for argv string");
return;
}
for (i = 0; i < context->execve.argc; i++) {
len = audit_log_single_execve_arg(context, ab, i,
&len_sent, p, buf);
if (len <= 0)
break;
p += len;
}
kfree(buf);
}
Commit Message: audit: fix a double fetch in audit_log_single_execve_arg()
There is a double fetch problem in audit_log_single_execve_arg()
where we first check the execve(2) argumnets for any "bad" characters
which would require hex encoding and then re-fetch the arguments for
logging in the audit record[1]. Of course this leaves a window of
opportunity for an unsavory application to munge with the data.
This patch reworks things by only fetching the argument data once[2]
into a buffer where it is scanned and logged into the audit
records(s). In addition to fixing the double fetch, this patch
improves on the original code in a few other ways: better handling
of large arguments which require encoding, stricter record length
checking, and some performance improvements (completely unverified,
but we got rid of some strlen() calls, that's got to be a good
thing).
As part of the development of this patch, I've also created a basic
regression test for the audit-testsuite, the test can be tracked on
GitHub at the following link:
* https://github.com/linux-audit/audit-testsuite/issues/25
[1] If you pay careful attention, there is actually a triple fetch
problem due to a strnlen_user() call at the top of the function.
[2] This is a tiny white lie, we do make a call to strnlen_user()
prior to fetching the argument data. I don't like it, but due to the
way the audit record is structured we really have no choice unless we
copy the entire argument at once (which would require a rather
wasteful allocation). The good news is that with this patch the
kernel no longer relies on this strnlen_user() value for anything
beyond recording it in the log, we also update it with a trustworthy
value whenever possible.
Reported-by: Pengfei Wang <[email protected]>
Cc: <[email protected]>
Signed-off-by: Paul Moore <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: pdf14_clist_update_params(pdf14_clist_device * pdev, const gs_gstate * pgs,
bool crop_blend_params,
gs_pdf14trans_params_t *group_params)
{
gs_pdf14trans_params_t params = { 0 };
gx_device * pcdev;
int changed = 0;
int code = 0;
gs_composite_t *pct_new = NULL;
params.crop_blend_params = crop_blend_params;
params.pdf14_op = PDF14_SET_BLEND_PARAMS;
if (pgs->blend_mode != pdev->blend_mode) {
changed |= PDF14_SET_BLEND_MODE;
params.blend_mode = pdev->blend_mode = pgs->blend_mode;
}
if (pgs->text_knockout != pdev->text_knockout) {
changed |= PDF14_SET_TEXT_KNOCKOUT;
params.text_knockout = pdev->text_knockout = pgs->text_knockout;
}
if (pgs->shape.alpha != pdev->shape) {
changed |= PDF14_SET_SHAPE_ALPHA;
params.shape.alpha = pdev->shape = pgs->shape.alpha;
}
if (pgs->opacity.alpha != pdev->opacity) {
changed |= PDF14_SET_OPACITY_ALPHA;
params.opacity.alpha = pdev->opacity = pgs->opacity.alpha;
}
if (pgs->overprint != pdev->overprint) {
changed |= PDF14_SET_OVERPRINT;
params.overprint = pdev->overprint = pgs->overprint;
}
if (pgs->overprint_mode != pdev->overprint_mode) {
changed |= PDF14_SET_OVERPRINT_MODE;
params.overprint_mode = pdev->overprint_mode = pgs->overprint_mode;
}
if (crop_blend_params) {
params.ctm = group_params->ctm;
params.bbox = group_params->bbox;
}
params.changed = changed;
/* Avoid recursion when we have a PDF14_SET_BLEND_PARAMS forced and apply
now to the target. Otherwise we send of te compositor action
to the pdf14 device at this time. This is due to the fact that we
need to often perform this operation when we are already starting to
do a compositor action */
if (changed != 0) {
code = gs_create_pdf14trans(&pct_new, ¶ms, pgs->memory);
if (code < 0) return code;
code = dev_proc(pdev->target, create_compositor)
(pdev->target, &pcdev, pct_new, (gs_gstate *)pgs, pgs->memory, NULL);
gs_free_object(pgs->memory, pct_new, "pdf14_clist_update_params");
}
return code;
}
Commit Message:
CWE ID: CWE-476
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void jpc_cod_destroyparms(jpc_ms_t *ms)
{
jpc_cod_t *cod = &ms->parms.cod;
jpc_cox_destroycompparms(&cod->compparms);
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int override_release(char __user *release, int len)
{
int ret = 0;
char buf[65];
if (current->personality & UNAME26) {
char *rest = UTS_RELEASE;
int ndots = 0;
unsigned v;
while (*rest) {
if (*rest == '.' && ++ndots >= 3)
break;
if (!isdigit(*rest) && *rest != '.')
break;
rest++;
}
v = ((LINUX_VERSION_CODE >> 8) & 0xff) + 40;
snprintf(buf, len, "2.6.%u%s", v, rest);
ret = copy_to_user(release, buf, len);
}
return ret;
}
Commit Message: kernel/sys.c: fix stack memory content leak via UNAME26
Calling uname() with the UNAME26 personality set allows a leak of kernel
stack contents. This fixes it by defensively calculating the length of
copy_to_user() call, making the len argument unsigned, and initializing
the stack buffer to zero (now technically unneeded, but hey, overkill).
CVE-2012-0957
Reported-by: PaX Team <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Cc: Andi Kleen <[email protected]>
Cc: PaX Team <[email protected]>
Cc: Brad Spengler <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-16
Target: 1
Example 2:
Code: int DSA_set0_key(DSA *d, BIGNUM *pub_key, BIGNUM *priv_key)
{
d->pub_key = pub_key;
d->priv_key = priv_key;
return 1;
}
Commit Message:
CWE ID: CWE-754
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const Cluster* Segment::FindCluster(long long time_ns) const
{
if ((m_clusters == NULL) || (m_clusterCount <= 0))
return &m_eos;
{
Cluster* const pCluster = m_clusters[0];
assert(pCluster);
assert(pCluster->m_index == 0);
if (time_ns <= pCluster->GetTime())
return pCluster;
}
long i = 0;
long j = m_clusterCount;
while (i < j)
{
const long k = i + (j - i) / 2;
assert(k < m_clusterCount);
Cluster* const pCluster = m_clusters[k];
assert(pCluster);
assert(pCluster->m_index == k);
const long long t = pCluster->GetTime();
if (t <= time_ns)
i = k + 1;
else
j = k;
assert(i <= j);
}
assert(i == j);
assert(i > 0);
assert(i <= m_clusterCount);
const long k = i - 1;
Cluster* const pCluster = m_clusters[k];
assert(pCluster);
assert(pCluster->m_index == k);
assert(pCluster->GetTime() <= time_ns);
return pCluster;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) {
xmlChar start[4];
xmlCharEncoding enc;
if ((ctxt == NULL) || (ctxt->input == NULL))
return(-1);
xmlDefaultSAXHandlerInit();
xmlDetectSAX2(ctxt);
GROW;
/*
* SAX: beginning of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator);
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
if ((ctxt->input->end - ctxt->input->cur) >= 4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if (CUR == 0) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
}
/*
* Check for the XMLDecl in the Prolog.
*/
GROW;
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
/*
* Note that we will switch encoding on the fly.
*/
xmlParseXMLDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right here
*/
return(-1);
}
SKIP_BLANKS;
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
}
if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
/*
* Doing validity checking on chunk doesn't make sense
*/
ctxt->instate = XML_PARSER_CONTENT;
ctxt->validate = 0;
ctxt->loadsubset = 0;
ctxt->depth = 0;
xmlParseContent(ctxt);
if ((RAW == '<') && (NXT(1) == '/')) {
xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
} else if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_EXTRA_CONTENT, NULL);
}
/*
* SAX: end of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
if (! ctxt->wellFormed) return(-1);
return(0);
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void SVGCharacters(void *context,const xmlChar *c,int length)
{
char
*text;
register char
*p;
register ssize_t
i;
SVGInfo
*svg_info;
/*
Receiving some characters from the parser.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.characters(%s,%.20g)",c,(double) length);
svg_info=(SVGInfo *) context;
text=(char *) AcquireQuantumMemory(length+1,sizeof(*text));
if (text == (char *) NULL)
return;
p=text;
for (i=0; i < (ssize_t) length; i++)
*p++=c[i];
*p='\0';
StripString(text);
if (svg_info->text == (char *) NULL)
svg_info->text=text;
else
{
(void) ConcatenateString(&svg_info->text,text);
text=DestroyString(text);
}
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void blkcg_css_offline(struct cgroup_subsys_state *css)
{
struct blkcg *blkcg = css_to_blkcg(css);
spin_lock_irq(&blkcg->lock);
while (!hlist_empty(&blkcg->blkg_list)) {
struct blkcg_gq *blkg = hlist_entry(blkcg->blkg_list.first,
struct blkcg_gq, blkcg_node);
struct request_queue *q = blkg->q;
if (spin_trylock(q->queue_lock)) {
blkg_destroy(blkg);
spin_unlock(q->queue_lock);
} else {
spin_unlock_irq(&blkcg->lock);
cpu_relax();
spin_lock_irq(&blkcg->lock);
}
}
spin_unlock_irq(&blkcg->lock);
wb_blkcg_offline(blkcg);
}
Commit Message: blkcg: fix double free of new_blkg in blkcg_init_queue
If blkg_create fails, new_blkg passed as an argument will
be freed by blkg_create, so there is no need to free it again.
Signed-off-by: Hou Tao <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-415
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static uint32_t scsi_init_iovec(SCSIDiskReq *r)
{
r->iov.iov_len = MIN(r->sector_count * 512, SCSI_DMA_BUF_SIZE);
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
return r->qiov.size / 512;
}
Commit Message: scsi-disk: lazily allocate bounce buffer
It will not be needed for reads and writes if the HBA provides a sglist.
In addition, this lets scsi-disk refuse commands with an excessive
allocation length, as well as limit memory on usual well-behaved guests.
Signed-off-by: Paolo Bonzini <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int perf_event_task_match(struct perf_event *event)
{
return event->attr.comm || event->attr.mmap ||
event->attr.mmap2 || event->attr.mmap_data ||
event->attr.task;
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int pegasus_close(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
netif_stop_queue(net);
if (!(pegasus->flags & PEGASUS_UNPLUG))
disable_net_traffic(pegasus);
tasklet_kill(&pegasus->rx_tl);
unlink_all_urbs(pegasus);
return 0;
}
Commit Message: pegasus: Use heap buffers for all register access
Allocating USB buffers on the stack is not portable, and no longer
works on x86_64 (with VMAP_STACK enabled as per default).
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
References: https://bugs.debian.org/852556
Reported-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]>
Tested-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]>
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int main(int argc, char **argv) {
const char *test_name = NULL;
bool skip_sanity_suite = false;
for (int i = 1; i < argc; ++i) {
if (!strcmp("--help", argv[i])) {
print_usage(argv[0]);
return 0;
}
if (!strcmp("--insanity", argv[i])) {
skip_sanity_suite = true;
continue;
}
if (!is_valid(argv[i])) {
printf("Error: invalid test name.\n");
print_usage(argv[0]);
return -1;
}
if (test_name != NULL) {
printf("Error: invalid arguments.\n");
print_usage(argv[0]);
return -1;
}
test_name = argv[i];
}
if (is_shell_running()) {
printf("Run 'adb shell stop' before running %s.\n", argv[0]);
return -1;
}
config_t *config = config_new(CONFIG_FILE_PATH);
if (!config) {
printf("Error: unable to open stack config file.\n");
print_usage(argv[0]);
return -1;
}
for (const config_section_node_t *node = config_section_begin(config); node != config_section_end(config); node = config_section_next(node)) {
const char *name = config_section_name(node);
if (config_has_key(config, name, "LinkKey") && string_to_bdaddr(name, &bt_remote_bdaddr)) {
break;
}
}
config_free(config);
if (bdaddr_is_empty(&bt_remote_bdaddr)) {
printf("Error: unable to find paired device in config file.\n");
print_usage(argv[0]);
return -1;
}
if (!hal_open(callbacks_get_adapter_struct())) {
printf("Unable to open Bluetooth HAL.\n");
return 1;
}
if (!btsocket_init()) {
printf("Unable to initialize Bluetooth sockets.\n");
return 2;
}
if (!pan_init()) {
printf("Unable to initialize PAN.\n");
return 3;
}
if (!gatt_init()) {
printf("Unable to initialize GATT.\n");
return 4;
}
watchdog_running = true;
pthread_create(&watchdog_thread, NULL, watchdog_fn, NULL);
static const char *DEFAULT = "\x1b[0m";
static const char *GREEN = "\x1b[0;32m";
static const char *RED = "\x1b[0;31m";
if (!isatty(fileno(stdout))) {
DEFAULT = GREEN = RED = "";
}
int pass = 0;
int fail = 0;
int case_num = 0;
if (!skip_sanity_suite) {
for (size_t i = 0; i < sanity_suite_size; ++i) {
if (!test_name || !strcmp(test_name, sanity_suite[i].function_name)) {
callbacks_init();
if (sanity_suite[i].function()) {
printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, sanity_suite[i].function_name, GREEN, DEFAULT);
++pass;
} else {
printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, sanity_suite[i].function_name, RED, DEFAULT);
++fail;
}
callbacks_cleanup();
++watchdog_id;
}
}
}
if (fail) {
printf("\n%sSanity suite failed with %d errors.%s\n", RED, fail, DEFAULT);
hal_close();
return 4;
}
for (size_t i = 0; i < test_suite_size; ++i) {
if (!test_name || !strcmp(test_name, test_suite[i].function_name)) {
callbacks_init();
CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed);
if (test_suite[i].function()) {
printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, test_suite[i].function_name, GREEN, DEFAULT);
++pass;
} else {
printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, test_suite[i].function_name, RED, DEFAULT);
++fail;
}
CALL_AND_WAIT(bt_interface->disable(), adapter_state_changed);
callbacks_cleanup();
++watchdog_id;
}
}
printf("\n");
if (fail) {
printf("%d/%d tests failed. See above for failed test cases.\n", fail, sanity_suite_size + test_suite_size);
} else {
printf("All tests passed!\n");
}
watchdog_running = false;
pthread_join(watchdog_thread, NULL);
hal_close();
return 0;
}
Commit Message: Add guest mode functionality (2/3)
Add a flag to enable() to start Bluetooth in restricted
mode. In restricted mode, all devices that are paired during
restricted mode are deleted upon leaving restricted mode.
Right now restricted mode is only entered while a guest
user is active.
Bug: 27410683
Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19
CWE ID: CWE-20
Target: 1
Example 2:
Code: static bool is_orphaned_event(struct perf_event *event)
{
return event->state == PERF_EVENT_STATE_DEAD;
}
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 <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Alexander Shishkin <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Min Chong <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Stephane Eranian <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Vince Weaver <[email protected]>
Fixes: f63a8daa5812 ("perf: Fix event->ctx locking")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual void ResetModel() {
last_pts_ = 0;
bits_in_buffer_model_ = cfg_.rc_target_bitrate * cfg_.rc_buf_initial_sz;
frame_number_ = 0;
first_drop_ = 0;
bits_total_ = 0;
duration_ = 0.0;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SpeechRecognitionManagerImpl::RecognitionAllowedCallback(int session_id,
bool ask_user,
bool is_allowed) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
auto iter = sessions_.find(session_id);
if (iter == sessions_.end())
return;
Session* session = iter->second.get();
if (session->abort_requested)
return;
if (ask_user) {
SpeechRecognitionSessionContext& context = session->context;
context.label = media_stream_manager_->MakeMediaAccessRequest(
context.render_process_id, context.render_frame_id, session_id,
StreamControls(true, false), context.security_origin,
base::BindOnce(
&SpeechRecognitionManagerImpl::MediaRequestPermissionCallback,
weak_factory_.GetWeakPtr(), session_id));
return;
}
if (is_allowed) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&SpeechRecognitionManagerImpl::DispatchEvent,
weak_factory_.GetWeakPtr(), session_id, EVENT_START));
} else {
OnRecognitionError(
session_id, blink::mojom::SpeechRecognitionError(
blink::mojom::SpeechRecognitionErrorCode::kNotAllowed,
blink::mojom::SpeechAudioErrorDetails::kNone));
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&SpeechRecognitionManagerImpl::DispatchEvent,
weak_factory_.GetWeakPtr(), session_id, EVENT_ABORT));
}
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void rtnl_set_sk_err(struct net *net, u32 group, int error)
{
struct sock *rtnl = net->rtnl;
netlink_set_err(rtnl, 0, group, error);
}
Commit Message: rtnl: fix info leak on RTM_GETLINK request for VF devices
Initialize the mac address buffer with 0 as the driver specific function
will probably not fill the whole buffer. In fact, all in-kernel drivers
fill only ETH_ALEN of the MAX_ADDR_LEN bytes, i.e. 6 of the 32 possible
bytes. Therefore we currently leak 26 bytes of stack memory to userland
via the netlink interface.
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void perf_output_end(struct perf_output_handle *handle)
{
struct perf_event *event = handle->event;
struct ring_buffer *rb = handle->rb;
if (handle->sample && !event->attr.watermark) {
int wakeup_events = event->attr.wakeup_events;
if (wakeup_events) {
int events = local_inc_return(&rb->events);
if (events >= wakeup_events) {
local_sub(wakeup_events, &rb->events);
local_inc(&rb->wakeup);
}
}
}
perf_output_put_handle(handle);
rcu_read_unlock();
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: DXVAVideoDecodeAccelerator::DXVAVideoDecodeAccelerator(
media::VideoDecodeAccelerator::Client* client,
base::ProcessHandle renderer_process)
: client_(client),
egl_config_(NULL),
state_(kUninitialized),
pictures_requested_(false),
renderer_process_(renderer_process),
last_input_buffer_id_(-1),
inputs_before_decode_(0) {
memset(&input_stream_info_, 0, sizeof(input_stream_info_));
memset(&output_stream_info_, 0, sizeof(output_stream_info_));
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: void ResourceDispatcherHostImpl::CancelRequestsForRoute(int child_id,
int route_id) {
std::vector<GlobalRequestID> matching_requests;
for (LoaderMap::const_iterator i = pending_loaders_.begin();
i != pending_loaders_.end(); ++i) {
if (i->first.child_id != child_id)
continue;
ResourceRequestInfoImpl* info = i->second->GetRequestInfo();
GlobalRequestID id(child_id, i->first.request_id);
DCHECK(id == i->first);
if (!info->is_download() && !IsTransferredNavigation(id) &&
(route_id == -1 || route_id == info->GetRouteID())) {
matching_requests.push_back(id);
}
}
for (size_t i = 0; i < matching_requests.size(); ++i) {
LoaderMap::iterator iter = pending_loaders_.find(matching_requests[i]);
if (iter != pending_loaders_.end())
RemovePendingLoader(iter);
}
if (route_id != -1) {
if (blocked_loaders_map_.find(ProcessRouteIDs(child_id, route_id)) !=
blocked_loaders_map_.end()) {
CancelBlockedRequestsForRoute(child_id, route_id);
}
} else {
std::set<int> route_ids;
for (BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.begin();
iter != blocked_loaders_map_.end(); ++iter) {
if (iter->first.first == child_id)
route_ids.insert(iter->first.second);
}
for (std::set<int>::const_iterator iter = route_ids.begin();
iter != route_ids.end(); ++iter) {
CancelBlockedRequestsForRoute(child_id, *iter);
}
}
}
Commit Message: Make chrome.appWindow.create() provide access to the child window at a predictable time.
When you first create a window with chrome.appWindow.create(), it won't have
loaded any resources. So, at create time, you are guaranteed that:
child_window.location.href == 'about:blank'
child_window.document.documentElement.outerHTML ==
'<html><head></head><body></body></html>'
This is in line with the behaviour of window.open().
BUG=131735
TEST=browser_tests:PlatformAppBrowserTest.WindowsApi
Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=144072
Review URL: https://chromiumcodereview.appspot.com/10644006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@144356 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void cmdloop(void)
{
int c;
int usinguid, havepartition, havenamespace, recursive;
static struct buf tag, cmd, arg1, arg2, arg3;
char *p, shut[MAX_MAILBOX_PATH+1], cmdname[100];
const char *err;
const char * commandmintimer;
double commandmintimerd = 0.0;
struct sync_reserve_list *reserve_list =
sync_reserve_list_create(SYNC_MESSAGE_LIST_HASH_SIZE);
struct applepushserviceargs applepushserviceargs;
prot_printf(imapd_out, "* OK [CAPABILITY ");
capa_response(CAPA_PREAUTH);
prot_printf(imapd_out, "]");
if (config_serverinfo) prot_printf(imapd_out, " %s", config_servername);
if (config_serverinfo == IMAP_ENUM_SERVERINFO_ON) {
prot_printf(imapd_out, " Cyrus IMAP %s", cyrus_version());
}
prot_printf(imapd_out, " server ready\r\n");
/* clear cancelled flag if present before the next command */
cmd_cancelled();
motd_file();
/* Get command timer logging paramater. This string
* is a time in seconds. Any command that takes >=
* this time to execute is logged */
commandmintimer = config_getstring(IMAPOPT_COMMANDMINTIMER);
cmdtime_settimer(commandmintimer ? 1 : 0);
if (commandmintimer) {
commandmintimerd = atof(commandmintimer);
}
for (;;) {
/* Release any held index */
index_release(imapd_index);
/* Flush any buffered output */
prot_flush(imapd_out);
if (backend_current) prot_flush(backend_current->out);
/* command no longer running */
proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), NULL);
/* Check for shutdown file */
if ( !imapd_userisadmin && imapd_userid &&
(shutdown_file(shut, sizeof(shut)) ||
userdeny(imapd_userid, config_ident, shut, sizeof(shut)))) {
for (p = shut; *p == '['; p++); /* can't have [ be first char */
prot_printf(imapd_out, "* BYE [ALERT] %s\r\n", p);
telemetry_rusage(imapd_userid);
shut_down(0);
}
signals_poll();
if (!proxy_check_input(protin, imapd_in, imapd_out,
backend_current ? backend_current->in : NULL,
NULL, 0)) {
/* No input from client */
continue;
}
/* Parse tag */
c = getword(imapd_in, &tag);
if (c == EOF) {
if ((err = prot_error(imapd_in))!=NULL
&& strcmp(err, PROT_EOF_STRING)) {
syslog(LOG_WARNING, "%s, closing connection", err);
prot_printf(imapd_out, "* BYE %s\r\n", err);
}
goto done;
}
if (c != ' ' || !imparse_isatom(tag.s) || (tag.s[0] == '*' && !tag.s[1])) {
prot_printf(imapd_out, "* BAD Invalid tag\r\n");
eatline(imapd_in, c);
continue;
}
/* Parse command name */
c = getword(imapd_in, &cmd);
if (!cmd.s[0]) {
prot_printf(imapd_out, "%s BAD Null command\r\n", tag.s);
eatline(imapd_in, c);
continue;
}
lcase(cmd.s);
xstrncpy(cmdname, cmd.s, 99);
cmd.s[0] = toupper((unsigned char) cmd.s[0]);
if (config_getswitch(IMAPOPT_CHATTY))
syslog(LOG_NOTICE, "command: %s %s", tag.s, cmd.s);
proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), cmd.s);
/* if we need to force a kick, do so */
if (referral_kick) {
kick_mupdate();
referral_kick = 0;
}
if (plaintextloginalert) {
prot_printf(imapd_out, "* OK [ALERT] %s\r\n",
plaintextloginalert);
plaintextloginalert = NULL;
}
/* Only Authenticate/Enable/Login/Logout/Noop/Capability/Id/Starttls
allowed when not logged in */
if (!imapd_userid && !strchr("AELNCIS", cmd.s[0])) goto nologin;
/* Start command timer */
cmdtime_starttimer();
/* note that about half the commands (the common ones that don't
hit the mailboxes file) now close the mailboxes file just in
case it was open. */
switch (cmd.s[0]) {
case 'A':
if (!strcmp(cmd.s, "Authenticate")) {
int haveinitresp = 0;
if (c != ' ') goto missingargs;
c = getword(imapd_in, &arg1);
if (!imparse_isatom(arg1.s)) {
prot_printf(imapd_out, "%s BAD Invalid authenticate mechanism\r\n", tag.s);
eatline(imapd_in, c);
continue;
}
if (c == ' ') {
haveinitresp = 1;
c = getword(imapd_in, &arg2);
if (c == EOF) goto missingargs;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
if (imapd_userid) {
prot_printf(imapd_out, "%s BAD Already authenticated\r\n", tag.s);
continue;
}
cmd_authenticate(tag.s, arg1.s, haveinitresp ? arg2.s : NULL);
snmp_increment(AUTHENTICATE_COUNT, 1);
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Append")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_append(tag.s, arg1.s, NULL);
snmp_increment(APPEND_COUNT, 1);
}
else goto badcmd;
break;
case 'C':
if (!strcmp(cmd.s, "Capability")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_capability(tag.s);
snmp_increment(CAPABILITY_COUNT, 1);
}
else if (!imapd_userid) goto nologin;
#ifdef HAVE_ZLIB
else if (!strcmp(cmd.s, "Compress")) {
if (c != ' ') goto missingargs;
c = getword(imapd_in, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_compress(tag.s, arg1.s);
snmp_increment(COMPRESS_COUNT, 1);
}
#endif /* HAVE_ZLIB */
else if (!strcmp(cmd.s, "Check")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_noop(tag.s, cmd.s);
snmp_increment(CHECK_COUNT, 1);
}
else if (!strcmp(cmd.s, "Copy")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
copy:
c = getword(imapd_in, &arg1);
if (c == '\r') goto missingargs;
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/0);
snmp_increment(COPY_COUNT, 1);
}
else if (!strcmp(cmd.s, "Create")) {
struct dlist *extargs = NULL;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == ' ') {
c = parsecreateargs(&extargs);
if (c == EOF) goto badpartition;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_create(tag.s, arg1.s, extargs, 0);
dlist_free(&extargs);
snmp_increment(CREATE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Close")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_close(tag.s, cmd.s);
snmp_increment(CLOSE_COUNT, 1);
}
else goto badcmd;
break;
case 'D':
if (!strcmp(cmd.s, "Delete")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_delete(tag.s, arg1.s, 0, 0);
snmp_increment(DELETE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Deleteacl")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_setacl(tag.s, arg1.s, arg2.s, NULL);
snmp_increment(DELETEACL_COUNT, 1);
}
else if (!strcmp(cmd.s, "Dump")) {
int uid_start = 0;
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c == ' ') {
c = getastring(imapd_in, imapd_out, &arg2);
if(!imparse_isnumber(arg2.s)) goto extraargs;
uid_start = atoi(arg2.s);
}
if(c == '\r') c = prot_getc(imapd_in);
if(c != '\n') goto extraargs;
cmd_dump(tag.s, arg1.s, uid_start);
/* snmp_increment(DUMP_COUNT, 1);*/
}
else goto badcmd;
break;
case 'E':
if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Enable")) {
if (c != ' ') goto missingargs;
cmd_enable(tag.s);
}
else if (!strcmp(cmd.s, "Expunge")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_expunge(tag.s, 0);
snmp_increment(EXPUNGE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Examine")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
prot_ungetc(c, imapd_in);
cmd_select(tag.s, cmd.s, arg1.s);
snmp_increment(EXAMINE_COUNT, 1);
}
else goto badcmd;
break;
case 'F':
if (!strcmp(cmd.s, "Fetch")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
fetch:
c = getword(imapd_in, &arg1);
if (c == '\r') goto missingargs;
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
cmd_fetch(tag.s, arg1.s, usinguid);
snmp_increment(FETCH_COUNT, 1);
}
else goto badcmd;
break;
case 'G':
if (!strcmp(cmd.s, "Getacl")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_getacl(tag.s, arg1.s);
snmp_increment(GETACL_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getannotation")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_getannotation(tag.s, arg1.s);
snmp_increment(GETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getmetadata")) {
if (c != ' ') goto missingargs;
cmd_getmetadata(tag.s);
snmp_increment(GETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getquota")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_getquota(tag.s, arg1.s);
snmp_increment(GETQUOTA_COUNT, 1);
}
else if (!strcmp(cmd.s, "Getquotaroot")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_getquotaroot(tag.s, arg1.s);
snmp_increment(GETQUOTAROOT_COUNT, 1);
}
#ifdef HAVE_SSL
else if (!strcmp(cmd.s, "Genurlauth")) {
if (c != ' ') goto missingargs;
cmd_genurlauth(tag.s);
/* snmp_increment(GENURLAUTH_COUNT, 1);*/
}
#endif
else goto badcmd;
break;
case 'I':
if (!strcmp(cmd.s, "Id")) {
if (c != ' ') goto missingargs;
cmd_id(tag.s);
snmp_increment(ID_COUNT, 1);
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Idle") && idle_enabled()) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_idle(tag.s);
snmp_increment(IDLE_COUNT, 1);
}
else goto badcmd;
break;
case 'L':
if (!strcmp(cmd.s, "Login")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c != ' ') goto missingargs;
cmd_login(tag.s, arg1.s);
snmp_increment(LOGIN_COUNT, 1);
}
else if (!strcmp(cmd.s, "Logout")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
snmp_increment(LOGOUT_COUNT, 1);
/* force any responses from our selected backend */
if (backend_current) imapd_check(NULL, 0);
prot_printf(imapd_out, "* BYE %s\r\n",
error_message(IMAP_BYE_LOGOUT));
prot_printf(imapd_out, "%s OK %s\r\n", tag.s,
error_message(IMAP_OK_COMPLETED));
if (imapd_userid && *imapd_userid) {
telemetry_rusage(imapd_userid);
}
goto done;
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "List")) {
struct listargs listargs;
if (c != ' ') goto missingargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.ret = LIST_RET_CHILDREN;
getlistargs(tag.s, &listargs);
if (listargs.pat.count) cmd_list(tag.s, &listargs);
snmp_increment(LIST_COUNT, 1);
}
else if (!strcmp(cmd.s, "Lsub")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.cmd = LIST_CMD_LSUB;
listargs.sel = LIST_SEL_SUBSCRIBED;
if (!strcasecmpsafe(imapd_magicplus, "+dav"))
listargs.sel |= LIST_SEL_DAV;
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
cmd_list(tag.s, &listargs);
snmp_increment(LSUB_COUNT, 1);
}
else if (!strcmp(cmd.s, "Listrights")) {
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_listrights(tag.s, arg1.s, arg2.s);
snmp_increment(LISTRIGHTS_COUNT, 1);
}
else if (!strcmp(cmd.s, "Localappend")) {
/* create a local-only mailbox */
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c != ' ') goto missingargs;
cmd_append(tag.s, arg1.s, *arg2.s ? arg2.s : NULL);
snmp_increment(APPEND_COUNT, 1);
}
else if (!strcmp(cmd.s, "Localcreate")) {
/* create a local-only mailbox */
struct dlist *extargs = NULL;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == ' ') {
c = parsecreateargs(&extargs);
if (c == EOF) goto badpartition;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_create(tag.s, arg1.s, extargs, 1);
dlist_free(&extargs);
/* xxxx snmp_increment(CREATE_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Localdelete")) {
/* delete a mailbox locally only */
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_delete(tag.s, arg1.s, 1, 1);
/* xxxx snmp_increment(DELETE_COUNT, 1); */
}
else goto badcmd;
break;
case 'M':
if (!strcmp(cmd.s, "Myrights")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_myrights(tag.s, arg1.s);
/* xxxx snmp_increment(MYRIGHTS_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Mupdatepush")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c == EOF) goto missingargs;
if(c == '\r') c = prot_getc(imapd_in);
if(c != '\n') goto extraargs;
cmd_mupdatepush(tag.s, arg1.s);
/* xxxx snmp_increment(MUPDATEPUSH_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Move")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
move:
c = getword(imapd_in, &arg1);
if (c == '\r') goto missingargs;
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/1);
snmp_increment(COPY_COUNT, 1);
} else goto badcmd;
break;
case 'N':
if (!strcmp(cmd.s, "Noop")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_noop(tag.s, cmd.s);
/* xxxx snmp_increment(NOOP_COUNT, 1); */
}
else if (!imapd_userid) goto nologin;
else if (!strcmp(cmd.s, "Namespace")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_namespace(tag.s);
/* xxxx snmp_increment(NAMESPACE_COUNT, 1); */
}
else goto badcmd;
break;
case 'R':
if (!strcmp(cmd.s, "Rename")) {
havepartition = 0;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) goto missingargs;
if (c == ' ') {
havepartition = 1;
c = getword(imapd_in, &arg3);
if (!imparse_isatom(arg3.s)) goto badpartition;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_rename(tag.s, arg1.s, arg2.s, havepartition ? arg3.s : 0);
/* xxxx snmp_increment(RENAME_COUNT, 1); */
} else if(!strcmp(cmd.s, "Reconstruct")) {
recursive = 0;
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if(c == ' ') {
/* Optional RECURSEIVE argument */
c = getword(imapd_in, &arg2);
if(!imparse_isatom(arg2.s))
goto extraargs;
else if(!strcasecmp(arg2.s, "RECURSIVE"))
recursive = 1;
else
goto extraargs;
}
if(c == '\r') c = prot_getc(imapd_in);
if(c != '\n') goto extraargs;
cmd_reconstruct(tag.s, arg1.s, recursive);
/* snmp_increment(RECONSTRUCT_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Rlist")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.sel = LIST_SEL_REMOTE;
listargs.ret = LIST_RET_CHILDREN;
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
cmd_list(tag.s, &listargs);
/* snmp_increment(LIST_COUNT, 1); */
}
else if (!strcmp(cmd.s, "Rlsub")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.cmd = LIST_CMD_LSUB;
listargs.sel = LIST_SEL_REMOTE | LIST_SEL_SUBSCRIBED;
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
cmd_list(tag.s, &listargs);
/* snmp_increment(LSUB_COUNT, 1); */
}
#ifdef HAVE_SSL
else if (!strcmp(cmd.s, "Resetkey")) {
int have_mbox = 0, have_mech = 0;
if (c == ' ') {
have_mbox = 1;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == ' ') {
have_mech = 1;
c = getword(imapd_in, &arg2);
}
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_resetkey(tag.s, have_mbox ? arg1.s : 0,
have_mech ? arg2.s : 0);
/* snmp_increment(RESETKEY_COUNT, 1);*/
}
#endif
else goto badcmd;
break;
case 'S':
if (!strcmp(cmd.s, "Starttls")) {
if (!tls_enabled()) {
/* we don't support starttls */
goto badcmd;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
/* XXX discard any input pipelined after STARTTLS */
prot_flush(imapd_in);
/* if we've already done SASL fail */
if (imapd_userid != NULL) {
prot_printf(imapd_out,
"%s BAD Can't Starttls after authentication\r\n", tag.s);
continue;
}
/* if we've already done COMPRESS fail */
if (imapd_compress_done == 1) {
prot_printf(imapd_out,
"%s BAD Can't Starttls after Compress\r\n", tag.s);
continue;
}
/* check if already did a successful tls */
if (imapd_starttls_done == 1) {
prot_printf(imapd_out,
"%s BAD Already did a successful Starttls\r\n",
tag.s);
continue;
}
cmd_starttls(tag.s, 0);
snmp_increment(STARTTLS_COUNT, 1);
continue;
}
if (!imapd_userid) {
goto nologin;
} else if (!strcmp(cmd.s, "Store")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
store:
c = getword(imapd_in, &arg1);
if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence;
cmd_store(tag.s, arg1.s, usinguid);
snmp_increment(STORE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Select")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
prot_ungetc(c, imapd_in);
cmd_select(tag.s, cmd.s, arg1.s);
snmp_increment(SELECT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Search")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
search:
cmd_search(tag.s, usinguid);
snmp_increment(SEARCH_COUNT, 1);
}
else if (!strcmp(cmd.s, "Subscribe")) {
if (c != ' ') goto missingargs;
havenamespace = 0;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == ' ') {
havenamespace = 1;
c = getastring(imapd_in, imapd_out, &arg2);
}
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
if (havenamespace) {
cmd_changesub(tag.s, arg1.s, arg2.s, 1);
}
else {
cmd_changesub(tag.s, (char *)0, arg1.s, 1);
}
snmp_increment(SUBSCRIBE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setacl")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg3);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_setacl(tag.s, arg1.s, arg2.s, arg3.s);
snmp_increment(SETACL_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setannotation")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_setannotation(tag.s, arg1.s);
snmp_increment(SETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setmetadata")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_setmetadata(tag.s, arg1.s);
snmp_increment(SETANNOTATION_COUNT, 1);
}
else if (!strcmp(cmd.s, "Setquota")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_setquota(tag.s, arg1.s);
snmp_increment(SETQUOTA_COUNT, 1);
}
else if (!strcmp(cmd.s, "Sort")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
sort:
cmd_sort(tag.s, usinguid);
snmp_increment(SORT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Status")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
cmd_status(tag.s, arg1.s);
snmp_increment(STATUS_COUNT, 1);
}
else if (!strcmp(cmd.s, "Scan")) {
struct listargs listargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg3);
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.ref = arg1.s;
strarray_append(&listargs.pat, arg2.s);
listargs.scan = arg3.s;
cmd_list(tag.s, &listargs);
snmp_increment(SCAN_COUNT, 1);
}
else if (!strcmp(cmd.s, "Syncapply")) {
struct dlist *kl = sync_parseline(imapd_in);
if (kl) {
cmd_syncapply(tag.s, kl, reserve_list);
dlist_free(&kl);
}
else goto extraargs;
}
else if (!strcmp(cmd.s, "Syncget")) {
struct dlist *kl = sync_parseline(imapd_in);
if (kl) {
cmd_syncget(tag.s, kl);
dlist_free(&kl);
}
else goto extraargs;
}
else if (!strcmp(cmd.s, "Syncrestart")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
/* just clear the GUID cache */
cmd_syncrestart(tag.s, &reserve_list, 1);
}
else if (!strcmp(cmd.s, "Syncrestore")) {
struct dlist *kl = sync_parseline(imapd_in);
if (kl) {
cmd_syncrestore(tag.s, kl, reserve_list);
dlist_free(&kl);
}
else goto extraargs;
}
else goto badcmd;
break;
case 'T':
if (!strcmp(cmd.s, "Thread")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
thread:
cmd_thread(tag.s, usinguid);
snmp_increment(THREAD_COUNT, 1);
}
else goto badcmd;
break;
case 'U':
if (!strcmp(cmd.s, "Uid")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 1;
if (c != ' ') goto missingargs;
c = getword(imapd_in, &arg1);
if (c != ' ') goto missingargs;
lcase(arg1.s);
xstrncpy(cmdname, arg1.s, 99);
if (!strcmp(arg1.s, "fetch")) {
goto fetch;
}
else if (!strcmp(arg1.s, "store")) {
goto store;
}
else if (!strcmp(arg1.s, "search")) {
goto search;
}
else if (!strcmp(arg1.s, "sort")) {
goto sort;
}
else if (!strcmp(arg1.s, "thread")) {
goto thread;
}
else if (!strcmp(arg1.s, "copy")) {
goto copy;
}
else if (!strcmp(arg1.s, "move")) {
goto move;
}
else if (!strcmp(arg1.s, "xmove")) {
goto move;
}
else if (!strcmp(arg1.s, "expunge")) {
c = getword(imapd_in, &arg1);
if (!imparse_issequence(arg1.s)) goto badsequence;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_expunge(tag.s, arg1.s);
snmp_increment(EXPUNGE_COUNT, 1);
}
else if (!strcmp(arg1.s, "xrunannotator")) {
goto xrunannotator;
}
else {
prot_printf(imapd_out, "%s BAD Unrecognized UID subcommand\r\n", tag.s);
eatline(imapd_in, c);
}
}
else if (!strcmp(cmd.s, "Unsubscribe")) {
if (c != ' ') goto missingargs;
havenamespace = 0;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == ' ') {
havenamespace = 1;
c = getastring(imapd_in, imapd_out, &arg2);
}
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
if (havenamespace) {
cmd_changesub(tag.s, arg1.s, arg2.s, 0);
}
else {
cmd_changesub(tag.s, (char *)0, arg1.s, 0);
}
snmp_increment(UNSUBSCRIBE_COUNT, 1);
}
else if (!strcmp(cmd.s, "Unselect")) {
if (!imapd_index && !backend_current) goto nomailbox;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_close(tag.s, cmd.s);
snmp_increment(UNSELECT_COUNT, 1);
}
else if (!strcmp(cmd.s, "Undump")) {
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
/* we want to get a list at this point */
if(c != ' ') goto missingargs;
cmd_undump(tag.s, arg1.s);
/* snmp_increment(UNDUMP_COUNT, 1);*/
}
#ifdef HAVE_SSL
else if (!strcmp(cmd.s, "Urlfetch")) {
if (c != ' ') goto missingargs;
cmd_urlfetch(tag.s);
/* snmp_increment(URLFETCH_COUNT, 1);*/
}
#endif
else goto badcmd;
break;
case 'X':
if (!strcmp(cmd.s, "Xbackup")) {
int havechannel = 0;
if (!config_getswitch(IMAPOPT_XBACKUP_ENABLED))
goto badcmd;
/* user */
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
/* channel */
if (c == ' ') {
havechannel = 1;
c = getword(imapd_in, &arg2);
if (c == EOF) goto missingargs;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xbackup(tag.s, arg1.s, havechannel ? arg2.s : NULL);
}
else if (!strcmp(cmd.s, "Xconvfetch")) {
cmd_xconvfetch(tag.s);
}
else if (!strcmp(cmd.s, "Xconvmultisort")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xconvmultisort(tag.s);
}
else if (!strcmp(cmd.s, "Xconvsort")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xconvsort(tag.s, 0);
}
else if (!strcmp(cmd.s, "Xconvupdates")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xconvsort(tag.s, 1);
}
else if (!strcmp(cmd.s, "Xfer")) {
int havepartition = 0;
/* Mailbox */
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
/* Dest Server */
if(c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg2);
if(c == ' ') {
/* Dest Partition */
c = getastring(imapd_in, imapd_out, &arg3);
if (!imparse_isatom(arg3.s)) goto badpartition;
havepartition = 1;
}
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xfer(tag.s, arg1.s, arg2.s,
(havepartition ? arg3.s : NULL));
/* snmp_increment(XFER_COUNT, 1);*/
}
else if (!strcmp(cmd.s, "Xconvmeta")) {
cmd_xconvmeta(tag.s);
}
else if (!strcmp(cmd.s, "Xlist")) {
struct listargs listargs;
if (c != ' ') goto missingargs;
memset(&listargs, 0, sizeof(struct listargs));
listargs.cmd = LIST_CMD_XLIST;
listargs.ret = LIST_RET_CHILDREN | LIST_RET_SPECIALUSE;
getlistargs(tag.s, &listargs);
if (listargs.pat.count) cmd_list(tag.s, &listargs);
snmp_increment(LIST_COUNT, 1);
}
else if (!strcmp(cmd.s, "Xmove")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
goto move;
}
else if (!strcmp(cmd.s, "Xrunannotator")) {
if (!imapd_index && !backend_current) goto nomailbox;
usinguid = 0;
if (c != ' ') goto missingargs;
xrunannotator:
c = getword(imapd_in, &arg1);
if (!arg1.len || !imparse_issequence(arg1.s)) goto badsequence;
cmd_xrunannotator(tag.s, arg1.s, usinguid);
}
else if (!strcmp(cmd.s, "Xsnippets")) {
if (c != ' ') goto missingargs;
if (!imapd_index && !backend_current) goto nomailbox;
cmd_xsnippets(tag.s);
}
else if (!strcmp(cmd.s, "Xstats")) {
cmd_xstats(tag.s, c);
}
else if (!strcmp(cmd.s, "Xwarmup")) {
/* XWARMUP doesn't need a mailbox to be selected */
if (c != ' ') goto missingargs;
cmd_xwarmup(tag.s);
}
else if (!strcmp(cmd.s, "Xkillmy")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xkillmy(tag.s, arg1.s);
}
else if (!strcmp(cmd.s, "Xforever")) {
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xforever(tag.s);
}
else if (!strcmp(cmd.s, "Xmeid")) {
if (c != ' ') goto missingargs;
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto missingargs;
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto extraargs;
cmd_xmeid(tag.s, arg1.s);
}
else if (apns_enabled && !strcmp(cmd.s, "Xapplepushservice")) {
if (c != ' ') goto missingargs;
memset(&applepushserviceargs, 0, sizeof(struct applepushserviceargs));
do {
c = getastring(imapd_in, imapd_out, &arg1);
if (c == EOF) goto aps_missingargs;
if (!strcmp(arg1.s, "mailboxes")) {
c = prot_getc(imapd_in);
if (c != '(')
goto aps_missingargs;
c = prot_getc(imapd_in);
if (c != ')') {
prot_ungetc(c, imapd_in);
do {
c = getastring(imapd_in, imapd_out, &arg2);
if (c == EOF) break;
strarray_push(&applepushserviceargs.mailboxes, arg2.s);
} while (c == ' ');
}
if (c != ')')
goto aps_missingargs;
c = prot_getc(imapd_in);
}
else {
c = getastring(imapd_in, imapd_out, &arg2);
if (!strcmp(arg1.s, "aps-version")) {
if (!imparse_isnumber(arg2.s)) goto aps_extraargs;
applepushserviceargs.aps_version = atoi(arg2.s);
}
else if (!strcmp(arg1.s, "aps-account-id"))
buf_copy(&applepushserviceargs.aps_account_id, &arg2);
else if (!strcmp(arg1.s, "aps-device-token"))
buf_copy(&applepushserviceargs.aps_device_token, &arg2);
else if (!strcmp(arg1.s, "aps-subtopic"))
buf_copy(&applepushserviceargs.aps_subtopic, &arg2);
else
goto aps_extraargs;
}
} while (c == ' ');
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') goto aps_extraargs;
cmd_xapplepushservice(tag.s, &applepushserviceargs);
}
else goto badcmd;
break;
default:
badcmd:
prot_printf(imapd_out, "%s BAD Unrecognized command\r\n", tag.s);
eatline(imapd_in, c);
}
/* End command timer - don't log "idle" commands */
if (commandmintimer && strcmp("idle", cmdname)) {
double cmdtime, nettime;
const char *mboxname = index_mboxname(imapd_index);
if (!mboxname) mboxname = "<none>";
cmdtime_endtimer(&cmdtime, &nettime);
if (cmdtime >= commandmintimerd) {
syslog(LOG_NOTICE, "cmdtimer: '%s' '%s' '%s' '%f' '%f' '%f'",
imapd_userid ? imapd_userid : "<none>", cmdname, mboxname,
cmdtime, nettime, cmdtime + nettime);
}
}
continue;
nologin:
prot_printf(imapd_out, "%s BAD Please login first\r\n", tag.s);
eatline(imapd_in, c);
continue;
nomailbox:
prot_printf(imapd_out,
"%s BAD Please select a mailbox first\r\n", tag.s);
eatline(imapd_in, c);
continue;
aps_missingargs:
buf_free(&applepushserviceargs.aps_account_id);
buf_free(&applepushserviceargs.aps_device_token);
buf_free(&applepushserviceargs.aps_subtopic);
strarray_fini(&applepushserviceargs.mailboxes);
missingargs:
prot_printf(imapd_out,
"%s BAD Missing required argument to %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
aps_extraargs:
buf_free(&applepushserviceargs.aps_account_id);
buf_free(&applepushserviceargs.aps_device_token);
buf_free(&applepushserviceargs.aps_subtopic);
strarray_fini(&applepushserviceargs.mailboxes);
extraargs:
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
badsequence:
prot_printf(imapd_out,
"%s BAD Invalid sequence in %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
badpartition:
prot_printf(imapd_out,
"%s BAD Invalid partition name in %s\r\n", tag.s, cmd.s);
eatline(imapd_in, c);
continue;
}
done:
cmd_syncrestart(NULL, &reserve_list, 0);
}
Commit Message: imapd: check for isadmin BEFORE parsing sync lines
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data)
{
int ret;
ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0),
PEGASUS_REQ_SET_REGS, PEGASUS_REQT_WRITE, 0,
indx, data, size, 100);
if (ret < 0)
netif_dbg(pegasus, drv, pegasus->net,
"%s returned %d\n", __func__, ret);
return ret;
}
Commit Message: pegasus: Use heap buffers for all register access
Allocating USB buffers on the stack is not portable, and no longer
works on x86_64 (with VMAP_STACK enabled as per default).
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
References: https://bugs.debian.org/852556
Reported-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]>
Tested-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]>
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int em_pop_sreg(struct x86_emulate_ctxt *ctxt)
{
int seg = ctxt->src2.val;
unsigned long selector;
int rc;
rc = emulate_pop(ctxt, &selector, 2);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->modrm_reg == VCPU_SREG_SS)
ctxt->interruptibility = KVM_X86_SHADOW_INT_MOV_SS;
if (ctxt->op_bytes > 2)
rsp_increment(ctxt, ctxt->op_bytes - 2);
rc = load_segment_descriptor(ctxt, (u16)selector, seg);
return rc;
}
Commit Message: KVM: x86: drop error recovery in em_jmp_far and em_ret_far
em_jmp_far and em_ret_far assumed that setting IP can only fail in 64
bit mode, but syzkaller proved otherwise (and SDM agrees).
Code segment was restored upon failure, but it was left uninitialized
outside of long mode, which could lead to a leak of host kernel stack.
We could have fixed that by always saving and restoring the CS, but we
take a simpler approach and just break any guest that manages to fail
as the error recovery is error-prone and modern CPUs don't need emulator
for this.
Found by syzkaller:
WARNING: CPU: 2 PID: 3668 at arch/x86/kvm/emulate.c:2217 em_ret_far+0x428/0x480
Kernel panic - not syncing: panic_on_warn set ...
CPU: 2 PID: 3668 Comm: syz-executor Not tainted 4.9.0-rc4+ #49
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
[...]
Call Trace:
[...] __dump_stack lib/dump_stack.c:15
[...] dump_stack+0xb3/0x118 lib/dump_stack.c:51
[...] panic+0x1b7/0x3a3 kernel/panic.c:179
[...] __warn+0x1c4/0x1e0 kernel/panic.c:542
[...] warn_slowpath_null+0x2c/0x40 kernel/panic.c:585
[...] em_ret_far+0x428/0x480 arch/x86/kvm/emulate.c:2217
[...] em_ret_far_imm+0x17/0x70 arch/x86/kvm/emulate.c:2227
[...] x86_emulate_insn+0x87a/0x3730 arch/x86/kvm/emulate.c:5294
[...] x86_emulate_instruction+0x520/0x1ba0 arch/x86/kvm/x86.c:5545
[...] emulate_instruction arch/x86/include/asm/kvm_host.h:1116
[...] complete_emulated_io arch/x86/kvm/x86.c:6870
[...] complete_emulated_mmio+0x4e9/0x710 arch/x86/kvm/x86.c:6934
[...] kvm_arch_vcpu_ioctl_run+0x3b7a/0x5a90 arch/x86/kvm/x86.c:6978
[...] kvm_vcpu_ioctl+0x61e/0xdd0 arch/x86/kvm/../../../virt/kvm/kvm_main.c:2557
[...] vfs_ioctl fs/ioctl.c:43
[...] do_vfs_ioctl+0x18c/0x1040 fs/ioctl.c:679
[...] SYSC_ioctl fs/ioctl.c:694
[...] SyS_ioctl+0x8f/0xc0 fs/ioctl.c:685
[...] entry_SYSCALL_64_fastpath+0x1f/0xc2
Reported-by: Dmitry Vyukov <[email protected]>
Cc: [email protected]
Fixes: d1442d85cc30 ("KVM: x86: Handle errors when RIP is set during far jumps")
Signed-off-by: Radim Krčmář <[email protected]>
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GDataDirectory* AddDirectory(GDataDirectory* parent,
GDataDirectoryService* directory_service,
int sequence_id) {
GDataDirectory* dir = new GDataDirectory(NULL, directory_service);
const std::string dir_name = "dir" + base::IntToString(sequence_id);
const std::string resource_id = std::string("dir_resource_id:") +
dir_name;
dir->set_title(dir_name);
dir->set_resource_id(resource_id);
GDataFileError error = GDATA_FILE_ERROR_FAILED;
FilePath moved_file_path;
directory_service->MoveEntryToDirectory(
parent->GetFilePath(),
dir,
base::Bind(&test_util::CopyResultsFromFileMoveCallback,
&error,
&moved_file_path));
test_util::RunBlockingPoolTask();
EXPECT_EQ(GDATA_FILE_OK, error);
EXPECT_EQ(parent->GetFilePath().AppendASCII(dir_name), moved_file_path);
return dir;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int irda_recvmsg_stream(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
int noblock = flags & MSG_DONTWAIT;
size_t copied = 0;
int target, err;
long timeo;
IRDA_DEBUG(3, "%s()\n", __func__);
if ((err = sock_error(sk)) < 0)
return err;
if (sock->flags & __SO_ACCEPTCON)
return -EINVAL;
err =-EOPNOTSUPP;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
err = 0;
target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, noblock);
msg->msg_namelen = 0;
do {
int chunk;
struct sk_buff *skb = skb_dequeue(&sk->sk_receive_queue);
if (skb == NULL) {
DEFINE_WAIT(wait);
err = 0;
if (copied >= target)
break;
prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
;
else if (sk->sk_shutdown & RCV_SHUTDOWN)
;
else if (noblock)
err = -EAGAIN;
else if (signal_pending(current))
err = sock_intr_errno(timeo);
else if (sk->sk_state != TCP_ESTABLISHED)
err = -ENOTCONN;
else if (skb_peek(&sk->sk_receive_queue) == NULL)
/* Wait process until data arrives */
schedule();
finish_wait(sk_sleep(sk), &wait);
if (err)
return err;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
continue;
}
chunk = min_t(unsigned int, skb->len, size);
if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) {
skb_queue_head(&sk->sk_receive_queue, skb);
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
skb_pull(skb, chunk);
/* put the skb back if we didn't use it up.. */
if (skb->len) {
IRDA_DEBUG(1, "%s(), back on q!\n",
__func__);
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
kfree_skb(skb);
} else {
IRDA_DEBUG(0, "%s() questionable!?\n", __func__);
/* put message back and return */
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
} while (size);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: void LayerTreeHostImpl::AnimateInternal(bool active_tree) {
DCHECK(task_runner_provider_->IsImplThread());
base::TimeTicks monotonic_time = CurrentBeginFrameArgs().frame_time;
bool did_animate = false;
if (input_handler_client_) {
bool ignore_fling =
settings_.ignore_root_layer_flings && IsCurrentlyScrollingViewport();
if (!ignore_fling) {
input_handler_client_->Animate(monotonic_time);
}
}
did_animate |= AnimatePageScale(monotonic_time);
did_animate |= AnimateLayers(monotonic_time);
did_animate |= AnimateScrollbars(monotonic_time);
did_animate |= AnimateBrowserControls(monotonic_time);
if (active_tree) {
did_animate |= Mutate(monotonic_time);
UpdateRootLayerStateForSynchronousInputHandler();
if (did_animate) {
SetNeedsRedraw();
}
}
}
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
[email protected], [email protected]
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954}
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: String HTMLInputElement::ValidationSubMessage() const {
if (!willValidate() || CustomError())
return String();
return input_type_->ValidationMessage(*input_type_view_).second;
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
CMS_RecipientInfo *ri)
{
CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
EVP_PKEY *pkey = ktri->pkey;
unsigned char *ek = NULL;
size_t eklen;
int ret = 0;
CMS_EncryptedContentInfo *ec;
ec = cms->d.envelopedData->encryptedContentInfo;
CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY);
return 0;
return 0;
}
Commit Message:
CWE ID: CWE-311
Target: 1
Example 2:
Code: ofpacts_put_openflow_actions(const struct ofpact ofpacts[], size_t ofpacts_len,
struct ofpbuf *openflow,
enum ofp_version ofp_version)
{
const struct ofpact *a;
size_t start_size = openflow->size;
OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
encode_ofpact(a, ofp_version, openflow);
}
return openflow->size - start_size;
}
Commit Message: ofp-actions: Avoid buffer overread in BUNDLE action decoding.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9052
Signed-off-by: Ben Pfaff <[email protected]>
Acked-by: Justin Pettit <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
while (elements-- > 0) {
zval *key, *data, **old_data;
ALLOC_INIT_ZVAL(key);
if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
ALLOC_INIT_ZVAL(data);
if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
zval_dtor(data);
FREE_ZVAL(data);
return 0;
}
if (!objprops) {
switch (Z_TYPE_P(key)) {
case IS_LONG:
if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
break;
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
break;
}
} else {
/* object properties should include no integers */
convert_to_string(key);
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
sizeof data, NULL);
}
zval_dtor(key);
FREE_ZVAL(key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
Commit Message: Fix for bug #68710 (Use After Free Vulnerability in PHP's unserialize())
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct ucma_multicast* ucma_alloc_multicast(struct ucma_context *ctx)
{
struct ucma_multicast *mc;
mc = kzalloc(sizeof(*mc), GFP_KERNEL);
if (!mc)
return NULL;
mutex_lock(&mut);
mc->id = idr_alloc(&multicast_idr, mc, 0, 0, GFP_KERNEL);
mutex_unlock(&mut);
if (mc->id < 0)
goto error;
mc->ctx = ctx;
list_add_tail(&mc->list, &ctx->mc_list);
return mc;
error:
kfree(mc);
return NULL;
}
Commit Message: infiniband: fix a possible use-after-free bug
ucma_process_join() will free the new allocated "mc" struct,
if there is any error after that, especially the copy_to_user().
But in parallel, ucma_leave_multicast() could find this "mc"
through idr_find() before ucma_process_join() frees it, since it
is already published.
So "mc" could be used in ucma_leave_multicast() after it is been
allocated and freed in ucma_process_join(), since we don't refcnt
it.
Fix this by separating "publish" from ID allocation, so that we
can get an ID first and publish it later after copy_to_user().
Fixes: c8f6a362bf3e ("RDMA/cma: Add multicast communication support")
Reported-by: Noam Rathaus <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: void GLES2DecoderImpl::DoVertexAttrib4fv(GLuint index, const GLfloat* v) {
VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_->GetVertexAttribInfo(index);
if (!info) {
SetGLError(GL_INVALID_VALUE, "glVertexAttrib4fv", "index out of range");
return;
}
VertexAttribManager::VertexAttribInfo::Vec4 value;
value.v[0] = v[0];
value.v[1] = v[1];
value.v[2] = v[2];
value.v[3] = v[3];
info->set_value(value);
glVertexAttrib4fv(index, v);
}
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void unix_notinflight(struct file *fp)
{
struct sock *s = unix_get_socket(fp);
if (s) {
struct unix_sock *u = unix_sk(s);
spin_lock(&unix_gc_lock);
BUG_ON(list_empty(&u->link));
if (atomic_long_dec_and_test(&u->inflight))
list_del_init(&u->link);
unix_tot_inflight--;
spin_unlock(&unix_gc_lock);
}
}
Commit Message: unix: properly account for FDs passed over unix sockets
It is possible for a process to allocate and accumulate far more FDs than
the process' limit by sending them over a unix socket then closing them
to keep the process' fd count low.
This change addresses this problem by keeping track of the number of FDs
in flight per user and preventing non-privileged processes from having
more FDs in flight than their configured FD limit.
Reported-by: [email protected]
Reported-by: Tetsuo Handa <[email protected]>
Mitigates: CVE-2013-4312 (Linux 2.0+)
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ssl3_read_n(SSL *s, int n, int max, int extend)
{
/* If extend == 0, obtain new n-byte packet; if extend == 1, increase
* packet by another n bytes.
* The packet will be in the sub-array of s->s3->rbuf.buf specified
* by s->packet and s->packet_length.
* (If s->read_ahead is set, 'max' bytes may be stored in rbuf
* [plus s->packet_length bytes if extend == 1].)
*/
int i,len,left;
long align=0;
unsigned char *pkt;
SSL3_BUFFER *rb;
if (n <= 0) return n;
rb = &(s->s3->rbuf);
if (rb->buf == NULL)
if (!ssl3_setup_read_buffer(s))
return -1;
left = rb->left;
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
#endif
if (!extend)
{
/* start with empty packet ... */
if (left == 0)
rb->offset = align;
else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH)
{
/* check if next packet length is large
* enough to justify payload alignment... */
pkt = rb->buf + rb->offset;
if (pkt[0] == SSL3_RT_APPLICATION_DATA
&& (pkt[3]<<8|pkt[4]) >= 128)
{
/* Note that even if packet is corrupted
* and its length field is insane, we can
* only be led to wrong decision about
* whether memmove will occur or not.
* Header values has no effect on memmove
* arguments and therefore no buffer
* overrun can be triggered. */
memmove (rb->buf+align,pkt,left);
rb->offset = align;
}
}
s->packet = rb->buf + rb->offset;
s->packet_length = 0;
/* ... now we can act as if 'extend' was set */
}
/* For DTLS/UDP reads should not span multiple packets
* because the read operation returns the whole packet
* at once (as long as it fits into the buffer). */
if (SSL_IS_DTLS(s))
{
if (left > 0 && n > left)
n = left;
}
/* if there is enough in the buffer from a previous read, take some */
if (left >= n)
{
s->packet_length+=n;
rb->left=left-n;
rb->offset+=n;
return(n);
}
/* else we need to read more data */
len = s->packet_length;
pkt = rb->buf+align;
/* Move any available bytes to front of buffer:
* 'len' bytes already pointed to by 'packet',
* 'left' extra ones at the end */
if (s->packet != pkt) /* len > 0 */
{
memmove(pkt, s->packet, len+left);
s->packet = pkt;
rb->offset = len + align;
}
if (n > (int)(rb->len - rb->offset)) /* does not happen */
{
SSLerr(SSL_F_SSL3_READ_N,ERR_R_INTERNAL_ERROR);
return -1;
}
if (!s->read_ahead)
/* ignore max parameter */
max = n;
else
{
if (max < n)
max = n;
if (max > (int)(rb->len - rb->offset))
max = rb->len - rb->offset;
}
while (left < n)
{
/* Now we have len+left bytes at the front of s->s3->rbuf.buf
* and need to read in more until we have len+n (up to
* len+max if possible) */
clear_sys_error();
if (s->rbio != NULL)
{
s->rwstate=SSL_READING;
i=BIO_read(s->rbio,pkt+len+left, max-left);
}
else
{
SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET);
i = -1;
}
if (i <= 0)
{
rb->left = left;
if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
!SSL_IS_DTLS(s))
if (len+left == 0)
ssl3_release_read_buffer(s);
return(i);
}
left+=i;
/* reads should *never* span multiple packets for DTLS because
* the underlying transport protocol is message oriented as opposed
* to byte oriented as in the TLS case. */
if (SSL_IS_DTLS(s))
{
if (n > left)
n = left; /* makes the while condition false */
}
}
/* done reading, now the book-keeping */
rb->offset += n;
rb->left = left - n;
s->packet_length += n;
s->rwstate=SSL_NOTHING;
return(n);
}
Commit Message: Fix crash in dtls1_get_record whilst in the listen state where you get two
separate reads performed - one for the header and one for the body of the
handshake record.
CVE-2014-3571
Reviewed-by: Matt Caswell <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: UINT8 BTM_GetSecurityMode (void)
{
return(btm_cb.security_mode);
}
Commit Message: DO NOT MERGE Remove Porsche car-kit pairing workaround
Bug: 26551752
Change-Id: I14c5e3fcda0849874c8a94e48aeb7d09585617e1
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GDataRootDirectory::AddEntryToResourceMap(GDataEntry* entry) {
DVLOG(1) << "AddEntryToResourceMap " << entry->resource_id();
resource_map_.insert(std::make_pair(entry->resource_id(), entry));
}
Commit Message: gdata: Define the resource ID for the root directory
Per the spec, the resource ID for the root directory is defined
as "folder:root". Add the resource ID to the root directory in our
file system representation so we can look up the root directory by
the resource ID.
BUG=127697
TEST=add unit tests
Review URL: https://chromiumcodereview.appspot.com/10332253
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137928 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: my_object_process_variant_of_array_of_ints123 (MyObject *obj, GValue *variant, GError **error)
{
GArray *array;
int i;
int j;
j = 0;
array = (GArray *)g_value_get_boxed (variant);
for (i = 0; i <= 2; i++)
{
j = g_array_index (array, int, i);
if (j != i + 1)
goto error;
}
return TRUE;
error:
*error = g_error_new (MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"Error decoding a variant of type ai (i + 1 = %i, j = %i)",
i, j + 1);
return FALSE;
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: void V8TestObject::VoidMethodStringFrozenArrayMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_voidMethodStringFrozenArrayMethod");
test_object_v8_internal::VoidMethodStringFrozenArrayMethodMethod(info);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: tt_cmap8_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_Byte* is32;
FT_UInt32 length;
FT_UInt32 num_groups;
if ( table + 16 + 8192 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
if ( table + length > valid->limit || length < 8208 )
FT_INVALID_TOO_SHORT;
is32 = table + 12;
p = is32 + 8192; /* skip `is32' array */
num_groups = TT_NEXT_ULONG( p );
if ( p + num_groups * 12 > valid->limit )
FT_INVALID_TOO_SHORT;
/* check groups, they must be in increasing order */
{
FT_UInt32 n, start, end, start_id, count, last = 0;
for ( n = 0; n < num_groups; n++ )
{
FT_UInt hi, lo;
start = TT_NEXT_ULONG( p );
end = TT_NEXT_ULONG( p );
start_id = TT_NEXT_ULONG( p );
if ( start > end )
FT_INVALID_DATA;
if ( n > 0 && start <= last )
FT_INVALID_DATA;
if ( valid->level >= FT_VALIDATE_TIGHT )
{
if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
count = (FT_UInt32)( end - start + 1 );
if ( start & ~0xFFFFU )
{
/* start_hi != 0; check that is32[i] is 1 for each i in */
/* the `hi' and `lo' of the range [start..end] */
for ( ; count > 0; count--, start++ )
{
hi = (FT_UInt)( start >> 16 );
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 )
FT_INVALID_DATA;
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 )
FT_INVALID_DATA;
}
}
else
{
/* start_hi == 0; check that is32[i] is 0 for each i in */
/* the range [start..end] */
/* end_hi cannot be != 0! */
if ( end & ~0xFFFFU )
FT_INVALID_DATA;
for ( ; count > 0; count--, start++ )
{
lo = (FT_UInt)( start & 0xFFFFU );
if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 )
FT_INVALID_DATA;
}
}
}
last = end;
}
}
return SFNT_Err_Ok;
}
Commit Message:
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void mark_object(struct object *obj, struct strbuf *path,
const char *name, void *data)
{
update_progress(data);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: evutil_freeaddrinfo(struct evutil_addrinfo *ai)
{
#ifdef EVENT__HAVE_GETADDRINFO
if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
freeaddrinfo(ai);
return;
}
#endif
while (ai) {
struct evutil_addrinfo *next = ai->ai_next;
if (ai->ai_canonname)
mm_free(ai->ai_canonname);
mm_free(ai);
ai = next;
}
}
Commit Message: evutil_parse_sockaddr_port(): fix buffer overflow
@asn-the-goblin-slayer:
"Length between '[' and ']' is cast to signed 32 bit integer on line 1815. Is
the length is more than 2<<31 (INT_MAX), len will hold a negative value.
Consequently, it will pass the check at line 1816. Segfault happens at line
1819.
Generate a resolv.conf with generate-resolv.conf, then compile and run
poc.c. See entry-functions.txt for functions in tor that might be
vulnerable.
Please credit 'Guido Vranken' for this discovery through the Tor bug bounty
program."
Reproducer for gdb (https://gist.github.com/azat/be2b0d5e9417ba0dfe2c):
start
p (1ULL<<31)+1ULL
# $1 = 2147483649
p malloc(sizeof(struct sockaddr))
# $2 = (void *) 0x646010
p malloc(sizeof(int))
# $3 = (void *) 0x646030
p malloc($1)
# $4 = (void *) 0x7fff76a2a010
p memset($4, 1, $1)
# $5 = 1990369296
p (char *)$4
# $6 = 0x7fff76a2a010 '\001' <repeats 200 times>...
set $6[0]='['
set $6[$1]=']'
p evutil_parse_sockaddr_port($4, $2, $3)
# $7 = -1
Before:
$ gdb bin/http-connect < gdb
(gdb) $1 = 2147483649
(gdb) (gdb) $2 = (void *) 0x646010
(gdb) (gdb) $3 = (void *) 0x646030
(gdb) (gdb) $4 = (void *) 0x7fff76a2a010
(gdb) (gdb) $5 = 1990369296
(gdb) (gdb) $6 = 0x7fff76a2a010 '\001' <repeats 200 times>...
(gdb) (gdb) (gdb) (gdb)
Program received signal SIGSEGV, Segmentation fault.
__memcpy_sse2_unaligned () at memcpy-sse2-unaligned.S:36
After:
$ gdb bin/http-connect < gdb
(gdb) $1 = 2147483649
(gdb) (gdb) $2 = (void *) 0x646010
(gdb) (gdb) $3 = (void *) 0x646030
(gdb) (gdb) $4 = (void *) 0x7fff76a2a010
(gdb) (gdb) $5 = 1990369296
(gdb) (gdb) $6 = 0x7fff76a2a010 '\001' <repeats 200 times>...
(gdb) (gdb) (gdb) (gdb) $7 = -1
(gdb) (gdb) quit
Fixes: #318
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int sysMapFile(const char* fn, MemMapping* pMap)
{
memset(pMap, 0, sizeof(*pMap));
if (fn && fn[0] == '@') {
FILE* mapf = fopen(fn+1, "r");
if (mapf == NULL) {
LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno));
return -1;
}
if (sysMapBlockFile(mapf, pMap) != 0) {
LOGW("Map of '%s' failed\n", fn);
return -1;
}
fclose(mapf);
} else {
int fd = open(fn, O_RDONLY, 0);
if (fd < 0) {
LOGE("Unable to open '%s': %s\n", fn, strerror(errno));
return -1;
}
if (sysMapFD(fd, pMap) != 0) {
LOGE("Map of '%s' failed\n", fn);
close(fd);
return -1;
}
close(fd);
}
return 0;
}
Commit Message: Fix integer overflows in recovery procedure.
Bug: 26960931
Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf
(cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b)
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const size_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
register const unsigned char
*p;
register Quantum
*q;
register ssize_t
x;
size_t
packet_size;
unsigned short
nibble;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
{
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
switch (type)
{
case -1:
{
SetPixelAlpha(image,pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
if (image->depth == 1)
{
ssize_t
bit,
number_bits;
number_bits=image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit=0; bit < number_bits; bit++)
{
SetPixelIndex(image,(((unsigned char) pixel) &
(0x01 << (7-bit))) != 0 ? 0 : 255,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),
exception),q);
q+=GetPixelChannels(image);
x++;
}
x--;
continue;
}
}
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
return(SyncAuthenticPixels(image,exception));
}
Commit Message: Rewrite reading pixel values.
CWE ID: CWE-125
Target: 1
Example 2:
Code: void V8TestObject::EventHandlerAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_eventHandlerAttribute_Getter");
test_object_v8_internal::EventHandlerAttributeAttributeGetter(info);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t MediaPlayerService::Client::pause()
{
ALOGV("[%d] pause", mConnId);
sp<MediaPlayerBase> p = getPlayer();
if (p == 0) return UNKNOWN_ERROR;
return p->pause();
}
Commit Message: MediaPlayerService: avoid invalid static cast
Bug: 30204103
Change-Id: Ie0dd3568a375f1e9fed8615ad3d85184bcc99028
(cherry picked from commit ee0a0e39acdcf8f97e0d6945c31ff36a06a36e9d)
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
struct inet_sock *inet = inet_sk(sk);
struct tcp_sock *tp = tcp_sk(sk);
__be16 orig_sport, orig_dport;
__be32 daddr, nexthop;
struct flowi4 fl4;
struct rtable *rt;
int err;
if (addr_len < sizeof(struct sockaddr_in))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EAFNOSUPPORT;
nexthop = daddr = usin->sin_addr.s_addr;
if (inet->opt && inet->opt->srr) {
if (!daddr)
return -EINVAL;
nexthop = inet->opt->faddr;
}
orig_sport = inet->inet_sport;
orig_dport = usin->sin_port;
rt = ip_route_connect(&fl4, nexthop, inet->inet_saddr,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,
IPPROTO_TCP,
orig_sport, orig_dport, sk, true);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
if (err == -ENETUNREACH)
IP_INC_STATS_BH(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
return err;
}
if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
ip_rt_put(rt);
return -ENETUNREACH;
}
if (!inet->opt || !inet->opt->srr)
daddr = rt->rt_dst;
if (!inet->inet_saddr)
inet->inet_saddr = rt->rt_src;
inet->inet_rcv_saddr = inet->inet_saddr;
if (tp->rx_opt.ts_recent_stamp && inet->inet_daddr != daddr) {
/* Reset inherited state */
tp->rx_opt.ts_recent = 0;
tp->rx_opt.ts_recent_stamp = 0;
tp->write_seq = 0;
}
if (tcp_death_row.sysctl_tw_recycle &&
!tp->rx_opt.ts_recent_stamp && rt->rt_dst == daddr) {
struct inet_peer *peer = rt_get_peer(rt);
/*
* VJ's idea. We save last timestamp seen from
* the destination in peer table, when entering state
* TIME-WAIT * and initialize rx_opt.ts_recent from it,
* when trying new connection.
*/
if (peer) {
inet_peer_refcheck(peer);
if ((u32)get_seconds() - peer->tcp_ts_stamp <= TCP_PAWS_MSL) {
tp->rx_opt.ts_recent_stamp = peer->tcp_ts_stamp;
tp->rx_opt.ts_recent = peer->tcp_ts;
}
}
}
inet->inet_dport = usin->sin_port;
inet->inet_daddr = daddr;
inet_csk(sk)->icsk_ext_hdr_len = 0;
if (inet->opt)
inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen;
tp->rx_opt.mss_clamp = TCP_MSS_DEFAULT;
/* Socket identity is still unknown (sport may be zero).
* However we set state to SYN-SENT and not releasing socket
* lock select source port, enter ourselves into the hash tables and
* complete initialization after this.
*/
tcp_set_state(sk, TCP_SYN_SENT);
err = inet_hash_connect(&tcp_death_row, sk);
if (err)
goto failure;
rt = ip_route_newports(&fl4, rt, orig_sport, orig_dport,
inet->inet_sport, inet->inet_dport, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
goto failure;
}
/* OK, now commit destination to socket. */
sk->sk_gso_type = SKB_GSO_TCPV4;
sk_setup_caps(sk, &rt->dst);
if (!tp->write_seq)
tp->write_seq = secure_tcp_sequence_number(inet->inet_saddr,
inet->inet_daddr,
inet->inet_sport,
usin->sin_port);
inet->inet_id = tp->write_seq ^ jiffies;
err = tcp_connect(sk);
rt = NULL;
if (err)
goto failure;
return 0;
failure:
/*
* This unhashes the socket and releases the local port,
* if necessary.
*/
tcp_set_state(sk, TCP_CLOSE);
ip_rt_put(rt);
sk->sk_route_caps = 0;
inet->inet_dport = 0;
return err;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: void ff_mpv_decode_init(MpegEncContext *s, AVCodecContext *avctx)
{
s->avctx = avctx;
s->width = avctx->coded_width;
s->height = avctx->coded_height;
s->codec_id = avctx->codec->id;
s->workaround_bugs = avctx->workaround_bugs;
/* convert fourcc to upper case */
s->codec_tag = avpriv_toupper4(avctx->codec_tag);
}
Commit Message: avcodec/idctdsp: Transmit studio_profile to init instead of using AVCodecContext profile
These 2 fields are not always the same, it is simpler to always use the same field
for detecting studio profile
Fixes: null pointer dereference
Fixes: ffmpeg_crash_3.avi
Found-by: Thuan Pham <[email protected]>, Marcel Böhme, Andrew Santosa and Alexandru RazvanCaciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebGLRenderingContextBase::deleteBuffer(WebGLBuffer* buffer) {
if (!DeleteObject(buffer))
return;
RemoveBoundBuffer(buffer);
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags, uint16_t *notecount)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
if (*notecount == 0)
return 0;
--*notecount;
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return 0;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return 0;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & FLAGS_DID_OS_NOTE) == 0) {
if (do_os_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_BUILD_ID) == 0) {
if (do_bid_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) {
if (do_pax_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_CORE) == 0) {
if (do_core_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags, size, clazz))
return size;
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
switch (xnh_type) {
case NT_NETBSD_VERSION:
return size;
case NT_NETBSD_MARCH:
if (*flags & FLAGS_DID_NETBSD_MARCH)
return size;
if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
(const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (*flags & FLAGS_DID_NETBSD_CMODEL)
return size;
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (*flags & FLAGS_DID_NETBSD_UNKNOWN)
return size;
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
return offset;
}
Commit Message: Limit string printing to 100 chars, and add flags I forgot in the previous
commit.
CWE ID: CWE-399
Target: 1
Example 2:
Code: std::unique_ptr<net::test_server::HttpResponse> HandleSetHeaderRequest(
const net::test_server::HttpRequest& request) {
if (!base::StartsWith(request.relative_url, "/set-header?",
base::CompareCase::SENSITIVE))
return nullptr;
size_t query_string_pos = request.relative_url.find('?');
std::string escaped_header =
request.relative_url.substr(query_string_pos + 1);
std::string header = net::UnescapeURLComponent(
escaped_header,
net::UnescapeRule::NORMAL | net::UnescapeRule::SPACES |
net::UnescapeRule::PATH_SEPARATORS |
net::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS);
size_t colon_pos = header.find(':');
if (colon_pos == std::string::npos)
return std::unique_ptr<net::test_server::HttpResponse>();
std::string header_name = header.substr(0, colon_pos);
std::string header_value = header.substr(colon_pos + 2);
std::unique_ptr<net::test_server::BasicHttpResponse> http_response(
new net::test_server::BasicHttpResponse);
http_response->set_code(net::HTTP_OK);
http_response->AddCustomHeader(header_name, header_value);
return std::move(http_response);
}
Commit Message: Hide DevTools frontend from webRequest API
Prevent extensions from observing requests for remote DevTools frontends
and add regression tests.
And update ExtensionTestApi to support initializing the embedded test
server and port from SetUpCommandLine (before SetUpOnMainThread).
BUG=797497,797500
TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo
Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735
Reviewed-on: https://chromium-review.googlesource.com/844316
Commit-Queue: Rob Wu <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#528187}
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void qrio_set_leds(void)
{
u8 ctrlh;
void __iomem *qrio_base = (void *)CONFIG_SYS_QRIO_BASE;
/* set UNIT LED to RED and BOOT LED to ON */
ctrlh = in_8(qrio_base + CTRLH_OFF);
ctrlh |= (CTRLH_WRL_BOOT | CTRLH_WRL_UNITRUN);
out_8(qrio_base + CTRLH_OFF, ctrlh);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BOOL rdp_decrypt(rdpRdp* rdp, STREAM* s, int length, UINT16 securityFlags)
{
BYTE cmac[8];
BYTE wmac[8];
if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
{
UINT16 len;
BYTE version, pad;
BYTE* sig;
if (stream_get_left(s) < 12)
return FALSE;
stream_read_UINT16(s, len); /* 0x10 */
stream_read_BYTE(s, version); /* 0x1 */
stream_read_BYTE(s, pad);
sig = s->p;
stream_seek(s, 8); /* signature */
length -= 12;
if (!security_fips_decrypt(s->p, length, rdp))
{
printf("FATAL: cannot decrypt\n");
return FALSE; /* TODO */
}
if (!security_fips_check_signature(s->p, length - pad, sig, rdp))
{
printf("FATAL: invalid packet signature\n");
return FALSE; /* TODO */
}
/* is this what needs adjusting? */
s->size -= pad;
return TRUE;
}
if (stream_get_left(s) < 8)
return FALSE;
stream_read(s, wmac, sizeof(wmac));
length -= sizeof(wmac);
security_decrypt(s->p, length, rdp);
if (securityFlags & SEC_SECURE_CHECKSUM)
security_salted_mac_signature(rdp, s->p, length, FALSE, cmac);
else
security_mac_signature(rdp, s->p, length, cmac);
if (memcmp(wmac, cmac, sizeof(wmac)) != 0)
{
printf("WARNING: invalid packet signature\n");
/*
* Because Standard RDP Security is totally broken,
* and cannot protect against MITM, don't treat signature
* verification failure as critical. This at least enables
* us to work with broken RDP clients and servers that
* generate invalid signatures.
*/
}
return TRUE;
}
Commit Message: security: add a NULL pointer check to fix a server crash.
CWE ID: CWE-476
Target: 1
Example 2:
Code: void WebRuntimeFeatures::enableScriptedSpeech(bool enable)
{
RuntimeEnabledFeatures::setScriptedSpeechEnabled(enable);
}
Commit Message: Remove SpeechSynthesis runtime flag (status=stable)
BUG=402536
Review URL: https://codereview.chromium.org/482273005
git-svn-id: svn://svn.chromium.org/blink/trunk@180763 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-94
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void set_banner(struct openconnect_info *vpninfo)
{
char *banner, *q;
const char *p;
if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)))) {
unsetenv("CISCO_BANNER");
return;
}
p = vpninfo->banner;
q = banner;
while (*p) {
if (*p == '%' && isxdigit((int)(unsigned char)p[1]) &&
isxdigit((int)(unsigned char)p[2])) {
*(q++) = unhex(p + 1);
p += 3;
} else
*(q++) = *(p++);
}
*q = 0;
setenv("CISCO_BANNER", banner, 1);
free(banner);
}
Commit Message:
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xsltDocumentElem(xsltTransformContextPtr ctxt, xmlNodePtr node,
xmlNodePtr inst, xsltStylePreCompPtr castedComp)
{
#ifdef XSLT_REFACTORED
xsltStyleItemDocumentPtr comp = (xsltStyleItemDocumentPtr) castedComp;
#else
xsltStylePreCompPtr comp = castedComp;
#endif
xsltStylesheetPtr style = NULL;
int ret;
xmlChar *filename = NULL, *prop, *elements;
xmlChar *element, *end;
xmlDocPtr res = NULL;
xmlDocPtr oldOutput;
xmlNodePtr oldInsert, root;
const char *oldOutputFile;
xsltOutputType oldType;
xmlChar *URL = NULL;
const xmlChar *method;
const xmlChar *doctypePublic;
const xmlChar *doctypeSystem;
const xmlChar *version;
const xmlChar *encoding;
int redirect_write_append = 0;
if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL))
return;
if (comp->filename == NULL) {
if (xmlStrEqual(inst->name, (const xmlChar *) "output")) {
/*
* The element "output" is in the namespace XSLT_SAXON_NAMESPACE
* (http://icl.com/saxon)
* The @file is in no namespace.
*/
#ifdef WITH_XSLT_DEBUG_EXTRA
xsltGenericDebug(xsltGenericDebugContext,
"Found saxon:output extension\n");
#endif
URL = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *) "file",
XSLT_SAXON_NAMESPACE);
if (URL == NULL)
URL = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *) "href",
XSLT_SAXON_NAMESPACE);
} else if (xmlStrEqual(inst->name, (const xmlChar *) "write")) {
#ifdef WITH_XSLT_DEBUG_EXTRA
xsltGenericDebug(xsltGenericDebugContext,
"Found xalan:write extension\n");
#endif
URL = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *)
"select",
XSLT_XALAN_NAMESPACE);
if (URL != NULL) {
xmlXPathCompExprPtr cmp;
xmlChar *val;
/*
* Trying to handle bug #59212
* The value of the "select" attribute is an
* XPath expression.
* (see http://xml.apache.org/xalan-j/extensionslib.html#redirect)
*/
cmp = xmlXPathCompile(URL);
val = xsltEvalXPathString(ctxt, cmp);
xmlXPathFreeCompExpr(cmp);
xmlFree(URL);
URL = val;
}
if (URL == NULL)
URL = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *)
"file",
XSLT_XALAN_NAMESPACE);
if (URL == NULL)
URL = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *)
"href",
XSLT_XALAN_NAMESPACE);
} else if (xmlStrEqual(inst->name, (const xmlChar *) "document")) {
URL = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *) "href",
NULL);
}
} else {
URL = xmlStrdup(comp->filename);
}
if (URL == NULL) {
xsltTransformError(ctxt, NULL, inst,
"xsltDocumentElem: href/URI-Reference not found\n");
return;
}
/*
* If the computation failed, it's likely that the URL wasn't escaped
*/
filename = xmlBuildURI(URL, (const xmlChar *) ctxt->outputFile);
if (filename == NULL) {
xmlChar *escURL;
escURL=xmlURIEscapeStr(URL, BAD_CAST ":/.?,");
if (escURL != NULL) {
filename = xmlBuildURI(escURL, (const xmlChar *) ctxt->outputFile);
xmlFree(escURL);
}
}
if (filename == NULL) {
xsltTransformError(ctxt, NULL, inst,
"xsltDocumentElem: URL computation failed for %s\n",
URL);
xmlFree(URL);
return;
}
/*
* Security checking: can we write to this resource
*/
if (ctxt->sec != NULL) {
ret = xsltCheckWrite(ctxt->sec, ctxt, filename);
if (ret == 0) {
xsltTransformError(ctxt, NULL, inst,
"xsltDocumentElem: write rights for %s denied\n",
filename);
xmlFree(URL);
xmlFree(filename);
return;
}
}
oldOutputFile = ctxt->outputFile;
oldOutput = ctxt->output;
oldInsert = ctxt->insert;
oldType = ctxt->type;
ctxt->outputFile = (const char *) filename;
style = xsltNewStylesheet();
if (style == NULL) {
xsltTransformError(ctxt, NULL, inst,
"xsltDocumentElem: out of memory\n");
goto error;
}
/*
* Version described in 1.1 draft allows full parameterization
* of the output.
*/
prop = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *) "version",
NULL);
if (prop != NULL) {
if (style->version != NULL)
xmlFree(style->version);
style->version = prop;
}
prop = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *) "encoding",
NULL);
if (prop != NULL) {
if (style->encoding != NULL)
xmlFree(style->encoding);
style->encoding = prop;
}
prop = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *) "method",
NULL);
if (prop != NULL) {
const xmlChar *URI;
if (style->method != NULL)
xmlFree(style->method);
style->method = NULL;
if (style->methodURI != NULL)
xmlFree(style->methodURI);
style->methodURI = NULL;
URI = xsltGetQNameURI(inst, &prop);
if (prop == NULL) {
if (style != NULL) style->errors++;
} else if (URI == NULL) {
if ((xmlStrEqual(prop, (const xmlChar *) "xml")) ||
(xmlStrEqual(prop, (const xmlChar *) "html")) ||
(xmlStrEqual(prop, (const xmlChar *) "text"))) {
style->method = prop;
} else {
xsltTransformError(ctxt, NULL, inst,
"invalid value for method: %s\n", prop);
if (style != NULL) style->warnings++;
}
} else {
style->method = prop;
style->methodURI = xmlStrdup(URI);
}
}
prop = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *)
"doctype-system", NULL);
if (prop != NULL) {
if (style->doctypeSystem != NULL)
xmlFree(style->doctypeSystem);
style->doctypeSystem = prop;
}
prop = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *)
"doctype-public", NULL);
if (prop != NULL) {
if (style->doctypePublic != NULL)
xmlFree(style->doctypePublic);
style->doctypePublic = prop;
}
prop = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *) "standalone",
NULL);
if (prop != NULL) {
if (xmlStrEqual(prop, (const xmlChar *) "yes")) {
style->standalone = 1;
} else if (xmlStrEqual(prop, (const xmlChar *) "no")) {
style->standalone = 0;
} else {
xsltTransformError(ctxt, NULL, inst,
"invalid value for standalone: %s\n",
prop);
if (style != NULL) style->warnings++;
}
xmlFree(prop);
}
prop = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *) "indent",
NULL);
if (prop != NULL) {
if (xmlStrEqual(prop, (const xmlChar *) "yes")) {
style->indent = 1;
} else if (xmlStrEqual(prop, (const xmlChar *) "no")) {
style->indent = 0;
} else {
xsltTransformError(ctxt, NULL, inst,
"invalid value for indent: %s\n", prop);
if (style != NULL) style->warnings++;
}
xmlFree(prop);
}
prop = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *)
"omit-xml-declaration",
NULL);
if (prop != NULL) {
if (xmlStrEqual(prop, (const xmlChar *) "yes")) {
style->omitXmlDeclaration = 1;
} else if (xmlStrEqual(prop, (const xmlChar *) "no")) {
style->omitXmlDeclaration = 0;
} else {
xsltTransformError(ctxt, NULL, inst,
"invalid value for omit-xml-declaration: %s\n",
prop);
if (style != NULL) style->warnings++;
}
xmlFree(prop);
}
elements = xsltEvalAttrValueTemplate(ctxt, inst,
(const xmlChar *)
"cdata-section-elements",
NULL);
if (elements != NULL) {
if (style->stripSpaces == NULL)
style->stripSpaces = xmlHashCreate(10);
if (style->stripSpaces == NULL)
return;
element = elements;
while (*element != 0) {
while (IS_BLANK_CH(*element))
element++;
if (*element == 0)
break;
end = element;
while ((*end != 0) && (!IS_BLANK_CH(*end)))
end++;
element = xmlStrndup(element, end - element);
if (element) {
const xmlChar *URI;
#ifdef WITH_XSLT_DEBUG_PARSING
xsltGenericDebug(xsltGenericDebugContext,
"add cdata section output element %s\n",
element);
#endif
URI = xsltGetQNameURI(inst, &element);
xmlHashAddEntry2(style->stripSpaces, element, URI,
(xmlChar *) "cdata");
xmlFree(element);
}
element = end;
}
xmlFree(elements);
}
/*
* Create a new document tree and process the element template
*/
XSLT_GET_IMPORT_PTR(method, style, method)
XSLT_GET_IMPORT_PTR(doctypePublic, style, doctypePublic)
XSLT_GET_IMPORT_PTR(doctypeSystem, style, doctypeSystem)
XSLT_GET_IMPORT_PTR(version, style, version)
XSLT_GET_IMPORT_PTR(encoding, style, encoding)
if ((method != NULL) &&
(!xmlStrEqual(method, (const xmlChar *) "xml"))) {
if (xmlStrEqual(method, (const xmlChar *) "html")) {
ctxt->type = XSLT_OUTPUT_HTML;
if (((doctypePublic != NULL) || (doctypeSystem != NULL)))
res = htmlNewDoc(doctypeSystem, doctypePublic);
else {
if (version != NULL) {
#ifdef XSLT_GENERATE_HTML_DOCTYPE
xsltGetHTMLIDs(version, &doctypePublic, &doctypeSystem);
#endif
}
res = htmlNewDocNoDtD(doctypeSystem, doctypePublic);
}
if (res == NULL)
goto error;
res->dict = ctxt->dict;
xmlDictReference(res->dict);
} else if (xmlStrEqual(method, (const xmlChar *) "xhtml")) {
xsltTransformError(ctxt, NULL, inst,
"xsltDocumentElem: unsupported method xhtml\n",
style->method);
ctxt->type = XSLT_OUTPUT_HTML;
res = htmlNewDocNoDtD(doctypeSystem, doctypePublic);
if (res == NULL)
goto error;
res->dict = ctxt->dict;
xmlDictReference(res->dict);
} else if (xmlStrEqual(method, (const xmlChar *) "text")) {
ctxt->type = XSLT_OUTPUT_TEXT;
res = xmlNewDoc(style->version);
if (res == NULL)
goto error;
res->dict = ctxt->dict;
xmlDictReference(res->dict);
#ifdef WITH_XSLT_DEBUG
xsltGenericDebug(xsltGenericDebugContext,
"reusing transformation dict for output\n");
#endif
} else {
xsltTransformError(ctxt, NULL, inst,
"xsltDocumentElem: unsupported method %s\n",
style->method);
goto error;
}
} else {
ctxt->type = XSLT_OUTPUT_XML;
res = xmlNewDoc(style->version);
if (res == NULL)
goto error;
res->dict = ctxt->dict;
xmlDictReference(res->dict);
#ifdef WITH_XSLT_DEBUG
xsltGenericDebug(xsltGenericDebugContext,
"reusing transformation dict for output\n");
#endif
}
res->charset = XML_CHAR_ENCODING_UTF8;
if (encoding != NULL)
res->encoding = xmlStrdup(encoding);
ctxt->output = res;
ctxt->insert = (xmlNodePtr) res;
xsltApplySequenceConstructor(ctxt, node, inst->children, NULL);
/*
* Do some post processing work depending on the generated output
*/
root = xmlDocGetRootElement(res);
if (root != NULL) {
const xmlChar *doctype = NULL;
if ((root->ns != NULL) && (root->ns->prefix != NULL))
doctype = xmlDictQLookup(ctxt->dict, root->ns->prefix, root->name);
if (doctype == NULL)
doctype = root->name;
/*
* Apply the default selection of the method
*/
if ((method == NULL) &&
(root->ns == NULL) &&
(!xmlStrcasecmp(root->name, (const xmlChar *) "html"))) {
xmlNodePtr tmp;
tmp = res->children;
while ((tmp != NULL) && (tmp != root)) {
if (tmp->type == XML_ELEMENT_NODE)
break;
if ((tmp->type == XML_TEXT_NODE) && (!xmlIsBlankNode(tmp)))
break;
tmp = tmp->next;
}
if (tmp == root) {
ctxt->type = XSLT_OUTPUT_HTML;
res->type = XML_HTML_DOCUMENT_NODE;
if (((doctypePublic != NULL) || (doctypeSystem != NULL))) {
res->intSubset = xmlCreateIntSubset(res, doctype,
doctypePublic,
doctypeSystem);
#ifdef XSLT_GENERATE_HTML_DOCTYPE
} else if (version != NULL) {
xsltGetHTMLIDs(version, &doctypePublic,
&doctypeSystem);
if (((doctypePublic != NULL) || (doctypeSystem != NULL)))
res->intSubset =
xmlCreateIntSubset(res, doctype,
doctypePublic,
doctypeSystem);
#endif
}
}
}
if (ctxt->type == XSLT_OUTPUT_XML) {
XSLT_GET_IMPORT_PTR(doctypePublic, style, doctypePublic)
XSLT_GET_IMPORT_PTR(doctypeSystem, style, doctypeSystem)
if (((doctypePublic != NULL) || (doctypeSystem != NULL)))
res->intSubset = xmlCreateIntSubset(res, doctype,
doctypePublic,
doctypeSystem);
}
}
/*
* Calls to redirect:write also take an optional attribute append.
* Attribute append="true|yes" which will attempt to simply append
* to an existing file instead of always opening a new file. The
* default behavior of always overwriting the file still happens
* if we do not specify append.
* Note that append use will forbid use of remote URI target.
*/
prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *)"append",
NULL);
if (prop != NULL) {
if (xmlStrEqual(prop, (const xmlChar *) "true") ||
xmlStrEqual(prop, (const xmlChar *) "yes")) {
style->omitXmlDeclaration = 1;
redirect_write_append = 1;
} else
style->omitXmlDeclaration = 0;
xmlFree(prop);
}
if (redirect_write_append) {
FILE *f;
f = fopen((const char *) filename, "ab");
if (f == NULL) {
ret = -1;
} else {
ret = xsltSaveResultToFile(f, res, style);
fclose(f);
}
} else {
ret = xsltSaveResultToFilename((const char *) filename, res, style, 0);
}
if (ret < 0) {
xsltTransformError(ctxt, NULL, inst,
"xsltDocumentElem: unable to save to %s\n",
filename);
ctxt->state = XSLT_STATE_ERROR;
#ifdef WITH_XSLT_DEBUG_EXTRA
} else {
xsltGenericDebug(xsltGenericDebugContext,
"Wrote %d bytes to %s\n", ret, filename);
#endif
}
error:
ctxt->output = oldOutput;
ctxt->insert = oldInsert;
ctxt->type = oldType;
ctxt->outputFile = oldOutputFile;
if (URL != NULL)
xmlFree(URL);
if (filename != NULL)
xmlFree(filename);
if (style != NULL)
xsltFreeStylesheet(style);
if (res != NULL)
xmlFreeDoc(res);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int aead_null_givdecrypt(struct aead_givcrypt_request *req)
{
return crypto_aead_decrypt(&req->areq);
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ceph_aes_encrypt(const void *key, int key_len,
void *dst, size_t *dst_len,
const void *src, size_t src_len)
{
struct scatterlist sg_in[2], prealloc_sg;
struct sg_table sg_out;
struct crypto_skcipher *tfm = ceph_crypto_alloc_cipher();
SKCIPHER_REQUEST_ON_STACK(req, tfm);
int ret;
char iv[AES_BLOCK_SIZE];
size_t zero_padding = (0x10 - (src_len & 0x0f));
char pad[16];
if (IS_ERR(tfm))
return PTR_ERR(tfm);
memset(pad, zero_padding, zero_padding);
*dst_len = src_len + zero_padding;
sg_init_table(sg_in, 2);
sg_set_buf(&sg_in[0], src, src_len);
sg_set_buf(&sg_in[1], pad, zero_padding);
ret = setup_sgtable(&sg_out, &prealloc_sg, dst, *dst_len);
if (ret)
goto out_tfm;
crypto_skcipher_setkey((void *)tfm, key, key_len);
memcpy(iv, aes_iv, AES_BLOCK_SIZE);
skcipher_request_set_tfm(req, tfm);
skcipher_request_set_callback(req, 0, NULL, NULL);
skcipher_request_set_crypt(req, sg_in, sg_out.sgl,
src_len + zero_padding, iv);
/*
print_hex_dump(KERN_ERR, "enc key: ", DUMP_PREFIX_NONE, 16, 1,
key, key_len, 1);
print_hex_dump(KERN_ERR, "enc src: ", DUMP_PREFIX_NONE, 16, 1,
src, src_len, 1);
print_hex_dump(KERN_ERR, "enc pad: ", DUMP_PREFIX_NONE, 16, 1,
pad, zero_padding, 1);
*/
ret = crypto_skcipher_encrypt(req);
skcipher_request_zero(req);
if (ret < 0) {
pr_err("ceph_aes_crypt failed %d\n", ret);
goto out_sg;
}
/*
print_hex_dump(KERN_ERR, "enc out: ", DUMP_PREFIX_NONE, 16, 1,
dst, *dst_len, 1);
*/
out_sg:
teardown_sgtable(&sg_out);
out_tfm:
crypto_free_skcipher(tfm);
return ret;
}
Commit Message: libceph: introduce ceph_crypt() for in-place en/decryption
Starting with 4.9, kernel stacks may be vmalloced and therefore not
guaranteed to be physically contiguous; the new CONFIG_VMAP_STACK
option is enabled by default on x86. This makes it invalid to use
on-stack buffers with the crypto scatterlist API, as sg_set_buf()
expects a logical address and won't work with vmalloced addresses.
There isn't a different (e.g. kvec-based) crypto API we could switch
net/ceph/crypto.c to and the current scatterlist.h API isn't getting
updated to accommodate this use case. Allocating a new header and
padding for each operation is a non-starter, so do the en/decryption
in-place on a single pre-assembled (header + data + padding) heap
buffer. This is explicitly supported by the crypto API:
"... the caller may provide the same scatter/gather list for the
plaintext and cipher text. After the completion of the cipher
operation, the plaintext data is replaced with the ciphertext data
in case of an encryption and vice versa for a decryption."
Signed-off-by: Ilya Dryomov <[email protected]>
Reviewed-by: Sage Weil <[email protected]>
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
one;
ssize_t
count,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count == 0) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
(void) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=1UL*ReadBlobByte(image);
bits_per_pixel=1UL*ReadBlobByte(image);
number_colormaps=1UL*ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 64)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((number_pixels*number_planes) != (size_t) (number_pixels*number_planes))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*number_planes*
sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
p=pixels+((image->rows-y-1)*image->columns*number_planes)+
x*number_planes+plane;
operand++;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=(int) ReadBlobLSBShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
p=pixels+((image->rows-y-1)*image->columns*number_planes)+
x*number_planes+plane;
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
*p=colormap[*p & mask];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
*p=colormap[x*map_length+(*p & mask)];
p++;
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,image->colormap[*p++].red);
SetPixelGreen(q,image->colormap[*p++].green);
SetPixelBlue(q,image->colormap[*p++].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int xts_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst,
struct scatterlist *src, unsigned int nbytes)
{
struct twofish_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
be128 buf[3];
struct xts_crypt_req req = {
.tbuf = buf,
.tbuflen = sizeof(buf),
.tweak_ctx = &ctx->tweak_ctx,
.tweak_fn = XTS_TWEAK_CAST(twofish_enc_blk),
.crypt_ctx = &ctx->crypt_ctx,
.crypt_fn = decrypt_callback,
};
return xts_crypt(desc, dst, src, nbytes, &req);
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline int open_to_namei_flags(int flag)
{
if ((flag+1) & O_ACCMODE)
flag++;
return flag;
}
Commit Message: fix autofs/afs/etc. magic mountpoint breakage
We end up trying to kfree() nd.last.name on open("/mnt/tmp", O_CREAT)
if /mnt/tmp is an autofs direct mount. The reason is that nd.last_type
is bogus here; we want LAST_BIND for everything of that kind and we
get LAST_NORM left over from finding parent directory.
So make sure that it *is* set properly; set to LAST_BIND before
doing ->follow_link() - for normal symlinks it will be changed
by __vfs_follow_link() and everything else needs it set that way.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool BlockEntry::EOS() const
{
return (GetKind() == kBlockEOS);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool MediaPlayerService::AudioOutput::isOnEmulator()
{
setMinBufferCount(); // benign race wrt other threads
return mIsOnEmulator;
}
Commit Message: MediaPlayerService: avoid invalid static cast
Bug: 30204103
Change-Id: Ie0dd3568a375f1e9fed8615ad3d85184bcc99028
(cherry picked from commit ee0a0e39acdcf8f97e0d6945c31ff36a06a36e9d)
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int mpi_powm(MPI res, MPI base, MPI exp, MPI mod)
{
mpi_ptr_t mp_marker = NULL, bp_marker = NULL, ep_marker = NULL;
mpi_ptr_t xp_marker = NULL;
mpi_ptr_t tspace = NULL;
mpi_ptr_t rp, ep, mp, bp;
mpi_size_t esize, msize, bsize, rsize;
int esign, msign, bsign, rsign;
mpi_size_t size;
int mod_shift_cnt;
int negative_result;
int assign_rp = 0;
mpi_size_t tsize = 0; /* to avoid compiler warning */
/* fixme: we should check that the warning is void */
int rc = -ENOMEM;
esize = exp->nlimbs;
msize = mod->nlimbs;
size = 2 * msize;
esign = exp->sign;
msign = mod->sign;
rp = res->d;
ep = exp->d;
if (!msize)
return -EINVAL;
if (!esize) {
/* Exponent is zero, result is 1 mod MOD, i.e., 1 or 0
* depending on if MOD equals 1. */
rp[0] = 1;
res->nlimbs = (msize == 1 && mod->d[0] == 1) ? 0 : 1;
res->sign = 0;
goto leave;
}
/* Normalize MOD (i.e. make its most significant bit set) as required by
* mpn_divrem. This will make the intermediate values in the calculation
* slightly larger, but the correct result is obtained after a final
* reduction using the original MOD value. */
mp = mp_marker = mpi_alloc_limb_space(msize);
if (!mp)
goto enomem;
mod_shift_cnt = count_leading_zeros(mod->d[msize - 1]);
if (mod_shift_cnt)
mpihelp_lshift(mp, mod->d, msize, mod_shift_cnt);
else
MPN_COPY(mp, mod->d, msize);
bsize = base->nlimbs;
bsign = base->sign;
if (bsize > msize) { /* The base is larger than the module. Reduce it. */
/* Allocate (BSIZE + 1) with space for remainder and quotient.
* (The quotient is (bsize - msize + 1) limbs.) */
bp = bp_marker = mpi_alloc_limb_space(bsize + 1);
if (!bp)
goto enomem;
MPN_COPY(bp, base->d, bsize);
/* We don't care about the quotient, store it above the remainder,
* at BP + MSIZE. */
mpihelp_divrem(bp + msize, 0, bp, bsize, mp, msize);
bsize = msize;
/* Canonicalize the base, since we are going to multiply with it
* quite a few times. */
MPN_NORMALIZE(bp, bsize);
} else
bp = base->d;
if (!bsize) {
res->nlimbs = 0;
res->sign = 0;
goto leave;
}
if (res->alloced < size) {
/* We have to allocate more space for RES. If any of the input
* parameters are identical to RES, defer deallocation of the old
* space. */
if (rp == ep || rp == mp || rp == bp) {
rp = mpi_alloc_limb_space(size);
if (!rp)
goto enomem;
assign_rp = 1;
} else {
if (mpi_resize(res, size) < 0)
goto enomem;
rp = res->d;
}
} else { /* Make BASE, EXP and MOD not overlap with RES. */
if (rp == bp) {
/* RES and BASE are identical. Allocate temp. space for BASE. */
BUG_ON(bp_marker);
bp = bp_marker = mpi_alloc_limb_space(bsize);
if (!bp)
goto enomem;
MPN_COPY(bp, rp, bsize);
}
if (rp == ep) {
/* RES and EXP are identical. Allocate temp. space for EXP. */
ep = ep_marker = mpi_alloc_limb_space(esize);
if (!ep)
goto enomem;
MPN_COPY(ep, rp, esize);
}
if (rp == mp) {
/* RES and MOD are identical. Allocate temporary space for MOD. */
BUG_ON(mp_marker);
mp = mp_marker = mpi_alloc_limb_space(msize);
if (!mp)
goto enomem;
MPN_COPY(mp, rp, msize);
}
}
MPN_COPY(rp, bp, bsize);
rsize = bsize;
rsign = bsign;
{
mpi_size_t i;
mpi_ptr_t xp;
int c;
mpi_limb_t e;
mpi_limb_t carry_limb;
struct karatsuba_ctx karactx;
xp = xp_marker = mpi_alloc_limb_space(2 * (msize + 1));
if (!xp)
goto enomem;
memset(&karactx, 0, sizeof karactx);
negative_result = (ep[0] & 1) && base->sign;
i = esize - 1;
e = ep[i];
c = count_leading_zeros(e);
e = (e << c) << 1; /* shift the exp bits to the left, lose msb */
c = BITS_PER_MPI_LIMB - 1 - c;
/* Main loop.
*
* Make the result be pointed to alternately by XP and RP. This
* helps us avoid block copying, which would otherwise be necessary
* with the overlap restrictions of mpihelp_divmod. With 50% probability
* the result after this loop will be in the area originally pointed
* by RP (==RES->d), and with 50% probability in the area originally
* pointed to by XP.
*/
for (;;) {
while (c) {
mpi_ptr_t tp;
mpi_size_t xsize;
/*if (mpihelp_mul_n(xp, rp, rp, rsize) < 0) goto enomem */
if (rsize < KARATSUBA_THRESHOLD)
mpih_sqr_n_basecase(xp, rp, rsize);
else {
if (!tspace) {
tsize = 2 * rsize;
tspace =
mpi_alloc_limb_space(tsize);
if (!tspace)
goto enomem;
} else if (tsize < (2 * rsize)) {
mpi_free_limb_space(tspace);
tsize = 2 * rsize;
tspace =
mpi_alloc_limb_space(tsize);
if (!tspace)
goto enomem;
}
mpih_sqr_n(xp, rp, rsize, tspace);
}
xsize = 2 * rsize;
if (xsize > msize) {
mpihelp_divrem(xp + msize, 0, xp, xsize,
mp, msize);
xsize = msize;
}
tp = rp;
rp = xp;
xp = tp;
rsize = xsize;
if ((mpi_limb_signed_t) e < 0) {
/*mpihelp_mul( xp, rp, rsize, bp, bsize ); */
if (bsize < KARATSUBA_THRESHOLD) {
mpi_limb_t tmp;
if (mpihelp_mul
(xp, rp, rsize, bp, bsize,
&tmp) < 0)
goto enomem;
} else {
if (mpihelp_mul_karatsuba_case
(xp, rp, rsize, bp, bsize,
&karactx) < 0)
goto enomem;
}
xsize = rsize + bsize;
if (xsize > msize) {
mpihelp_divrem(xp + msize, 0,
xp, xsize, mp,
msize);
xsize = msize;
}
tp = rp;
rp = xp;
xp = tp;
rsize = xsize;
}
e <<= 1;
c--;
}
i--;
if (i < 0)
break;
e = ep[i];
c = BITS_PER_MPI_LIMB;
}
/* We shifted MOD, the modulo reduction argument, left MOD_SHIFT_CNT
* steps. Adjust the result by reducing it with the original MOD.
*
* Also make sure the result is put in RES->d (where it already
* might be, see above).
*/
if (mod_shift_cnt) {
carry_limb =
mpihelp_lshift(res->d, rp, rsize, mod_shift_cnt);
rp = res->d;
if (carry_limb) {
rp[rsize] = carry_limb;
rsize++;
}
} else {
MPN_COPY(res->d, rp, rsize);
rp = res->d;
}
if (rsize >= msize) {
mpihelp_divrem(rp + msize, 0, rp, rsize, mp, msize);
rsize = msize;
}
/* Remove any leading zero words from the result. */
if (mod_shift_cnt)
mpihelp_rshift(rp, rp, rsize, mod_shift_cnt);
MPN_NORMALIZE(rp, rsize);
mpihelp_release_karatsuba_ctx(&karactx);
}
if (negative_result && rsize) {
if (mod_shift_cnt)
mpihelp_rshift(mp, mp, msize, mod_shift_cnt);
mpihelp_sub(rp, mp, msize, rp, rsize);
rsize = msize;
rsign = msign;
MPN_NORMALIZE(rp, rsize);
}
res->nlimbs = rsize;
res->sign = rsign;
leave:
rc = 0;
enomem:
if (assign_rp)
mpi_assign_limb_space(res, rp, size);
if (mp_marker)
mpi_free_limb_space(mp_marker);
if (bp_marker)
mpi_free_limb_space(bp_marker);
if (ep_marker)
mpi_free_limb_space(ep_marker);
if (xp_marker)
mpi_free_limb_space(xp_marker);
if (tspace)
mpi_free_limb_space(tspace);
return rc;
}
Commit Message: mpi: Fix NULL ptr dereference in mpi_powm() [ver #3]
This fixes CVE-2016-8650.
If mpi_powm() is given a zero exponent, it wants to immediately return
either 1 or 0, depending on the modulus. However, if the result was
initalised with zero limb space, no limbs space is allocated and a
NULL-pointer exception ensues.
Fix this by allocating a minimal amount of limb space for the result when
the 0-exponent case when the result is 1 and not touching the limb space
when the result is 0.
This affects the use of RSA keys and X.509 certificates that carry them.
BUG: unable to handle kernel NULL pointer dereference at (null)
IP: [<ffffffff8138ce5d>] mpi_powm+0x32/0x7e6
PGD 0
Oops: 0002 [#1] SMP
Modules linked in:
CPU: 3 PID: 3014 Comm: keyctl Not tainted 4.9.0-rc6-fscache+ #278
Hardware name: ASUS All Series/H97-PLUS, BIOS 2306 10/09/2014
task: ffff8804011944c0 task.stack: ffff880401294000
RIP: 0010:[<ffffffff8138ce5d>] [<ffffffff8138ce5d>] mpi_powm+0x32/0x7e6
RSP: 0018:ffff880401297ad8 EFLAGS: 00010212
RAX: 0000000000000000 RBX: ffff88040868bec0 RCX: ffff88040868bba0
RDX: ffff88040868b260 RSI: ffff88040868bec0 RDI: ffff88040868bee0
RBP: ffff880401297ba8 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000047 R11: ffffffff8183b210 R12: 0000000000000000
R13: ffff8804087c7600 R14: 000000000000001f R15: ffff880401297c50
FS: 00007f7a7918c700(0000) GS:ffff88041fb80000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000000000000000 CR3: 0000000401250000 CR4: 00000000001406e0
Stack:
ffff88040868bec0 0000000000000020 ffff880401297b00 ffffffff81376cd4
0000000000000100 ffff880401297b10 ffffffff81376d12 ffff880401297b30
ffffffff81376f37 0000000000000100 0000000000000000 ffff880401297ba8
Call Trace:
[<ffffffff81376cd4>] ? __sg_page_iter_next+0x43/0x66
[<ffffffff81376d12>] ? sg_miter_get_next_page+0x1b/0x5d
[<ffffffff81376f37>] ? sg_miter_next+0x17/0xbd
[<ffffffff8138ba3a>] ? mpi_read_raw_from_sgl+0xf2/0x146
[<ffffffff8132a95c>] rsa_verify+0x9d/0xee
[<ffffffff8132acca>] ? pkcs1pad_sg_set_buf+0x2e/0xbb
[<ffffffff8132af40>] pkcs1pad_verify+0xc0/0xe1
[<ffffffff8133cb5e>] public_key_verify_signature+0x1b0/0x228
[<ffffffff8133d974>] x509_check_for_self_signed+0xa1/0xc4
[<ffffffff8133cdde>] x509_cert_parse+0x167/0x1a1
[<ffffffff8133d609>] x509_key_preparse+0x21/0x1a1
[<ffffffff8133c3d7>] asymmetric_key_preparse+0x34/0x61
[<ffffffff812fc9f3>] key_create_or_update+0x145/0x399
[<ffffffff812fe227>] SyS_add_key+0x154/0x19e
[<ffffffff81001c2b>] do_syscall_64+0x80/0x191
[<ffffffff816825e4>] entry_SYSCALL64_slow_path+0x25/0x25
Code: 56 41 55 41 54 53 48 81 ec a8 00 00 00 44 8b 71 04 8b 42 04 4c 8b 67 18 45 85 f6 89 45 80 0f 84 b4 06 00 00 85 c0 75 2f 41 ff ce <49> c7 04 24 01 00 00 00 b0 01 75 0b 48 8b 41 18 48 83 38 01 0f
RIP [<ffffffff8138ce5d>] mpi_powm+0x32/0x7e6
RSP <ffff880401297ad8>
CR2: 0000000000000000
---[ end trace d82015255d4a5d8d ]---
Basically, this is a backport of a libgcrypt patch:
http://git.gnupg.org/cgi-bin/gitweb.cgi?p=libgcrypt.git;a=patch;h=6e1adb05d290aeeb1c230c763970695f4a538526
Fixes: cdec9cb5167a ("crypto: GnuPG based MPI lib - source files (part 1)")
Signed-off-by: Andrey Ryabinin <[email protected]>
Signed-off-by: David Howells <[email protected]>
cc: Dmitry Kasatkin <[email protected]>
cc: [email protected]
cc: [email protected]
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void ImportCbYCrYQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 10:
{
Quantum
cbcr[4];
pixel=0;
if (quantum_info->pack == MagickFalse)
{
register ssize_t
i;
size_t
quantum;
ssize_t
n;
n=0;
quantum=0;
for (x=0; x < (ssize_t) number_pixels; x+=2)
{
for (i=0; i < 4; i++)
{
switch (n % 3)
{
case 0:
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 22) & 0x3ff) << 6)));
break;
}
case 1:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 12) & 0x3ff) << 6)));
break;
}
case 2:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 2) & 0x3ff) << 6)));
break;
}
}
cbcr[i]=(Quantum) (quantum);
n++;
}
p+=quantum_info->pad;
SetPixelRed(image,cbcr[1],q);
SetPixelGreen(image,cbcr[0],q);
SetPixelBlue(image,cbcr[2],q);
q+=GetPixelChannels(image);
SetPixelRed(image,cbcr[3],q);
SetPixelGreen(image,cbcr[0],q);
SetPixelBlue(image,cbcr[2],q);
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/126
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void tcp_v4_reqsk_send_ack(const struct sock *sk, struct sk_buff *skb,
struct request_sock *req)
{
/* sk->sk_state == TCP_LISTEN -> for regular TCP_SYN_RECV
* sk->sk_state == TCP_SYN_RECV -> for Fast Open.
*/
u32 seq = (sk->sk_state == TCP_LISTEN) ? tcp_rsk(req)->snt_isn + 1 :
tcp_sk(sk)->snd_nxt;
/* RFC 7323 2.3
* The window field (SEG.WND) of every outgoing segment, with the
* exception of <SYN> segments, MUST be right-shifted by
* Rcv.Wind.Shift bits:
*/
tcp_v4_send_ack(sock_net(sk), skb, seq,
tcp_rsk(req)->rcv_nxt,
req->rsk_rcv_wnd >> inet_rsk(req)->rcv_wscale,
tcp_time_stamp,
req->ts_recent,
0,
tcp_md5_do_lookup(sk, (union tcp_md5_addr *)&ip_hdr(skb)->daddr,
AF_INET),
inet_rsk(req)->no_srccheck ? IP_REPLY_ARG_NOSRCCHECK : 0,
ip_hdr(skb)->tos);
}
Commit Message: tcp: take care of truncations done by sk_filter()
With syzkaller help, Marco Grassi found a bug in TCP stack,
crashing in tcp_collapse()
Root cause is that sk_filter() can truncate the incoming skb,
but TCP stack was not really expecting this to happen.
It probably was expecting a simple DROP or ACCEPT behavior.
We first need to make sure no part of TCP header could be removed.
Then we need to adjust TCP_SKB_CB(skb)->end_seq
Many thanks to syzkaller team and Marco for giving us a reproducer.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Marco Grassi <[email protected]>
Reported-by: Vladis Dronov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-284
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p,
int *got_frame, uint8_t *data_start,
unsigned int data_size)
{
WebPContext *s = avctx->priv_data;
AVPacket pkt;
int ret;
if (!s->initialized) {
ff_vp8_decode_init(avctx);
s->initialized = 1;
if (s->has_alpha)
avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
}
s->lossless = 0;
if (data_size > INT_MAX) {
av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n");
return AVERROR_PATCHWELCOME;
}
av_init_packet(&pkt);
pkt.data = data_start;
pkt.size = data_size;
ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt);
if (ret < 0)
return ret;
update_canvas_size(avctx, avctx->width, avctx->height);
if (s->has_alpha) {
ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data,
s->alpha_data_size);
if (ret < 0)
return ret;
}
return ret;
}
Commit Message: avcodec/webp: Always set pix_fmt
Fixes: out of array access
Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632
Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Reviewed-by: "Ronald S. Bultje" <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name)
{
unsigned upper_length;
int len, type, optlen;
char *dest, *ret;
/* option points to OPT_DATA, need to go back to get OPT_LEN */
len = option[-OPT_DATA + OPT_LEN];
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
* ((unsigned)(len + optlen - 1) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name);
while (len >= optlen) {
switch (type) {
case OPTION_IP:
case OPTION_IP_PAIR:
dest += sprint_nip(dest, "", option);
if (type == OPTION_IP)
break;
dest += sprint_nip(dest, "/", option + 4);
break;
case OPTION_U8:
dest += sprintf(dest, "%u", *option);
break;
case OPTION_U16: {
uint16_t val_u16;
move_from_unaligned16(val_u16, option);
dest += sprintf(dest, "%u", ntohs(val_u16));
break;
}
case OPTION_S32:
case OPTION_U32: {
uint32_t val_u32;
move_from_unaligned32(val_u32, option);
dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32));
break;
}
/* Note: options which use 'return' instead of 'break'
* (for example, OPTION_STRING) skip the code which handles
* the case of list of options.
*/
case OPTION_STRING:
case OPTION_STRING_HOST:
memcpy(dest, option, len);
dest[len] = '\0';
if (type == OPTION_STRING_HOST && !good_hostname(dest))
safe_strncpy(dest, "bad", len);
return ret;
case OPTION_STATIC_ROUTES: {
/* Option binary format:
* mask [one byte, 0..32]
* ip [big endian, 0..4 bytes depending on mask]
* router [big endian, 4 bytes]
* may be repeated
*
* We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2"
*/
const char *pfx = "";
while (len >= 1 + 4) { /* mask + 0-byte ip + router */
uint32_t nip;
uint8_t *p;
unsigned mask;
int bytes;
mask = *option++;
if (mask > 32)
break;
len--;
nip = 0;
p = (void*) &nip;
bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */
while (--bytes >= 0) {
*p++ = *option++;
len--;
}
if (len < 4)
break;
/* print ip/mask */
dest += sprint_nip(dest, pfx, (void*) &nip);
pfx = " ";
dest += sprintf(dest, "/%u ", mask);
/* print router */
dest += sprint_nip(dest, "", option);
option += 4;
len -= 4;
}
return ret;
}
case OPTION_6RD:
/* Option binary format (see RFC 5969):
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 6rdPrefix |
* ... (16 octets) ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* ... 6rdBRIPv4Address(es) ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* We convert it to a string
* "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..."
*
* Sanity check: ensure that our length is at least 22 bytes, that
* IPv4MaskLen <= 32,
* 6rdPrefixLen <= 128,
* 6rdPrefixLen + (32 - IPv4MaskLen) <= 128
* (2nd condition need no check - it follows from 1st and 3rd).
* Else, return envvar with empty value ("optname=")
*/
if (len >= (1 + 1 + 16 + 4)
&& option[0] <= 32
&& (option[1] + 32 - option[0]) <= 128
) {
/* IPv4MaskLen */
dest += sprintf(dest, "%u ", *option++);
/* 6rdPrefixLen */
dest += sprintf(dest, "%u ", *option++);
/* 6rdPrefix */
dest += sprint_nip6(dest, /* "", */ option);
option += 16;
len -= 1 + 1 + 16 + 4;
/* "+ 4" above corresponds to the length of IPv4 addr
* we consume in the loop below */
while (1) {
/* 6rdBRIPv4Address(es) */
dest += sprint_nip(dest, " ", option);
option += 4;
len -= 4; /* do we have yet another 4+ bytes? */
if (len < 0)
break; /* no */
}
}
return ret;
#if ENABLE_FEATURE_UDHCP_RFC3397
case OPTION_DNS_STRING:
/* unpack option into dest; use ret for prefix (i.e., "optname=") */
dest = dname_dec(option, len, ret);
if (dest) {
free(ret);
return dest;
}
/* error. return "optname=" string */
return ret;
case OPTION_SIP_SERVERS:
/* Option binary format:
* type: byte
* type=0: domain names, dns-compressed
* type=1: IP addrs
*/
option++;
len--;
if (option[-1] == 0) {
dest = dname_dec(option, len, ret);
if (dest) {
free(ret);
return dest;
}
} else
if (option[-1] == 1) {
const char *pfx = "";
while (1) {
len -= 4;
if (len < 0)
break;
dest += sprint_nip(dest, pfx, option);
pfx = " ";
option += 4;
}
}
return ret;
#endif
} /* switch */
/* If we are here, try to format any remaining data
* in the option as another, similarly-formatted option
*/
option += optlen;
len -= optlen;
if (len < optlen /* || !(optflag->flags & OPTION_LIST) */)
break;
*dest++ = ' ';
*dest = '\0';
} /* while */
return ret;
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,
key_perm_t perm)
{
struct keyring_search_context ctx = {
.match_data.cmp = lookup_user_key_possessed,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_NO_STATE_CHECK,
};
struct request_key_auth *rka;
struct key *key;
key_ref_t key_ref, skey_ref;
int ret;
try_again:
ctx.cred = get_current_cred();
key_ref = ERR_PTR(-ENOKEY);
switch (id) {
case KEY_SPEC_THREAD_KEYRING:
if (!ctx.cred->thread_keyring) {
if (!(lflags & KEY_LOOKUP_CREATE))
goto error;
ret = install_thread_keyring();
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error;
}
goto reget_creds;
}
key = ctx.cred->thread_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_PROCESS_KEYRING:
if (!ctx.cred->process_keyring) {
if (!(lflags & KEY_LOOKUP_CREATE))
goto error;
ret = install_process_keyring();
if (ret < 0) {
key_ref = ERR_PTR(ret);
goto error;
}
goto reget_creds;
}
key = ctx.cred->process_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_SESSION_KEYRING:
if (!ctx.cred->session_keyring) {
/* always install a session keyring upon access if one
* doesn't exist yet */
ret = install_user_keyrings();
if (ret < 0)
goto error;
if (lflags & KEY_LOOKUP_CREATE)
ret = join_session_keyring(NULL);
else
ret = install_session_keyring(
ctx.cred->user->session_keyring);
if (ret < 0)
goto error;
goto reget_creds;
} else if (ctx.cred->session_keyring ==
ctx.cred->user->session_keyring &&
lflags & KEY_LOOKUP_CREATE) {
ret = join_session_keyring(NULL);
if (ret < 0)
goto error;
goto reget_creds;
}
rcu_read_lock();
key = rcu_dereference(ctx.cred->session_keyring);
__key_get(key);
rcu_read_unlock();
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_USER_KEYRING:
if (!ctx.cred->user->uid_keyring) {
ret = install_user_keyrings();
if (ret < 0)
goto error;
}
key = ctx.cred->user->uid_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_USER_SESSION_KEYRING:
if (!ctx.cred->user->session_keyring) {
ret = install_user_keyrings();
if (ret < 0)
goto error;
}
key = ctx.cred->user->session_keyring;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_GROUP_KEYRING:
/* group keyrings are not yet supported */
key_ref = ERR_PTR(-EINVAL);
goto error;
case KEY_SPEC_REQKEY_AUTH_KEY:
key = ctx.cred->request_key_auth;
if (!key)
goto error;
__key_get(key);
key_ref = make_key_ref(key, 1);
break;
case KEY_SPEC_REQUESTOR_KEYRING:
if (!ctx.cred->request_key_auth)
goto error;
down_read(&ctx.cred->request_key_auth->sem);
if (test_bit(KEY_FLAG_REVOKED,
&ctx.cred->request_key_auth->flags)) {
key_ref = ERR_PTR(-EKEYREVOKED);
key = NULL;
} else {
rka = ctx.cred->request_key_auth->payload.data[0];
key = rka->dest_keyring;
__key_get(key);
}
up_read(&ctx.cred->request_key_auth->sem);
if (!key)
goto error;
key_ref = make_key_ref(key, 1);
break;
default:
key_ref = ERR_PTR(-EINVAL);
if (id < 1)
goto error;
key = key_lookup(id);
if (IS_ERR(key)) {
key_ref = ERR_CAST(key);
goto error;
}
key_ref = make_key_ref(key, 0);
/* check to see if we possess the key */
ctx.index_key.type = key->type;
ctx.index_key.description = key->description;
ctx.index_key.desc_len = strlen(key->description);
ctx.match_data.raw_data = key;
kdebug("check possessed");
skey_ref = search_process_keyrings(&ctx);
kdebug("possessed=%p", skey_ref);
if (!IS_ERR(skey_ref)) {
key_put(key);
key_ref = skey_ref;
}
break;
}
/* unlink does not use the nominated key in any way, so can skip all
* the permission checks as it is only concerned with the keyring */
if (lflags & KEY_LOOKUP_FOR_UNLINK) {
ret = 0;
goto error;
}
if (!(lflags & KEY_LOOKUP_PARTIAL)) {
ret = wait_for_key_construction(key, true);
switch (ret) {
case -ERESTARTSYS:
goto invalid_key;
default:
if (perm)
goto invalid_key;
case 0:
break;
}
} else if (perm) {
ret = key_validate(key);
if (ret < 0)
goto invalid_key;
}
ret = -EIO;
if (!(lflags & KEY_LOOKUP_PARTIAL) &&
!test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
goto invalid_key;
/* check the permissions */
ret = key_task_permission(key_ref, ctx.cred, perm);
if (ret < 0)
goto invalid_key;
key->last_used_at = current_kernel_time().tv_sec;
error:
put_cred(ctx.cred);
return key_ref;
invalid_key:
key_ref_put(key_ref);
key_ref = ERR_PTR(ret);
goto error;
/* if we attempted to install a keyring, then it may have caused new
* creds to be installed */
reget_creds:
put_cred(ctx.cred);
goto try_again;
}
Commit Message: KEYS: Fix keyring ref leak in join_session_keyring()
This fixes CVE-2016-0728.
If a thread is asked to join as a session keyring the keyring that's already
set as its session, we leak a keyring reference.
This can be tested with the following program:
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <keyutils.h>
int main(int argc, const char *argv[])
{
int i = 0;
key_serial_t serial;
serial = keyctl(KEYCTL_JOIN_SESSION_KEYRING,
"leaked-keyring");
if (serial < 0) {
perror("keyctl");
return -1;
}
if (keyctl(KEYCTL_SETPERM, serial,
KEY_POS_ALL | KEY_USR_ALL) < 0) {
perror("keyctl");
return -1;
}
for (i = 0; i < 100; i++) {
serial = keyctl(KEYCTL_JOIN_SESSION_KEYRING,
"leaked-keyring");
if (serial < 0) {
perror("keyctl");
return -1;
}
}
return 0;
}
If, after the program has run, there something like the following line in
/proc/keys:
3f3d898f I--Q--- 100 perm 3f3f0000 0 0 keyring leaked-keyring: empty
with a usage count of 100 * the number of times the program has been run,
then the kernel is malfunctioning. If leaked-keyring has zero usages or
has been garbage collected, then the problem is fixed.
Reported-by: Yevgeny Pats <[email protected]>
Signed-off-by: David Howells <[email protected]>
Acked-by: Don Zickus <[email protected]>
Acked-by: Prarit Bhargava <[email protected]>
Acked-by: Jarod Wilson <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void gdImageWBMP (gdImagePtr im, int fg, FILE * outFile)
{
gdIOCtx *out = gdNewFileCtx(outFile);
gdImageWBMPCtx(im, fg, out);
out->gd_free(out);
}
Commit Message: Sync with upstream
Even though libgd/libgd#492 is not a relevant bug fix for PHP, since
the binding doesn't use the `gdImage*Ptr()` functions at all, we're
porting the fix to stay in sync here.
CWE ID: CWE-415
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters)
{
FILE *f = NULL;
int w, h, prec;
int i, numcomps, max;
OPJ_COLOR_SPACE color_space;
opj_image_cmptparm_t cmptparm; /* maximum of 1 component */
opj_image_t * image = NULL;
int adjustS, ushift, dshift, force8;
char endian1, endian2, sign;
char signtmp[32];
char temp[32];
int bigendian;
opj_image_comp_t *comp = NULL;
numcomps = 1;
color_space = OPJ_CLRSPC_GRAY;
memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t));
max = 0;
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Failed to open %s for reading !\n", filename);
return NULL;
}
fseek(f, 0, SEEK_SET);
if (fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d", temp, &endian1,
&endian2, signtmp, &prec, temp, &w, temp, &h) != 9) {
fclose(f);
fprintf(stderr,
"ERROR: Failed to read the right number of element from the fscanf() function!\n");
return NULL;
}
i = 0;
sign = '+';
while (signtmp[i] != '\0') {
if (signtmp[i] == '-') {
sign = '-';
}
i++;
}
fgetc(f);
if (endian1 == 'M' && endian2 == 'L') {
bigendian = 1;
} else if (endian2 == 'M' && endian1 == 'L') {
bigendian = 0;
} else {
fclose(f);
fprintf(stderr, "Bad pgx header, please check input file\n");
return NULL;
}
/* initialize image component */
cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0;
cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0;
cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx +
1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx
+ 1;
cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy +
1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy
+ 1;
if (sign == '-') {
cmptparm.sgnd = 1;
} else {
cmptparm.sgnd = 0;
}
if (prec < 8) {
force8 = 1;
ushift = 8 - prec;
dshift = prec - ushift;
if (cmptparm.sgnd) {
adjustS = (1 << (prec - 1));
} else {
adjustS = 0;
}
cmptparm.sgnd = 0;
prec = 8;
} else {
ushift = dshift = force8 = adjustS = 0;
}
cmptparm.prec = (OPJ_UINT32)prec;
cmptparm.bpp = (OPJ_UINT32)prec;
cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx;
cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy;
/* create the image */
image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space);
if (!image) {
fclose(f);
return NULL;
}
/* set image offset and reference grid */
image->x0 = cmptparm.x0;
image->y0 = cmptparm.x0;
image->x1 = cmptparm.w;
image->y1 = cmptparm.h;
/* set image data */
comp = &image->comps[0];
for (i = 0; i < w * h; i++) {
int v;
if (force8) {
v = readuchar(f) + adjustS;
v = (v << ushift) + (v >> dshift);
comp->data[i] = (unsigned char)v;
if (v > max) {
max = v;
}
continue;
}
if (comp->prec == 8) {
if (!comp->sgnd) {
v = readuchar(f);
} else {
v = (char) readuchar(f);
}
} else if (comp->prec <= 16) {
if (!comp->sgnd) {
v = readushort(f, bigendian);
} else {
v = (short) readushort(f, bigendian);
}
} else {
if (!comp->sgnd) {
v = (int)readuint(f, bigendian);
} else {
v = (int) readuint(f, bigendian);
}
}
if (v > max) {
max = v;
}
comp->data[i] = v;
}
fclose(f);
comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1;
return image;
}
Commit Message: pgxtoimage(): fix write stack buffer overflow (#997)
CWE ID: CWE-787
Target: 1
Example 2:
Code: xsltExtElementPreCompTest(xsltStylesheetPtr style, xmlNodePtr inst,
xsltTransformFunction function)
{
xsltElemPreCompPtr ret;
if (style == NULL) {
xsltTransformError(NULL, NULL, inst,
"xsltExtElementTest: no transformation context\n");
return (NULL);
}
if (testStyleData == NULL) {
xsltGenericDebug(xsltGenericDebugContext,
"xsltExtElementPreCompTest: not initialized,"
" calling xsltStyleGetExtData\n");
xsltStyleGetExtData(style, (const xmlChar *) XSLT_DEFAULT_URL);
if (testStyleData == NULL) {
xsltTransformError(NULL, style, inst,
"xsltExtElementPreCompTest: not initialized\n");
if (style != NULL)
style->errors++;
return (NULL);
}
}
if (inst == NULL) {
xsltTransformError(NULL, style, inst,
"xsltExtElementPreCompTest: no instruction\n");
if (style != NULL)
style->errors++;
return (NULL);
}
ret = xsltNewElemPreComp(style, inst, function);
return (ret);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Wait() {
message_loop_runner_->Run();
message_loop_runner_ = new MessageLoopRunner;
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_FUNCTION(mcrypt_get_iv_size)
{
char *cipher;
char *module;
int cipher_len, module_len;
char *cipher_dir_string;
char *module_dir_string;
MCRYPT td;
MCRYPT_GET_INI
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
&cipher, &cipher_len, &module, &module_len) == FAILURE) {
return;
}
td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
if (td != MCRYPT_FAILED) {
RETVAL_LONG(mcrypt_enc_get_iv_size(td));
mcrypt_module_close(td);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
Target: 1
Example 2:
Code: void ExtensionTabsZoomTest::SetUpOnMainThread() {
ExtensionTabsTest::SetUpOnMainThread();
extension_ = ExtensionBuilder("Test").Build();
}
Commit Message: Change TemporaryAddressSpoof test to not depend on PDF OpenActions.
OpenActions that navigate to URIs are going to be blocked when
https://pdfium-review.googlesource.com/c/pdfium/+/42731 relands.
It was reverted because this test was breaking and blocking the
pdfium roll into chromium.
The test will now click on a link in the PDF that navigates to the
URI.
Bug: 851821
Change-Id: I49853e99de7b989858b1962ad4a92a4168d4c2db
Reviewed-on: https://chromium-review.googlesource.com/c/1244367
Commit-Queue: Henrique Nakashima <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Reviewed-by: Devlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#596011}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method)
{
char q_user[SHORT_STRING], q_pass[SHORT_STRING];
char buf[STRING];
int rc;
if (mutt_bit_isset(idata->capabilities, LOGINDISABLED))
{
mutt_message(_("LOGIN disabled on this server."));
return IMAP_AUTH_UNAVAIL;
}
if (mutt_account_getuser(&idata->conn->account) < 0)
return IMAP_AUTH_FAILURE;
if (mutt_account_getpass(&idata->conn->account) < 0)
return IMAP_AUTH_FAILURE;
mutt_message(_("Logging in..."));
imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user);
imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass);
/* don't print the password unless we're at the ungodly debugging level
* of 5 or higher */
if (DebugLevel < IMAP_LOG_PASS)
mutt_debug(2, "Sending LOGIN command for %s...\n", idata->conn->account.user);
snprintf(buf, sizeof(buf), "LOGIN %s %s", q_user, q_pass);
rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK | IMAP_CMD_PASS);
if (!rc)
{
mutt_clear_error(); /* clear "Logging in...". fixes #3524 */
return IMAP_AUTH_SUCCESS;
}
mutt_error(_("Login failed."));
return IMAP_AUTH_FAILURE;
}
Commit Message: quote imap strings more carefully
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-77
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ExtensionTtsController::SpeakNow(Utterance* utterance) {
std::string extension_id = GetMatchingExtensionId(utterance);
if (!extension_id.empty()) {
current_utterance_ = utterance;
utterance->set_extension_id(extension_id);
ListValue args;
args.Set(0, Value::CreateStringValue(utterance->text()));
DictionaryValue* options = static_cast<DictionaryValue*>(
utterance->options()->DeepCopy());
if (options->HasKey(util::kEnqueueKey))
options->Remove(util::kEnqueueKey, NULL);
args.Set(1, options);
args.Set(2, Value::CreateIntegerValue(utterance->id()));
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
utterance->profile()->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id,
events::kOnSpeak,
json_args,
utterance->profile(),
GURL());
return;
}
GetPlatformImpl()->clear_error();
bool success = GetPlatformImpl()->Speak(
utterance->text(),
utterance->locale(),
utterance->gender(),
utterance->rate(),
utterance->pitch(),
utterance->volume());
if (!success) {
utterance->set_error(GetPlatformImpl()->error());
utterance->FinishAndDestroy();
return;
}
current_utterance_ = utterance;
CheckSpeechStatus();
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 1
Example 2:
Code: OMX_ERRORTYPE SoftOpus::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.opus",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAndroidOpus:
{
const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
(const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;
if (!isValidOMXParam(opusParams)) {
return OMX_ErrorBadParameter;
}
if (opusParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE codecs: check OMX buffer size before use in (vorbis|opus)dec
Bug: 27833616
Change-Id: I1ccdd16a00741da072527a6d13e87fd7c7fe8c54
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ZEND_API zval *_zend_ts_hash_index_add_or_update(TsHashTable *ht, zend_ulong h, zval *pData, int flag ZEND_FILE_LINE_DC)
{
zval *retval;
begin_write(ht);
retval = _zend_hash_index_add_or_update(TS_HASH(ht), h, pData, flag ZEND_FILE_LINE_RELAY_CC);
end_write(ht);
return retval;
}
Commit Message:
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int __fpu__restore_sig(void __user *buf, void __user *buf_fx, int size)
{
int ia32_fxstate = (buf != buf_fx);
struct task_struct *tsk = current;
struct fpu *fpu = &tsk->thread.fpu;
int state_size = fpu_kernel_xstate_size;
u64 xfeatures = 0;
int fx_only = 0;
ia32_fxstate &= (IS_ENABLED(CONFIG_X86_32) ||
IS_ENABLED(CONFIG_IA32_EMULATION));
if (!buf) {
fpu__clear(fpu);
return 0;
}
if (!access_ok(VERIFY_READ, buf, size))
return -EACCES;
fpu__activate_curr(fpu);
if (!static_cpu_has(X86_FEATURE_FPU))
return fpregs_soft_set(current, NULL,
0, sizeof(struct user_i387_ia32_struct),
NULL, buf) != 0;
if (use_xsave()) {
struct _fpx_sw_bytes fx_sw_user;
if (unlikely(check_for_xstate(buf_fx, buf_fx, &fx_sw_user))) {
/*
* Couldn't find the extended state information in the
* memory layout. Restore just the FP/SSE and init all
* the other extended state.
*/
state_size = sizeof(struct fxregs_state);
fx_only = 1;
trace_x86_fpu_xstate_check_failed(fpu);
} else {
state_size = fx_sw_user.xstate_size;
xfeatures = fx_sw_user.xfeatures;
}
}
if (ia32_fxstate) {
/*
* For 32-bit frames with fxstate, copy the user state to the
* thread's fpu state, reconstruct fxstate from the fsave
* header. Sanitize the copied state etc.
*/
struct fpu *fpu = &tsk->thread.fpu;
struct user_i387_ia32_struct env;
int err = 0;
/*
* Drop the current fpu which clears fpu->fpstate_active. This ensures
* that any context-switch during the copy of the new state,
* avoids the intermediate state from getting restored/saved.
* Thus avoiding the new restored state from getting corrupted.
* We will be ready to restore/save the state only after
* fpu->fpstate_active is again set.
*/
fpu__drop(fpu);
if (using_compacted_format())
err = copy_user_to_xstate(&fpu->state.xsave, buf_fx);
else
err = __copy_from_user(&fpu->state.xsave, buf_fx, state_size);
if (err || __copy_from_user(&env, buf, sizeof(env))) {
fpstate_init(&fpu->state);
trace_x86_fpu_init_state(fpu);
err = -1;
} else {
sanitize_restored_xstate(tsk, &env, xfeatures, fx_only);
}
fpu->fpstate_active = 1;
preempt_disable();
fpu__restore(fpu);
preempt_enable();
return err;
} else {
/*
* For 64-bit frames and 32-bit fsave frames, restore the user
* state to the registers directly (with exceptions handled).
*/
user_fpu_begin();
if (copy_user_to_fpregs_zeroing(buf_fx, xfeatures, fx_only)) {
fpu__clear(fpu);
return -1;
}
}
return 0;
}
Commit Message: x86/fpu: Don't let userspace set bogus xcomp_bv
On x86, userspace can use the ptrace() or rt_sigreturn() system calls to
set a task's extended state (xstate) or "FPU" registers. ptrace() can
set them for another task using the PTRACE_SETREGSET request with
NT_X86_XSTATE, while rt_sigreturn() can set them for the current task.
In either case, registers can be set to any value, but the kernel
assumes that the XSAVE area itself remains valid in the sense that the
CPU can restore it.
However, in the case where the kernel is using the uncompacted xstate
format (which it does whenever the XSAVES instruction is unavailable),
it was possible for userspace to set the xcomp_bv field in the
xstate_header to an arbitrary value. However, all bits in that field
are reserved in the uncompacted case, so when switching to a task with
nonzero xcomp_bv, the XRSTOR instruction failed with a #GP fault. This
caused the WARN_ON_FPU(err) in copy_kernel_to_xregs() to be hit. In
addition, since the error is otherwise ignored, the FPU registers from
the task previously executing on the CPU were leaked.
Fix the bug by checking that the user-supplied value of xcomp_bv is 0 in
the uncompacted case, and returning an error otherwise.
The reason for validating xcomp_bv rather than simply overwriting it
with 0 is that we want userspace to see an error if it (incorrectly)
provides an XSAVE area in compacted format rather than in uncompacted
format.
Note that as before, in case of error we clear the task's FPU state.
This is perhaps non-ideal, especially for PTRACE_SETREGSET; it might be
better to return an error before changing anything. But it seems the
"clear on error" behavior is fine for now, and it's a little tricky to
do otherwise because it would mean we couldn't simply copy the full
userspace state into kernel memory in one __copy_from_user().
This bug was found by syzkaller, which hit the above-mentioned
WARN_ON_FPU():
WARNING: CPU: 1 PID: 0 at ./arch/x86/include/asm/fpu/internal.h:373 __switch_to+0x5b5/0x5d0
CPU: 1 PID: 0 Comm: swapper/1 Not tainted 4.13.0 #453
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
task: ffff9ba2bc8e42c0 task.stack: ffffa78cc036c000
RIP: 0010:__switch_to+0x5b5/0x5d0
RSP: 0000:ffffa78cc08bbb88 EFLAGS: 00010082
RAX: 00000000fffffffe RBX: ffff9ba2b8bf2180 RCX: 00000000c0000100
RDX: 00000000ffffffff RSI: 000000005cb10700 RDI: ffff9ba2b8bf36c0
RBP: ffffa78cc08bbbd0 R08: 00000000929fdf46 R09: 0000000000000001
R10: 0000000000000000 R11: 0000000000000000 R12: ffff9ba2bc8e42c0
R13: 0000000000000000 R14: ffff9ba2b8bf3680 R15: ffff9ba2bf5d7b40
FS: 00007f7e5cb10700(0000) GS:ffff9ba2bf400000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000004005cc CR3: 0000000079fd5000 CR4: 00000000001406e0
Call Trace:
Code: 84 00 00 00 00 00 e9 11 fd ff ff 0f ff 66 0f 1f 84 00 00 00 00 00 e9 e7 fa ff ff 0f ff 66 0f 1f 84 00 00 00 00 00 e9 c2 fa ff ff <0f> ff 66 0f 1f 84 00 00 00 00 00 e9 d4 fc ff ff 66 66 2e 0f 1f
Here is a C reproducer. The expected behavior is that the program spin
forever with no output. However, on a buggy kernel running on a
processor with the "xsave" feature but without the "xsaves" feature
(e.g. Sandy Bridge through Broadwell for Intel), within a second or two
the program reports that the xmm registers were corrupted, i.e. were not
restored correctly. With CONFIG_X86_DEBUG_FPU=y it also hits the above
kernel warning.
#define _GNU_SOURCE
#include <stdbool.h>
#include <inttypes.h>
#include <linux/elf.h>
#include <stdio.h>
#include <sys/ptrace.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
int pid = fork();
uint64_t xstate[512];
struct iovec iov = { .iov_base = xstate, .iov_len = sizeof(xstate) };
if (pid == 0) {
bool tracee = true;
for (int i = 0; i < sysconf(_SC_NPROCESSORS_ONLN) && tracee; i++)
tracee = (fork() != 0);
uint32_t xmm0[4] = { [0 ... 3] = tracee ? 0x00000000 : 0xDEADBEEF };
asm volatile(" movdqu %0, %%xmm0\n"
" mov %0, %%rbx\n"
"1: movdqu %%xmm0, %0\n"
" mov %0, %%rax\n"
" cmp %%rax, %%rbx\n"
" je 1b\n"
: "+m" (xmm0) : : "rax", "rbx", "xmm0");
printf("BUG: xmm registers corrupted! tracee=%d, xmm0=%08X%08X%08X%08X\n",
tracee, xmm0[0], xmm0[1], xmm0[2], xmm0[3]);
} else {
usleep(100000);
ptrace(PTRACE_ATTACH, pid, 0, 0);
wait(NULL);
ptrace(PTRACE_GETREGSET, pid, NT_X86_XSTATE, &iov);
xstate[65] = -1;
ptrace(PTRACE_SETREGSET, pid, NT_X86_XSTATE, &iov);
ptrace(PTRACE_CONT, pid, 0, 0);
wait(NULL);
}
return 1;
}
Note: the program only tests for the bug using the ptrace() system call.
The bug can also be reproduced using the rt_sigreturn() system call, but
only when called from a 32-bit program, since for 64-bit programs the
kernel restores the FPU state from the signal frame by doing XRSTOR
directly from userspace memory (with proper error checking).
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Biggers <[email protected]>
Reviewed-by: Kees Cook <[email protected]>
Reviewed-by: Rik van Riel <[email protected]>
Acked-by: Dave Hansen <[email protected]>
Cc: <[email protected]> [v3.17+]
Cc: Andrew Morton <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Borislav Petkov <[email protected]>
Cc: Eric Biggers <[email protected]>
Cc: Fenghua Yu <[email protected]>
Cc: Kevin Hao <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Michael Halcrow <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Wanpeng Li <[email protected]>
Cc: Yu-cheng Yu <[email protected]>
Cc: [email protected]
Fixes: 0b29643a5843 ("x86/xsaves: Change compacted format xsave area header")
Link: http://lkml.kernel.org/r/[email protected]
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int qib_mmap_mem(struct vm_area_struct *vma, struct qib_ctxtdata *rcd,
unsigned len, void *kvaddr, u32 write_ok, char *what)
{
struct qib_devdata *dd = rcd->dd;
unsigned long pfn;
int ret;
if ((vma->vm_end - vma->vm_start) > len) {
qib_devinfo(dd->pcidev,
"FAIL on %s: len %lx > %x\n", what,
vma->vm_end - vma->vm_start, len);
ret = -EFAULT;
goto bail;
}
/*
* shared context user code requires rcvhdrq mapped r/w, others
* only allowed readonly mapping.
*/
if (!write_ok) {
if (vma->vm_flags & VM_WRITE) {
qib_devinfo(dd->pcidev,
"%s must be mapped readonly\n", what);
ret = -EPERM;
goto bail;
}
/* don't allow them to later change with mprotect */
vma->vm_flags &= ~VM_MAYWRITE;
}
pfn = virt_to_phys(kvaddr) >> PAGE_SHIFT;
ret = remap_pfn_range(vma, vma->vm_start, pfn,
len, vma->vm_page_prot);
if (ret)
qib_devinfo(dd->pcidev,
"%s ctxt%u mmap of %lx, %x bytes failed: %d\n",
what, rcd->ctxt, pfn, len, ret);
bail:
return ret;
}
Commit Message: IB/security: Restrict use of the write() interface
The drivers/infiniband stack uses write() as a replacement for
bi-directional ioctl(). This is not safe. There are ways to
trigger write calls that result in the return structure that
is normally written to user space being shunted off to user
specified kernel memory instead.
For the immediate repair, detect and deny suspicious accesses to
the write API.
For long term, update the user space libraries and the kernel API
to something that doesn't present the same security vulnerabilities
(likely a structured ioctl() interface).
The impacted uAPI interfaces are generally only available if
hardware from drivers/infiniband is installed in the system.
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
[ Expanded check to all known write() entry points ]
Cc: [email protected]
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void disk_release_events(struct gendisk *disk)
{
/* the block count should be 1 from disk_del_events() */
WARN_ON_ONCE(disk->ev && disk->ev->block != 1);
kfree(disk->ev);
}
Commit Message: block: fix use-after-free in seq file
I got a KASAN report of use-after-free:
==================================================================
BUG: KASAN: use-after-free in klist_iter_exit+0x61/0x70 at addr ffff8800b6581508
Read of size 8 by task trinity-c1/315
=============================================================================
BUG kmalloc-32 (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in disk_seqf_start+0x66/0x110 age=144 cpu=1 pid=315
___slab_alloc+0x4f1/0x520
__slab_alloc.isra.58+0x56/0x80
kmem_cache_alloc_trace+0x260/0x2a0
disk_seqf_start+0x66/0x110
traverse+0x176/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
INFO: Freed in disk_seqf_stop+0x42/0x50 age=160 cpu=1 pid=315
__slab_free+0x17a/0x2c0
kfree+0x20a/0x220
disk_seqf_stop+0x42/0x50
traverse+0x3b5/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
CPU: 1 PID: 315 Comm: trinity-c1 Tainted: G B 4.7.0+ #62
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014
ffffea0002d96000 ffff880119b9f918 ffffffff81d6ce81 ffff88011a804480
ffff8800b6581500 ffff880119b9f948 ffffffff8146c7bd ffff88011a804480
ffffea0002d96000 ffff8800b6581500 fffffffffffffff4 ffff880119b9f970
Call Trace:
[<ffffffff81d6ce81>] dump_stack+0x65/0x84
[<ffffffff8146c7bd>] print_trailer+0x10d/0x1a0
[<ffffffff814704ff>] object_err+0x2f/0x40
[<ffffffff814754d1>] kasan_report_error+0x221/0x520
[<ffffffff8147590e>] __asan_report_load8_noabort+0x3e/0x40
[<ffffffff83888161>] klist_iter_exit+0x61/0x70
[<ffffffff82404389>] class_dev_iter_exit+0x9/0x10
[<ffffffff81d2e8ea>] disk_seqf_stop+0x3a/0x50
[<ffffffff8151f812>] seq_read+0x4b2/0x11a0
[<ffffffff815f8fdc>] proc_reg_read+0xbc/0x180
[<ffffffff814b24e4>] do_loop_readv_writev+0x134/0x210
[<ffffffff814b4c45>] do_readv_writev+0x565/0x660
[<ffffffff814b8a17>] vfs_readv+0x67/0xa0
[<ffffffff814b8de6>] do_preadv+0x126/0x170
[<ffffffff814b92ec>] SyS_preadv+0xc/0x10
This problem can occur in the following situation:
open()
- pread()
- .seq_start()
- iter = kmalloc() // succeeds
- seqf->private = iter
- .seq_stop()
- kfree(seqf->private)
- pread()
- .seq_start()
- iter = kmalloc() // fails
- .seq_stop()
- class_dev_iter_exit(seqf->private) // boom! old pointer
As the comment in disk_seqf_stop() says, stop is called even if start
failed, so we need to reinitialise the private pointer to NULL when seq
iteration stops.
An alternative would be to set the private pointer to NULL when the
kmalloc() in disk_seqf_start() fails.
Cc: [email protected]
Signed-off-by: Vegard Nossum <[email protected]>
Acked-by: Tejun Heo <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int snd_timer_close(struct snd_timer_instance *timeri)
{
struct snd_timer *timer = NULL;
struct snd_timer_instance *slave, *tmp;
if (snd_BUG_ON(!timeri))
return -ENXIO;
/* force to stop the timer */
snd_timer_stop(timeri);
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) {
/* wait, until the active callback is finished */
spin_lock_irq(&slave_active_lock);
while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
spin_unlock_irq(&slave_active_lock);
udelay(10);
spin_lock_irq(&slave_active_lock);
}
spin_unlock_irq(&slave_active_lock);
mutex_lock(®ister_mutex);
list_del(&timeri->open_list);
mutex_unlock(®ister_mutex);
} else {
timer = timeri->timer;
if (snd_BUG_ON(!timer))
goto out;
/* wait, until the active callback is finished */
spin_lock_irq(&timer->lock);
while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
spin_unlock_irq(&timer->lock);
udelay(10);
spin_lock_irq(&timer->lock);
}
spin_unlock_irq(&timer->lock);
mutex_lock(®ister_mutex);
list_del(&timeri->open_list);
if (timer && list_empty(&timer->open_list_head) &&
timer->hw.close)
timer->hw.close(timer);
/* remove slave links */
list_for_each_entry_safe(slave, tmp, &timeri->slave_list_head,
open_list) {
spin_lock_irq(&slave_active_lock);
_snd_timer_stop(slave, 1, SNDRV_TIMER_EVENT_RESOLUTION);
list_move_tail(&slave->open_list, &snd_timer_slave_list);
slave->master = NULL;
slave->timer = NULL;
spin_unlock_irq(&slave_active_lock);
}
mutex_unlock(®ister_mutex);
}
out:
if (timeri->private_free)
timeri->private_free(timeri);
kfree(timeri->owner);
kfree(timeri);
if (timer)
module_put(timer->module);
return 0;
}
Commit Message: ALSA: timer: Harden slave timer list handling
A slave timer instance might be still accessible in a racy way while
operating the master instance as it lacks of locking. Since the
master operation is mostly protected with timer->lock, we should cope
with it while changing the slave instance, too. Also, some linked
lists (active_list and ack_list) of slave instances aren't unlinked
immediately at stopping or closing, and this may lead to unexpected
accesses.
This patch tries to address these issues. It adds spin lock of
timer->lock (either from master or slave, which is equivalent) in a
few places. For avoiding a deadlock, we ensure that the global
slave_active_lock is always locked at first before each timer lock.
Also, ack and active_list of slave instances are properly unlinked at
snd_timer_stop() and snd_timer_close().
Last but not least, remove the superfluous call of _snd_timer_stop()
at removing slave links. This is a noop, and calling it may confuse
readers wrt locking. Further cleanup will follow in a later patch.
Actually we've got reports of use-after-free by syzkaller fuzzer, and
this hopefully fixes these issues.
Reported-by: Dmitry Vyukov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: brcmf_parse_vndr_ies(const u8 *vndr_ie_buf, u32 vndr_ie_len,
struct parsed_vndr_ies *vndr_ies)
{
struct brcmf_vs_tlv *vndrie;
struct brcmf_tlv *ie;
struct parsed_vndr_ie_info *parsed_info;
s32 remaining_len;
remaining_len = (s32)vndr_ie_len;
memset(vndr_ies, 0, sizeof(*vndr_ies));
ie = (struct brcmf_tlv *)vndr_ie_buf;
while (ie) {
if (ie->id != WLAN_EID_VENDOR_SPECIFIC)
goto next;
vndrie = (struct brcmf_vs_tlv *)ie;
/* len should be bigger than OUI length + one */
if (vndrie->len < (VS_IE_FIXED_HDR_LEN - TLV_HDR_LEN + 1)) {
brcmf_err("invalid vndr ie. length is too small %d\n",
vndrie->len);
goto next;
}
/* if wpa or wme ie, do not add ie */
if (!memcmp(vndrie->oui, (u8 *)WPA_OUI, TLV_OUI_LEN) &&
((vndrie->oui_type == WPA_OUI_TYPE) ||
(vndrie->oui_type == WME_OUI_TYPE))) {
brcmf_dbg(TRACE, "Found WPA/WME oui. Do not add it\n");
goto next;
}
parsed_info = &vndr_ies->ie_info[vndr_ies->count];
/* save vndr ie information */
parsed_info->ie_ptr = (char *)vndrie;
parsed_info->ie_len = vndrie->len + TLV_HDR_LEN;
memcpy(&parsed_info->vndrie, vndrie, sizeof(*vndrie));
vndr_ies->count++;
brcmf_dbg(TRACE, "** OUI %02x %02x %02x, type 0x%02x\n",
parsed_info->vndrie.oui[0],
parsed_info->vndrie.oui[1],
parsed_info->vndrie.oui[2],
parsed_info->vndrie.oui_type);
if (vndr_ies->count >= VNDR_IE_PARSE_LIMIT)
break;
next:
remaining_len -= (ie->len + TLV_HDR_LEN);
if (remaining_len <= TLV_HDR_LEN)
ie = NULL;
else
ie = (struct brcmf_tlv *)(((u8 *)ie) + ie->len +
TLV_HDR_LEN);
}
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: [email protected] # v4.7
Reported-by: Daxing Guo <[email protected]>
Reviewed-by: Hante Meuleman <[email protected]>
Reviewed-by: Pieter-Paul Giesberts <[email protected]>
Reviewed-by: Franky Lin <[email protected]>
Signed-off-by: Arend van Spriel <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Document::registerVisibilityObserver(DocumentVisibilityObserver* observer)
{
ASSERT(!m_visibilityObservers.contains(observer));
m_visibilityObservers.add(observer);
}
Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone.
BUG=556724,577105
Review URL: https://codereview.chromium.org/1667573002
Cr-Commit-Position: refs/heads/master@{#373642}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void NetworkHandler::GetCookies(Maybe<Array<String>> protocol_urls,
std::unique_ptr<GetCookiesCallback> callback) {
if (!host_) {
callback->sendFailure(Response::InternalError());
return;
}
std::vector<GURL> urls = ComputeCookieURLs(host_, protocol_urls);
scoped_refptr<CookieRetriever> retriever =
new CookieRetriever(std::move(callback));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&CookieRetriever::RetrieveCookiesOnIO, retriever,
base::Unretained(
process_->GetStoragePartition()->GetURLRequestContext()),
urls));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
Target: 1
Example 2:
Code: status_t String8::append(const char* other)
{
return append(other, strlen(other));
}
Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8
Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length
is causing a heap overflow.
Correcting the length computation and adding bound checks to the
conversion functions.
Test: ran libutils_tests
Bug: 29250543
Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb
(cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1)
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
{
unsigned int len;
if (!(dev->flags & IFF_UP))
return false;
len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
if (skb->len <= len)
return true;
/* if TSO is enabled, we don't care about the length as the packet
* could be forwarded without being segmented before
*/
if (skb_is_gso(skb))
return true;
return false;
}
Commit Message: tun: call dev_get_valid_name() before register_netdevice()
register_netdevice() could fail early when we have an invalid
dev name, in which case ->ndo_uninit() is not called. For tun
device, this is a problem because a timer etc. are already
initialized and it expects ->ndo_uninit() to clean them up.
We could move these initializations into a ->ndo_init() so
that register_netdevice() knows better, however this is still
complicated due to the logic in tun_detach().
Therefore, I choose to just call dev_get_valid_name() before
register_netdevice(), which is quicker and much easier to audit.
And for this specific case, it is already enough.
Fixes: 96442e42429e ("tuntap: choose the txq based on rxq")
Reported-by: Dmitry Alexeev <[email protected]>
Cc: Jason Wang <[email protected]>
Cc: "Michael S. Tsirkin" <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476
Output: | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.