instruction
stringclasses
1 value
input
stringlengths
386
71.4k
output
stringclasses
4 values
__index_level_0__
int64
15
30k
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void Compositor::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { } Vulnerability Type: DoS Mem. Corr. CWE ID: CWE-20 Summary: Blink, as used in Google Chrome before 50.0.2661.94, does not ensure that frames satisfy a check for the same renderer process in addition to a Same Origin Policy check, which allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact via a crafted web site, related to BindingSecurity.cpp and DOMWindow.cpp. Commit Message: Don't report OnFirstSurfaceActivation for ui::Compositor Bug: 893850 Change-Id: Iee754cefbd083d0a21a2b672fb8e837eaab81c43 Reviewed-on: https://chromium-review.googlesource.com/c/1293712 Reviewed-by: Antoine Labour <piman@chromium.org> Commit-Queue: Saman Sami <samans@chromium.org> Cr-Commit-Position: refs/heads/master@{#601629}
Medium
2,409
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int qcow2_snapshot_load_tmp(BlockDriverState *bs, const char *snapshot_id, const char *name, Error **errp) { int i, snapshot_index; BDRVQcowState *s = bs->opaque; QCowSnapshot *sn; uint64_t *new_l1_table; int new_l1_bytes; int ret; assert(bs->read_only); /* Search the snapshot */ snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name); if (snapshot_index < 0) { error_setg(errp, "Can't find snapshot"); return -ENOENT; } sn = &s->snapshots[snapshot_index]; /* Allocate and read in the snapshot's L1 table */ new_l1_bytes = sn->l1_size * sizeof(uint64_t); new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512)); return ret; } Vulnerability Type: DoS Overflow Mem. Corr. CWE ID: CWE-190 Summary: Multiple integer overflows in the block drivers in QEMU, possibly before 2.0.0, allow local users to cause a denial of service (crash) via a crafted catalog size in (1) the parallels_open function in block/parallels.c or (2) bochs_open function in bochs.c, a large L1 table in the (3) qcow2_snapshot_load_tmp in qcow2-snapshot.c or (4) qcow2_grow_l1_table function in qcow2-cluster.c, (5) a large request in the bdrv_check_byte_request function in block.c and other block drivers, (6) crafted cluster indexes in the get_refcount function in qcow2-refcount.c, or (7) a large number of blocks in the cloop_open function in cloop.c, which trigger buffer overflows, memory corruption, large memory allocations and out-of-bounds read and writes. Commit Message:
Medium
12,058
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static ssize_t read_mem(struct file *file, char __user *buf, size_t count, loff_t *ppos) { phys_addr_t p = *ppos; ssize_t read, sz; void *ptr; if (p != *ppos) return 0; if (!valid_phys_addr_range(p, count)) return -EFAULT; read = 0; #ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED /* we don't have page 0 mapped on sparc and m68k.. */ if (p < PAGE_SIZE) { sz = size_inside_page(p, count); if (sz > 0) { if (clear_user(buf, sz)) return -EFAULT; buf += sz; p += sz; count -= sz; read += sz; } } #endif while (count > 0) { unsigned long remaining; sz = size_inside_page(p, count); if (!range_is_allowed(p >> PAGE_SHIFT, count)) return -EPERM; /* * On ia64 if a page has been mapped somewhere as uncached, then * it must also be accessed uncached by the kernel or data * corruption may occur. */ ptr = xlate_dev_mem_ptr(p); if (!ptr) return -EFAULT; remaining = copy_to_user(buf, ptr, sz); unxlate_dev_mem_ptr(p, ptr); if (remaining) return -EFAULT; buf += sz; p += sz; count -= sz; read += sz; } *ppos += read; return read; } Vulnerability Type: Bypass CWE ID: CWE-732 Summary: The mm subsystem in the Linux kernel through 4.10.10 does not properly enforce the CONFIG_STRICT_DEVMEM protection mechanism, which allows local users to read or write to kernel memory locations in the first megabyte (and bypass slab-allocation access restrictions) via an application that opens the /dev/mem file, related to arch/x86/mm/init.c and drivers/char/mem.c. Commit Message: mm: Tighten x86 /dev/mem with zeroing reads Under CONFIG_STRICT_DEVMEM, reading System RAM through /dev/mem is disallowed. However, on x86, the first 1MB was always allowed for BIOS and similar things, regardless of it actually being System RAM. It was possible for heap to end up getting allocated in low 1MB RAM, and then read by things like x86info or dd, which would trip hardened usercopy: usercopy: kernel memory exposure attempt detected from ffff880000090000 (dma-kmalloc-256) (4096 bytes) This changes the x86 exception for the low 1MB by reading back zeros for System RAM areas instead of blindly allowing them. More work is needed to extend this to mmap, but currently mmap doesn't go through usercopy, so hardened usercopy won't Oops the kernel. Reported-by: Tommi Rantala <tommi.t.rantala@nokia.com> Tested-by: Tommi Rantala <tommi.t.rantala@nokia.com> Signed-off-by: Kees Cook <keescook@chromium.org>
Low
1,885
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, unsigned int *width, unsigned int *height, int *flip_image) { int palette_size; unsigned char tga[TGA_HEADER_SIZE]; unsigned char id_len, /*cmap_type,*/ image_type; unsigned char pixel_depth, image_desc; unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size; unsigned short /*x_origin, y_origin,*/ image_w, image_h; if (!bits_per_pixel || !width || !height || !flip_image) { return 0; } if (fread(tga, TGA_HEADER_SIZE, 1, fp) != 1) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); return 0 ; } id_len = tga[0]; /*cmap_type = tga[1];*/ image_type = tga[2]; /*cmap_index = get_ushort(&tga[3]);*/ cmap_len = get_ushort(&tga[5]); cmap_entry_size = tga[7]; #if 0 x_origin = get_ushort(&tga[8]); y_origin = get_ushort(&tga[10]); #endif image_w = get_ushort(&tga[12]); image_h = get_ushort(&tga[14]); pixel_depth = tga[16]; image_desc = tga[17]; *bits_per_pixel = (unsigned int)pixel_depth; *width = (unsigned int)image_w; *height = (unsigned int)image_h; /* Ignore tga identifier, if present ... */ if (id_len) { unsigned char *id = (unsigned char *) malloc(id_len); if (id == 0) { fprintf(stderr, "tga_readheader: memory out\n"); return 0; } if (!fread(id, id_len, 1, fp)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); free(id); return 0 ; } free(id); } /* Test for compressed formats ... not yet supported ... if (image_type > 8) { fprintf(stderr, "Sorry, compressed tga files are not currently supported.\n"); return 0 ; } *flip_image = !(image_desc & 32); /* Palettized formats are not yet supported, skip over the palette, if present ... */ palette_size = cmap_len * (cmap_entry_size / 8); if (palette_size > 0) { fprintf(stderr, "File contains a palette - not yet supported."); fseek(fp, palette_size, SEEK_CUR); } return 1; } Vulnerability Type: DoS CWE ID: CWE-787 Summary: An invalid write access was discovered in bin/jp2/convert.c in OpenJPEG 2.2.0, triggering a crash in the tgatoimage function. The vulnerability may lead to remote denial of service or possibly unspecified other impact. Commit Message: tgatoimage(): avoid excessive memory allocation attempt, and fixes unaligned load (#995)
Medium
3,678
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void free_pipe_info(struct pipe_inode_info *pipe) { int i; for (i = 0; i < pipe->buffers; i++) { struct pipe_buffer *buf = pipe->bufs + i; if (buf->ops) buf->ops->release(pipe, buf); } if (pipe->tmp_page) __free_page(pipe->tmp_page); kfree(pipe->bufs); kfree(pipe); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: fs/pipe.c in the Linux kernel before 4.5 does not limit the amount of unread data in pipes, which allows local users to cause a denial of service (memory consumption) by creating many pipes with non-default sizes. Commit Message: pipe: limit the per-user amount of pages allocated in pipes On no-so-small systems, it is possible for a single process to cause an OOM condition by filling large pipes with data that are never read. A typical process filling 4000 pipes with 1 MB of data will use 4 GB of memory. On small systems it may be tricky to set the pipe max size to prevent this from happening. This patch makes it possible to enforce a per-user soft limit above which new pipes will be limited to a single page, effectively limiting them to 4 kB each, as well as a hard limit above which no new pipes may be created for this user. This has the effect of protecting the system against memory abuse without hurting other users, and still allowing pipes to work correctly though with less data at once. The limit are controlled by two new sysctls : pipe-user-pages-soft, and pipe-user-pages-hard. Both may be disabled by setting them to zero. The default soft limit allows the default number of FDs per process (1024) to create pipes of the default size (64kB), thus reaching a limit of 64MB before starting to create only smaller pipes. With 256 processes limited to 1024 FDs each, this results in 1024*64kB + (256*1024 - 1024) * 4kB = 1084 MB of memory allocated for a user. The hard limit is disabled by default to avoid breaking existing applications that make intensive use of pipes (eg: for splicing). Reported-by: socketpair@gmail.com Reported-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp> Mitigates: CVE-2013-4312 (Linux 2.0+) Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Willy Tarreau <w@1wt.eu> Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>
Low
17,191
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent) { FD_t wfd = NULL; int rc = 0; /* Create the file with 0200 permissions (write by owner). */ { mode_t old_umask = umask(0577); wfd = Fopen(dest, "w.ufdio"); umask(old_umask); } if (Ferror(wfd)) { rc = RPMERR_OPEN_FAILED; goto exit; } if (!nocontent) rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm); exit: if (wfd) { int myerrno = errno; Fclose(wfd); errno = myerrno; } return rc; } Vulnerability Type: DoS CWE ID: CWE-59 Summary: It was found that versions of rpm before 4.13.0.2 use temporary files with predictable names when installing an RPM. An attacker with ability to write in a directory where files will be installed could create symbolic links to an arbitrary location and modify content, and possibly permissions to arbitrary files, which could be used for denial of service or possibly privilege escalation. Commit Message: Don't follow symlinks on file creation (CVE-2017-7501) Open newly created files with O_EXCL to prevent symlink tricks. When reopening hardlinks for writing the actual content, use append mode instead. This is compatible with the write-only permissions but is not destructive in case we got redirected to somebody elses file, verify the target before actually writing anything. As these are files with the temporary suffix, errors mean a local user with sufficient privileges to break the installation of the package anyway is trying to goof us on purpose, don't bother trying to mend it (we couldn't fix the hardlink case anyhow) but just bail out. Based on a patch by Florian Festi.
Low
9,367
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void DatabaseImpl::IDBThreadHelper::CreateTransaction( int64_t transaction_id, const std::vector<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode) { DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; connection_->database()->CreateTransaction(transaction_id, connection_.get(), object_store_ids, mode); } Vulnerability Type: CWE ID: CWE-416 Summary: A use after free in Blink in Google Chrome prior to 59.0.3071.104 for Mac, Windows, and Linux, and 59.0.3071.117 for Android, allowed a remote attacker to perform an out of bounds memory read via a crafted HTML page, aka an IndexedDB sandbox escape. Commit Message: [IndexedDB] Fixed transaction use-after-free vuln Bug: 725032 Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa Reviewed-on: https://chromium-review.googlesource.com/518483 Reviewed-by: Joshua Bell <jsbell@chromium.org> Commit-Queue: Daniel Murphy <dmurph@chromium.org> Cr-Commit-Position: refs/heads/master@{#475952}
Medium
7,549
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int dtls1_process_buffered_records(SSL *s) { pitem *item; SSL3_BUFFER *rb; item = pqueue_peek(s->rlayer.d->unprocessed_rcds.q); if (item) { /* Check if epoch is current. */ if (s->rlayer.d->unprocessed_rcds.epoch != s->rlayer.d->r_epoch) return (1); /* Nothing to do. */ rb = RECORD_LAYER_get_rbuf(&s->rlayer); */ return 1; } /* Process all the records. */ while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) { dtls1_get_unprocessed_record(s); if (!dtls1_process_record(s)) return (0); if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds), /* Process all the records. */ while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) { dtls1_get_unprocessed_record(s); if (!dtls1_process_record(s)) return (0); if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds), SSL3_RECORD_get_seq_num(s->rlayer.rrec)) < 0) return -1; } } * here, anything else is handled by higher layers * Application data protocol * none of our business */ s->rlayer.d->processed_rcds.epoch = s->rlayer.d->r_epoch; s->rlayer.d->unprocessed_rcds.epoch = s->rlayer.d->r_epoch + 1; return (1); } Vulnerability Type: DoS CWE ID: CWE-189 Summary: The Anti-Replay feature in the DTLS implementation in OpenSSL before 1.1.0 mishandles early use of a new epoch number in conjunction with a large sequence number, which allows remote attackers to cause a denial of service (false-positive packet drops) via spoofed DTLS records, related to rec_layer_d1.c and ssl3_record.c. Commit Message:
Low
27,584
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void worker_process(int fd, debugger_request_t& request) { std::string tombstone_path; int tombstone_fd = -1; switch (request.action) { case DEBUGGER_ACTION_DUMP_TOMBSTONE: case DEBUGGER_ACTION_CRASH: tombstone_fd = open_tombstone(&tombstone_path); if (tombstone_fd == -1) { ALOGE("debuggerd: failed to open tombstone file: %s\n", strerror(errno)); exit(1); } break; case DEBUGGER_ACTION_DUMP_BACKTRACE: break; default: ALOGE("debuggerd: unexpected request action: %d", request.action); exit(1); } if (ptrace(PTRACE_ATTACH, request.tid, 0, 0) != 0) { ALOGE("debuggerd: ptrace attach failed: %s", strerror(errno)); exit(1); } bool attach_gdb = should_attach_gdb(request); if (attach_gdb) { if (init_getevent() != 0) { ALOGE("debuggerd: failed to initialize input device, not waiting for gdb"); attach_gdb = false; } } std::set<pid_t> siblings; if (!attach_gdb) { ptrace_siblings(request.pid, request.tid, siblings); } std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(request.pid)); int amfd = -1; std::unique_ptr<std::string> amfd_data; if (request.action == DEBUGGER_ACTION_CRASH) { amfd = activity_manager_connect(); amfd_data.reset(new std::string); } bool succeeded = false; if (!drop_privileges()) { ALOGE("debuggerd: failed to drop privileges, exiting"); _exit(1); } int crash_signal = SIGKILL; succeeded = perform_dump(request, fd, tombstone_fd, backtrace_map.get(), siblings, &crash_signal, amfd_data.get()); if (succeeded) { if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) { if (!tombstone_path.empty()) { android::base::WriteFully(fd, tombstone_path.c_str(), tombstone_path.length()); } } } if (attach_gdb) { if (!send_signal(request.pid, 0, SIGSTOP)) { ALOGE("debuggerd: failed to stop process for gdb attach: %s", strerror(errno)); attach_gdb = false; } } if (!attach_gdb) { activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get()); } if (ptrace(PTRACE_DETACH, request.tid, 0, 0) != 0) { ALOGE("debuggerd: ptrace detach from %d failed: %s", request.tid, strerror(errno)); } for (pid_t sibling : siblings) { ptrace(PTRACE_DETACH, sibling, 0, 0); } if (!attach_gdb && request.action == DEBUGGER_ACTION_CRASH) { if (!send_signal(request.pid, request.tid, crash_signal)) { ALOGE("debuggerd: failed to kill process %d: %s", request.pid, strerror(errno)); } } if (attach_gdb) { wait_for_user_action(request); activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get()); if (!send_signal(request.pid, 0, SIGCONT)) { ALOGE("debuggerd: failed to resume process %d: %s", request.pid, strerror(errno)); } uninit_getevent(); } close(amfd); exit(!succeeded); } Vulnerability Type: +Priv CWE ID: CWE-264 Summary: debuggerd/debuggerd.cpp in Debuggerd in Android 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-09-01, and 7.0 before 2016-09-01 mishandles the interaction between PTRACE_ATTACH operations and thread exits, which allows attackers to gain privileges via a crafted application, aka internal bug 29555636. Commit Message: debuggerd: verify that traced threads belong to the right process. Fix two races in debuggerd's PTRACE_ATTACH logic: 1. The target thread in a crash dump request could exit between the /proc/<pid>/task/<tid> check and the PTRACE_ATTACH. 2. Sibling threads could exit between listing /proc/<pid>/task and the PTRACE_ATTACH. Bug: http://b/29555636 Change-Id: I4dfe1ea30e2c211d2389321bd66e3684dd757591
Medium
9,154
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: InvalidState AXNodeObject::getInvalidState() const { const AtomicString& attributeValue = getAOMPropertyOrARIAAttribute(AOMStringProperty::kInvalid); if (equalIgnoringCase(attributeValue, "false")) return InvalidStateFalse; if (equalIgnoringCase(attributeValue, "true")) return InvalidStateTrue; if (equalIgnoringCase(attributeValue, "spelling")) return InvalidStateSpelling; if (equalIgnoringCase(attributeValue, "grammar")) return InvalidStateGrammar; if (!attributeValue.isEmpty()) return InvalidStateOther; if (getNode() && getNode()->isElementNode() && toElement(getNode())->isFormControlElement()) { HTMLFormControlElement* element = toHTMLFormControlElement(getNode()); HeapVector<Member<HTMLFormControlElement>> invalidControls; bool isInvalid = !element->checkValidity(&invalidControls, CheckValidityDispatchNoEvent); return isInvalid ? InvalidStateTrue : InvalidStateFalse; } return AXObject::getInvalidState(); } Vulnerability Type: Exec Code CWE ID: CWE-254 Summary: Google Chrome before 44.0.2403.89 does not ensure that the auto-open list omits all dangerous file types, which makes it easier for remote attackers to execute arbitrary code by providing a crafted file and leveraging a user's previous *Always open files of this type* choice, related to download_commands.cc and download_prefs.cc. Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858}
Medium
20,645
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void CopyToOMX(const OMX_BUFFERHEADERTYPE *header) { if (!mIsBackup) { return; } memcpy(header->pBuffer + header->nOffset, (const OMX_U8 *)mMem->pointer() + header->nOffset, header->nFilledLen); } Vulnerability Type: +Info CWE ID: CWE-200 Summary: An information disclosure vulnerability in libstagefright in Mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-11-01, and 7.0 before 2016-11-01 could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access sensitive data without permission. Android ID: A-29422020. Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
Medium
27,791
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
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); } } Vulnerability Type: DoS Overflow Bypass CWE ID: CWE-119 Summary: The Linux kernel before 4.4.1 allows local users to bypass file-descriptor limits and cause a denial of service (memory consumption) by sending each descriptor over a UNIX socket before closing it, related to net/unix/af_unix.c and net/unix/garbage.c. 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: socketpair@gmail.com Reported-by: Tetsuo Handa <penguin-kernel@I-love.SAKURA.ne.jp> Mitigates: CVE-2013-4312 (Linux 2.0+) Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: Willy Tarreau <w@1wt.eu> Signed-off-by: David S. Miller <davem@davemloft.net>
Low
24,734
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y, MagickMax(Ar_image->columns,Cr_image->columns),1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y, MagickMax(Ai_image->columns,Ci_image->columns),1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y, MagickMax(Br_image->columns,Cr_image->columns),1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y, MagickMax(Bi_image->columns,Ci_image->columns),1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(images); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]); Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]); Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]); Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } Vulnerability Type: Overflow CWE ID: CWE-119 Summary: ImageMagick 7.0.8-50 Q16 has a heap-based buffer overflow in MagickCore/fourier.c in ComplexImage. Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1595
Medium
4,275
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_surface *user_srf; struct vmw_surface *srf; struct vmw_resource *res; struct vmw_resource *tmp; union drm_vmw_gb_surface_create_arg *arg = (union drm_vmw_gb_surface_create_arg *)data; struct drm_vmw_gb_surface_create_req *req = &arg->req; struct drm_vmw_gb_surface_create_rep *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret; uint32_t size; uint32_t backup_handle; if (req->multisample_count != 0) return -EINVAL; if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS) return -EINVAL; if (unlikely(vmw_user_surface_size == 0)) vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) + 128; size = vmw_user_surface_size + 128; /* Define a surface based on the parameters. */ ret = vmw_surface_gb_priv_define(dev, size, req->svga3d_flags, req->format, req->drm_surface_flags & drm_vmw_surface_flag_scanout, req->mip_levels, req->multisample_count, req->array_size, req->base_size, &srf); if (unlikely(ret != 0)) return ret; user_srf = container_of(srf, struct vmw_user_surface, srf); if (drm_is_primary_client(file_priv)) user_srf->master = drm_master_get(file_priv->master); ret = ttm_read_lock(&dev_priv->reservation_sem, true); if (unlikely(ret != 0)) return ret; res = &user_srf->srf.res; if (req->buffer_handle != SVGA3D_INVALID_ID) { ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle, &res->backup, &user_srf->backup_base); if (ret == 0 && res->backup->base.num_pages * PAGE_SIZE < res->backup_size) { DRM_ERROR("Surface backup buffer is too small.\n"); vmw_dmabuf_unreference(&res->backup); ret = -EINVAL; goto out_unlock; } } else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer) ret = vmw_user_dmabuf_alloc(dev_priv, tfile, res->backup_size, req->drm_surface_flags & drm_vmw_surface_flag_shareable, &backup_handle, &res->backup, &user_srf->backup_base); if (unlikely(ret != 0)) { vmw_resource_unreference(&res); goto out_unlock; } tmp = vmw_resource_reference(res); ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime, req->drm_surface_flags & drm_vmw_surface_flag_shareable, VMW_RES_SURFACE, &vmw_user_surface_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); vmw_resource_unreference(&res); goto out_unlock; } rep->handle = user_srf->prime.base.hash.key; rep->backup_size = res->backup_size; if (res->backup) { rep->buffer_map_handle = drm_vma_node_offset_addr(&res->backup->base.vma_node); rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE; rep->buffer_handle = backup_handle; } else { rep->buffer_map_handle = 0; rep->buffer_size = 0; rep->buffer_handle = SVGA3D_INVALID_ID; } vmw_resource_unreference(&res); out_unlock: ttm_read_unlock(&dev_priv->reservation_sem); return ret; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The vmw_gb_surface_define_ioctl function (accessible via DRM_IOCTL_VMW_GB_SURFACE_CREATE) in drivers/gpu/drm/vmwgfx/vmwgfx_surface.c in the Linux kernel through 4.11.4 defines a backup_handle variable but does not give it an initial value. If one attempts to create a GB surface, with a previously allocated DMA buffer to be used as a backup buffer, the backup_handle variable does not get written to and is then later returned to user space, allowing local users to obtain sensitive information from uninitialized kernel memory via a crafted ioctl call. Commit Message: drm/vmwgfx: Make sure backup_handle is always valid When vmw_gb_surface_define_ioctl() is called with an existing buffer, we end up returning an uninitialized variable in the backup_handle. The fix is to first initialize backup_handle to 0 just to be sure, and second, when a user-provided buffer is found, we will use the req->buffer_handle as the backup_handle. Cc: <stable@vger.kernel.org> Reported-by: Murray McAllister <murray.mcallister@insomniasec.com> Signed-off-by: Sinclair Yeh <syeh@vmware.com> Reviewed-by: Deepak Rawat <drawat@vmware.com>
Low
9,887
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) { jas_image_t *image; bmp_hdr_t hdr; bmp_info_t *info; uint_fast16_t cmptno; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; uint_fast16_t numcmpts; long n; if (optstr) { jas_eprintf("warning: ignoring BMP decoder options\n"); } jas_eprintf( "THE BMP FORMAT IS NOT FULLY SUPPORTED!\n" "THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n" "IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n" "TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n" ); /* Read the bitmap header. */ if (bmp_gethdr(in, &hdr)) { jas_eprintf("cannot get header\n"); return 0; } /* Read the bitmap information. */ if (!(info = bmp_getinfo(in))) { jas_eprintf("cannot get info\n"); return 0; } /* Ensure that we support this type of BMP file. */ if (!bmp_issupported(&hdr, info)) { jas_eprintf("error: unsupported BMP encoding\n"); bmp_info_destroy(info); return 0; } /* Skip over any useless data between the end of the palette and start of the bitmap data. */ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { jas_eprintf("error: possibly bad bitmap offset?\n"); return 0; } if (n > 0) { jas_eprintf("skipping unknown data in BMP file\n"); if (bmp_gobble(in, n)) { bmp_info_destroy(info); return 0; } } /* Get the number of components. */ numcmpts = bmp_numcmpts(info); for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = info->width; cmptparm->height = info->height; cmptparm->prec = 8; cmptparm->sgnd = false; } /* Create image object. */ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { bmp_info_destroy(info); return 0; } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read the bitmap data. */ if (bmp_getdata(in, info, image)) { bmp_info_destroy(info); jas_image_destroy(image); return 0; } bmp_info_destroy(info); return image; } Vulnerability Type: DoS CWE ID: CWE-476 Summary: The bmp_getdata function in libjasper/bmp/bmp_dec.c in JasPer before 1.900.5 allows remote attackers to cause a denial of service (NULL pointer dereference) via a crafted BMP image in an imginfo command. Commit Message: Fixed a sanitizer failure in the BMP codec. Also, added a --debug-level command line option to the imginfo command for debugging purposes.
Medium
8,716
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: const Cluster* Segment::GetLast() const { if ((m_clusters == NULL) || (m_clusterCount <= 0)) return &m_eos; const long idx = m_clusterCount - 1; Cluster* const pCluster = m_clusters[idx]; assert(pCluster); return pCluster; } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. 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
Low
29,788
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect) { HTTPContext *s = h->priv_data; URLContext *old_hd = s->hd; int64_t old_off = s->off; uint8_t old_buf[BUFFER_SIZE]; int old_buf_size, ret; AVDictionary *options = NULL; if (whence == AVSEEK_SIZE) return s->filesize; else if (!force_reconnect && ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))) return s->off; else if ((s->filesize == -1 && whence == SEEK_END)) return AVERROR(ENOSYS); if (whence == SEEK_CUR) off += s->off; else if (whence == SEEK_END) off += s->filesize; else if (whence != SEEK_SET) return AVERROR(EINVAL); if (off < 0) return AVERROR(EINVAL); s->off = off; if (s->off && h->is_streamed) return AVERROR(ENOSYS); /* we save the old context in case the seek fails */ old_buf_size = s->buf_end - s->buf_ptr; memcpy(old_buf, s->buf_ptr, old_buf_size); s->hd = NULL; /* if it fails, continue on old connection */ if ((ret = http_open_cnx(h, &options)) < 0) { av_dict_free(&options); memcpy(s->buffer, old_buf, old_buf_size); s->buf_ptr = s->buffer; s->buf_end = s->buffer + old_buf_size; s->hd = old_hd; s->off = old_off; return ret; } av_dict_free(&options); ffurl_close(old_hd); return off; } Vulnerability Type: Exec Code Overflow CWE ID: CWE-119 Summary: Heap-based buffer overflow in libavformat/http.c in FFmpeg before 2.8.10, 3.0.x before 3.0.5, 3.1.x before 3.1.6, and 3.2.x before 3.2.2 allows remote web servers to execute arbitrary code via a negative chunk size in an HTTP response. Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <paulcher@icloud.com>.
Low
28,044
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData, int srcWidth, int srcHeight, SplashCoord *mat, GBool glyphMode) { SplashBitmap *scaledMask; SplashClipResult clipRes, clipRes2; SplashPipe pipe; int scaledWidth, scaledHeight, t0, t1; SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11; SplashCoord vx[4], vy[4]; int xMin, yMin, xMax, yMax; ImageSection section[3]; int nSections; int y, xa, xb, x, i, xx, yy; vx[0] = mat[4]; vy[0] = mat[5]; vx[1] = mat[2] + mat[4]; vy[1] = mat[3] + mat[5]; vx[2] = mat[0] + mat[2] + mat[4]; vy[2] = mat[1] + mat[3] + mat[5]; vx[3] = mat[0] + mat[4]; vy[3] = mat[1] + mat[5]; xMin = imgCoordMungeLowerC(vx[0], glyphMode); xMax = imgCoordMungeUpperC(vx[0], glyphMode); yMin = imgCoordMungeLowerC(vy[0], glyphMode); yMax = imgCoordMungeUpperC(vy[0], glyphMode); for (i = 1; i < 4; ++i) { t0 = imgCoordMungeLowerC(vx[i], glyphMode); if (t0 < xMin) { xMin = t0; } t0 = imgCoordMungeUpperC(vx[i], glyphMode); if (t0 > xMax) { xMax = t0; } t1 = imgCoordMungeLowerC(vy[i], glyphMode); if (t1 < yMin) { yMin = t1; } t1 = imgCoordMungeUpperC(vy[i], glyphMode); if (t1 > yMax) { yMax = t1; } } clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1); opClipRes = clipRes; if (clipRes == splashClipAllOutside) { return; } if (mat[0] >= 0) { t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) - imgCoordMungeLowerC(mat[4], glyphMode); } else { t0 = imgCoordMungeUpperC(mat[4], glyphMode) - imgCoordMungeLowerC(mat[0] + mat[4], glyphMode); } if (mat[1] >= 0) { t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) - imgCoordMungeLowerC(mat[5], glyphMode); } else { t1 = imgCoordMungeUpperC(mat[5], glyphMode) - imgCoordMungeLowerC(mat[1] + mat[5], glyphMode); } scaledWidth = t0 > t1 ? t0 : t1; if (mat[2] >= 0) { t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) - imgCoordMungeLowerC(mat[4], glyphMode); } else { t0 = imgCoordMungeUpperC(mat[4], glyphMode) - imgCoordMungeLowerC(mat[2] + mat[4], glyphMode); } if (mat[3] >= 0) { t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) - imgCoordMungeLowerC(mat[5], glyphMode); } else { t1 = imgCoordMungeUpperC(mat[5], glyphMode) - imgCoordMungeLowerC(mat[3] + mat[5], glyphMode); } scaledHeight = t0 > t1 ? t0 : t1; if (scaledWidth == 0) { scaledWidth = 1; } if (scaledHeight == 0) { scaledHeight = 1; } r00 = mat[0] / scaledWidth; r01 = mat[1] / scaledWidth; r10 = mat[2] / scaledHeight; r11 = mat[3] / scaledHeight; det = r00 * r11 - r01 * r10; if (splashAbs(det) < 1e-6) { return; } ir00 = r11 / det; ir01 = -r01 / det; ir10 = -r10 / det; ir11 = r00 / det; scaledMask = scaleMask(src, srcData, srcWidth, srcHeight, scaledWidth, scaledHeight); i = (vy[2] <= vy[3]) ? 2 : 3; } Vulnerability Type: DoS CWE ID: Summary: splash/Splash.cc in poppler before 0.22.1 allows context-dependent attackers to cause a denial of service (NULL pointer dereference and crash) via vectors related to the (1) Splash::arbitraryTransformMask, (2) Splash::blitMask, and (3) Splash::scaleMaskYuXu functions. Commit Message:
Medium
7,369
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu) { const struct usb_cdc_union_desc *union_desc; struct usb_host_interface *alt; union_desc = ims_pcu_get_cdc_union_desc(intf); if (!union_desc) return -EINVAL; pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev, union_desc->bMasterInterface0); alt = pcu->ctrl_intf->cur_altsetting; pcu->ep_ctrl = &alt->endpoint[0].desc; pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl); pcu->data_intf = usb_ifnum_to_if(pcu->udev, union_desc->bSlaveInterface0); alt = pcu->data_intf->cur_altsetting; if (alt->desc.bNumEndpoints != 2) { dev_err(pcu->dev, "Incorrect number of endpoints on data interface (%d)\n", alt->desc.bNumEndpoints); return -EINVAL; } pcu->ep_out = &alt->endpoint[0].desc; if (!usb_endpoint_is_bulk_out(pcu->ep_out)) { dev_err(pcu->dev, "First endpoint on data interface is not BULK OUT\n"); return -EINVAL; } pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out); if (pcu->max_out_size < 8) { dev_err(pcu->dev, "Max OUT packet size is too small (%zd)\n", pcu->max_out_size); return -EINVAL; } pcu->ep_in = &alt->endpoint[1].desc; if (!usb_endpoint_is_bulk_in(pcu->ep_in)) { dev_err(pcu->dev, "Second endpoint on data interface is not BULK IN\n"); return -EINVAL; } pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in); if (pcu->max_in_size < 8) { dev_err(pcu->dev, "Max IN packet size is too small (%zd)\n", pcu->max_in_size); return -EINVAL; } return 0; } Vulnerability Type: DoS CWE ID: Summary: The ims_pcu_parse_cdc_data function in drivers/input/misc/ims-pcu.c in the Linux kernel before 4.5.1 allows physically proximate attackers to cause a denial of service (system crash) via a USB device without both a master and a slave interface. Commit Message: Input: ims-pcu - sanity check against missing interfaces A malicious device missing interface can make the driver oops. Add sanity checking. Signed-off-by: Oliver Neukum <ONeukum@suse.com> CC: stable@vger.kernel.org Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
Low
19,698
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: my_object_rec_arrays (MyObject *obj, GPtrArray *in, GPtrArray **ret, GError **error) { char **strs; GArray *ints; guint v_UINT; if (in->len != 2) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid array len"); return FALSE; } strs = g_ptr_array_index (in, 0); if (!*strs || strcmp (*strs, "foo")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 0"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "bar")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 1"); return FALSE; } strs++; if (*strs) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string array len in pos 0"); return FALSE; } strs = g_ptr_array_index (in, 1); if (!*strs || strcmp (*strs, "baz")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 0"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "whee")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 1"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "moo")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 2"); return FALSE; } strs++; if (*strs) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string array len in pos 1"); return FALSE; } *ret = g_ptr_array_new (); ints = g_array_new (TRUE, TRUE, sizeof (guint)); v_UINT = 10; g_array_append_val (ints, v_UINT); v_UINT = 42; g_array_append_val (ints, v_UINT); v_UINT = 27; g_array_append_val (ints, v_UINT); g_ptr_array_add (*ret, ints); ints = g_array_new (TRUE, TRUE, sizeof (guint)); v_UINT = 30; g_array_append_val (ints, v_UINT); g_ptr_array_add (*ret, ints); return TRUE; } Vulnerability Type: DoS Bypass CWE ID: CWE-264 Summary: DBus-GLib 0.73 disregards the access flag of exported GObject properties, which allows local users to bypass intended access restrictions and possibly cause a denial of service by modifying properties, as demonstrated by properties of the (1) DeviceKit-Power, (2) NetworkManager, and (3) ModemManager services. Commit Message:
Low
11,363
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags) { struct dentry *dir; struct fscrypt_info *ci; int dir_has_key, cached_with_key; if (flags & LOOKUP_RCU) return -ECHILD; dir = dget_parent(dentry); if (!d_inode(dir)->i_sb->s_cop->is_encrypted(d_inode(dir))) { dput(dir); return 0; } ci = d_inode(dir)->i_crypt_info; if (ci && ci->ci_keyring_key && (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED) | (1 << KEY_FLAG_DEAD)))) ci = NULL; /* this should eventually be an flag in d_flags */ spin_lock(&dentry->d_lock); cached_with_key = dentry->d_flags & DCACHE_ENCRYPTED_WITH_KEY; spin_unlock(&dentry->d_lock); dir_has_key = (ci != NULL); dput(dir); /* * If the dentry was cached without the key, and it is a * negative dentry, it might be a valid name. We can't check * if the key has since been made available due to locking * reasons, so we fail the validation so ext4_lookup() can do * this check. * * We also fail the validation if the dentry was created with * the key present, but we no longer have the key, or vice versa. */ if ((!cached_with_key && d_is_negative(dentry)) || (!cached_with_key && dir_has_key) || (cached_with_key && !dir_has_key)) return 0; return 1; } Vulnerability Type: DoS +Priv CWE ID: CWE-416 Summary: Use-after-free vulnerability in fs/crypto/ in the Linux kernel before 4.10.7 allows local users to cause a denial of service (NULL pointer dereference) or possibly gain privileges by revoking keyring keys being used for ext4, f2fs, or ubifs encryption, causing cryptographic transform objects to be freed prematurely. Commit Message: fscrypt: remove broken support for detecting keyring key revocation Filesystem encryption ostensibly supported revoking a keyring key that had been used to "unlock" encrypted files, causing those files to become "locked" again. This was, however, buggy for several reasons, the most severe of which was that when key revocation happened to be detected for an inode, its fscrypt_info was immediately freed, even while other threads could be using it for encryption or decryption concurrently. This could be exploited to crash the kernel or worse. This patch fixes the use-after-free by removing the code which detects the keyring key having been revoked, invalidated, or expired. Instead, an encrypted inode that is "unlocked" now simply remains unlocked until it is evicted from memory. Note that this is no worse than the case for block device-level encryption, e.g. dm-crypt, and it still remains possible for a privileged user to evict unused pages, inodes, and dentries by running 'sync; echo 3 > /proc/sys/vm/drop_caches', or by simply unmounting the filesystem. In fact, one of those actions was already needed anyway for key revocation to work even somewhat sanely. This change is not expected to break any applications. In the future I'd like to implement a real API for fscrypt key revocation that interacts sanely with ongoing filesystem operations --- waiting for existing operations to complete and blocking new operations, and invalidating and sanitizing key material and plaintext from the VFS caches. But this is a hard problem, and for now this bug must be fixed. This bug affected almost all versions of ext4, f2fs, and ubifs encryption, and it was potentially reachable in any kernel configured with encryption support (CONFIG_EXT4_ENCRYPTION=y, CONFIG_EXT4_FS_ENCRYPTION=y, CONFIG_F2FS_FS_ENCRYPTION=y, or CONFIG_UBIFS_FS_ENCRYPTION=y). Note that older kernels did not use the shared fs/crypto/ code, but due to the potential security implications of this bug, it may still be worthwhile to backport this fix to them. Fixes: b7236e21d55f ("ext4 crypto: reorganize how we store keys in the inode") Cc: stable@vger.kernel.org # v4.2+ Signed-off-by: Eric Biggers <ebiggers@google.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu> Acked-by: Michael Halcrow <mhalcrow@google.com>
Low
26,308
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { if (size > 512) return 0; net::ProxyBypassRules rules; std::string input(data, data + size); rules.ParseFromString(input); rules.ParseFromStringUsingSuffixMatching(input); return 0; } Vulnerability Type: CWE ID: CWE-20 Summary: Lack of special casing of localhost in WPAD files in Google Chrome prior to 71.0.3578.80 allowed an attacker on the local network segment to proxy resources on localhost via a crafted WPAD file. Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <eroman@chromium.org> Reviewed-by: Dominick Ng <dominickn@chromium.org> Reviewed-by: Tarun Bansal <tbansal@chromium.org> Reviewed-by: Matt Menke <mmenke@chromium.org> Reviewed-by: Sami Kyöstilä <skyostil@chromium.org> Cr-Commit-Position: refs/heads/master@{#606112}
Medium
19,018
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void RunCoeffCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) input_block[j] = rnd.Rand8() - rnd.Rand8(); fwd_txfm_ref(input_block, output_ref_block, pitch_, tx_type_); REGISTER_STATE_CHECK(RunFwdTxfm(input_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) EXPECT_EQ(output_block[j], output_ref_block[j]); } } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. 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
Low
1,806
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode) { int i,j,pass; Residue *r = f->residue_config + rn; int rtype = f->residue_types[rn]; int c = r->classbook; int classwords = f->codebooks[c].dimensions; int n_read = r->end - r->begin; int part_read = n_read / r->part_size; int temp_alloc_point = temp_alloc_save(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata)); #else int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications)); #endif CHECK(f); for (i=0; i < ch; ++i) if (!do_not_decode[i]) memset(residue_buffers[i], 0, sizeof(float) * n); if (rtype == 2 && ch != 1) { for (j=0; j < ch; ++j) if (!do_not_decode[j]) break; if (j == ch) goto done; for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set = 0; if (ch == 2) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = (z & 1), p_inter = z>>1; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #else if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #endif } else { z += r->part_size; c_inter = z & 1; p_inter = z >> 1; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else if (ch == 1) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = 0, p_inter = z; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = 0; p_inter = z; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = z % ch, p_inter = z/ch; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = z % ch; p_inter = z / ch; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } } goto done; } CHECK(f); for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set=0; while (pcount < part_read) { if (pass == 0) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { Codebook *c = f->codebooks+r->classbook; int temp; DECODE(temp,f,c); if (temp == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[j][class_set] = r->classdata[temp]; #else for (i=classwords-1; i >= 0; --i) { classifications[j][i+pcount] = temp % r->classifications; temp /= r->classifications; } #endif } } } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[j][class_set][i]; #else int c = classifications[j][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { float *target = residue_buffers[j]; int offset = r->begin + pcount * r->part_size; int n = r->part_size; Codebook *book = f->codebooks + b; if (!residue_decode(f, book, target, offset, n, rtype)) goto done; } } } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } done: CHECK(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE temp_free(f,part_classdata); #else temp_free(f,classifications); #endif temp_alloc_restore(f,temp_alloc_point); } Vulnerability Type: DoS Overflow Mem. Corr. CWE ID: CWE-119 Summary: Sean Barrett stb_vorbis version 1.12 and earlier contains a Buffer Overflow vulnerability in All vorbis decoding paths. that can result in memory corruption, denial of service, comprised execution of host program. This attack appear to be exploitable via Victim must open a specially crafted Ogg Vorbis file. This vulnerability appears to have been fixed in 1.13. Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files
Medium
29,384
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: krb5_gss_inquire_sec_context_by_oid (OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { krb5_gss_ctx_id_rec *ctx; size_t i; if (minor_status == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; *minor_status = 0; if (desired_object == GSS_C_NO_OID) return GSS_S_CALL_INACCESSIBLE_READ; if (data_set == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; *data_set = GSS_C_NO_BUFFER_SET; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (!ctx->established) return GSS_S_NO_CONTEXT; for (i = 0; i < sizeof(krb5_gss_inquire_sec_context_by_oid_ops)/ sizeof(krb5_gss_inquire_sec_context_by_oid_ops[0]); i++) { if (g_OID_prefix_equal(desired_object, &krb5_gss_inquire_sec_context_by_oid_ops[i].oid)) { return (*krb5_gss_inquire_sec_context_by_oid_ops[i].func)(minor_status, context_handle, desired_object, data_set); } } *minor_status = EINVAL; return GSS_S_UNAVAILABLE; } Vulnerability Type: DoS Exec Code CWE ID: Summary: The krb5_gss_process_context_token function in lib/gssapi/krb5/process_context_token.c in the libgssapi_krb5 library in MIT Kerberos 5 (aka krb5) through 1.11.5, 1.12.x through 1.12.2, and 1.13.x before 1.13.1 does not properly maintain security-context handles, which allows remote authenticated users to cause a denial of service (use-after-free and double free, and daemon crash) or possibly execute arbitrary code via crafted GSSAPI traffic, as demonstrated by traffic to kadmind. Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup
Low
12,689
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op) { /* ensure image exists first */ if (page->image == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined"); return 0; } /* grow the page to accomodate a new stripe if necessary */ if (page->striped) { int new_height = y + image->height + page->end_row; if (page->image->height < new_height) { jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height); jbig2_image_resize(ctx, page->image, page->image->width, new_height); } } jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op); return 0; } Vulnerability Type: Overflow CWE ID: CWE-119 Summary: ghostscript before version 9.21 is vulnerable to a heap based buffer overflow that was found in the ghostscript jbig2_decode_gray_scale_image function which is used to decode halftone segments in a JBIG2 image. A document (PostScript or PDF) with an embedded, specially crafted, jbig2 image could trigger a segmentation fault in ghostscript. Commit Message:
Medium
8,884
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: bool GLSurfaceEGLSurfaceControl::SupportsSwapBuffersWithBounds() { return false; } Vulnerability Type: DoS CWE ID: Summary: Multiple unspecified vulnerabilities in Google Chrome before 52.0.2743.82 allow attackers to cause a denial of service or possibly have other impact via unknown vectors. Commit Message: gpu/android : Add support for partial swap with surface control. Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should allow the display compositor to draw the minimum sub-rect necessary from the damage tracking in BufferQueue on the client-side, and also to pass this damage rect to the framework. R=piman@chromium.org Bug: 926020 Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61 Reviewed-on: https://chromium-review.googlesource.com/c/1457467 Commit-Queue: Khushal <khushalsagar@chromium.org> Commit-Queue: Antoine Labour <piman@chromium.org> Reviewed-by: Antoine Labour <piman@chromium.org> Auto-Submit: Khushal <khushalsagar@chromium.org> Cr-Commit-Position: refs/heads/master@{#629852}
Medium
9,724
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void FakeCrosDisksClient::Mount(const std::string& source_path, const std::string& source_format, const std::string& mount_label, const std::vector<std::string>& mount_options, MountAccessMode access_mode, RemountOption remount, VoidDBusMethodCallback callback) { MountType type = source_format.empty() ? MOUNT_TYPE_DEVICE : MOUNT_TYPE_ARCHIVE; if (GURL(source_path).is_valid()) type = MOUNT_TYPE_NETWORK_STORAGE; base::FilePath mounted_path; switch (type) { case MOUNT_TYPE_ARCHIVE: mounted_path = GetArchiveMountPoint().Append( base::FilePath::FromUTF8Unsafe(mount_label)); break; case MOUNT_TYPE_DEVICE: mounted_path = GetRemovableDiskMountPoint().Append( base::FilePath::FromUTF8Unsafe(mount_label)); break; case MOUNT_TYPE_NETWORK_STORAGE: if (custom_mount_point_callback_) { mounted_path = custom_mount_point_callback_.Run(source_path, mount_options); } break; case MOUNT_TYPE_INVALID: NOTREACHED(); return; } mounted_paths_.insert(mounted_path); base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce(&PerformFakeMount, source_path, mounted_path), base::BindOnce(&FakeCrosDisksClient::DidMount, weak_ptr_factory_.GetWeakPtr(), source_path, type, mounted_path, std::move(callback))); } Vulnerability Type: DoS CWE ID: Summary: Multiple unspecified vulnerabilities in Google Chrome before 47.0.2526.80 allow attackers to cause a denial of service or possibly have other impact via unknown vectors. 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 <xiyuan@chromium.org> Commit-Queue: Sam McNally <sammc@chromium.org> Cr-Commit-Position: refs/heads/master@{#567513}
Low
12,567
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: const net::HttpRequestHeaders& request_headers() const { return request_headers_; } Vulnerability Type: DoS CWE ID: Summary: Multiple unspecified vulnerabilities in Google Chrome before 50.0.2661.94 allow attackers to cause a denial of service or possibly have other impact via unknown vectors. Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <jam@chromium.org> Reviewed-by: Ramin Halavati <rhalavati@chromium.org> Reviewed-by: Maks Orlovich <morlovich@chromium.org> Reviewed-by: Peter Kasting <pkasting@chromium.org> Cr-Commit-Position: refs/heads/master@{#607652}
Low
25,870
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ip6t_entry *)e); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } Vulnerability Type: DoS Overflow +Info CWE ID: CWE-119 Summary: The IPT_SO_SET_REPLACE setsockopt implementation in the netfilter subsystem in the Linux kernel before 4.6 allows local users to cause a denial of service (out-of-bounds read) or possibly obtain sensitive information from kernel heap memory by leveraging in-container root access to provide a crafted offset value that leads to crossing a ruleset blob boundary. Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
Low
1,903
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void CaptivePortalDetector::DetectCaptivePortal( const GURL& url, const DetectionCallback& detection_callback) { DCHECK(CalledOnValidThread()); DCHECK(!FetchingURL()); DCHECK(detection_callback_.is_null()); detection_callback_ = detection_callback; url_fetcher_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this); url_fetcher_->SetAutomaticallyRetryOn5xx(false); url_fetcher_->SetRequestContext(request_context_.get()); url_fetcher_->SetLoadFlags( net::LOAD_BYPASS_CACHE | net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SEND_AUTH_DATA); url_fetcher_->Start(); } Vulnerability Type: DoS Overflow CWE ID: CWE-190 Summary: Integer overflow in the SkAutoSTArray implementation in include/core/SkTemplates.h in the filters implementation in Skia, as used in Google Chrome before 41.0.2272.76, allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors that trigger a reset action with a large count value, leading to an out-of-bounds write operation. Commit Message: Add data usage tracking for chrome services Add data usage tracking for captive portal, web resource and signin services BUG=655749 Review-Url: https://codereview.chromium.org/2643013004 Cr-Commit-Position: refs/heads/master@{#445810}
Low
25,545
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: http_DissectRequest(struct sess *sp) { struct http_conn *htc; struct http *hp; uint16_t retval; CHECK_OBJ_NOTNULL(sp, SESS_MAGIC); htc = sp->htc; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); hp = sp->http; CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); hp->logtag = HTTP_Rx; retval = http_splitline(sp->wrk, sp->fd, hp, htc, HTTP_HDR_REQ, HTTP_HDR_URL, HTTP_HDR_PROTO); if (retval != 0) { WSPR(sp, SLT_HttpGarbage, htc->rxbuf); return (retval); } http_ProtoVer(hp); retval = htc_request_check_host_hdr(hp); if (retval != 0) { WSP(sp, SLT_Error, "Duplicated Host header"); return (retval); } return (retval); } Vulnerability Type: Http R.Spl. CWE ID: Summary: Varnish 3.x before 3.0.7, when used in certain stacked installations, allows remote attackers to inject arbitrary HTTP headers and conduct HTTP response splitting attacks via a header line terminated by a r (carriage return) character in conjunction with multiple Content-Length headers in an HTTP request. Commit Message: Check for duplicate Content-Length headers in requests If a duplicate CL header is in the request, we fail the request with a 400 (Bad Request) Fix a test case that was sending duplicate CL by misstake and would not fail because of that.
Low
90
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static const ut8 *r_bin_dwarf_parse_comp_unit(Sdb *s, const ut8 *obuf, RBinDwarfCompUnit *cu, const RBinDwarfDebugAbbrev *da, size_t offset, const ut8 *debug_str, size_t debug_str_len) { const ut8 *buf = obuf, *buf_end = obuf + (cu->hdr.length - 7); ut64 abbr_code; size_t i; if (cu->hdr.length > debug_str_len) { return NULL; } while (buf && buf < buf_end && buf >= obuf) { if (cu->length && cu->capacity == cu->length) { r_bin_dwarf_expand_cu (cu); } buf = r_uleb128 (buf, buf_end - buf, &abbr_code); if (abbr_code > da->length || !buf) { return NULL; } r_bin_dwarf_init_die (&cu->dies[cu->length]); if (!abbr_code) { cu->dies[cu->length].abbrev_code = 0; cu->length++; buf++; continue; } cu->dies[cu->length].abbrev_code = abbr_code; cu->dies[cu->length].tag = da->decls[abbr_code - 1].tag; abbr_code += offset; if (da->capacity < abbr_code) { return NULL; } for (i = 0; i < da->decls[abbr_code - 1].length; i++) { if (cu->dies[cu->length].length == cu->dies[cu->length].capacity) { r_bin_dwarf_expand_die (&cu->dies[cu->length]); } if (i >= cu->dies[cu->length].capacity || i >= da->decls[abbr_code - 1].capacity) { eprintf ("Warning: malformed dwarf attribute capacity doesn't match length\n"); break; } memset (&cu->dies[cu->length].attr_values[i], 0, sizeof (cu->dies[cu->length].attr_values[i])); buf = r_bin_dwarf_parse_attr_value (buf, buf_end - buf, &da->decls[abbr_code - 1].specs[i], &cu->dies[cu->length].attr_values[i], &cu->hdr, debug_str, debug_str_len); if (cu->dies[cu->length].attr_values[i].name == DW_AT_comp_dir) { const char *name = cu->dies[cu->length].attr_values[i].encoding.str_struct.string; sdb_set (s, "DW_AT_comp_dir", name, 0); } cu->dies[cu->length].length++; } cu->length++; } return buf; } Vulnerability Type: DoS CWE ID: CWE-125 Summary: In radare2 2.0.1, libr/bin/dwarf.c allows remote attackers to cause a denial of service (invalid read and application crash) via a crafted ELF file, related to r_bin_dwarf_parse_comp_unit in dwarf.c and sdb_set_internal in shlr/sdb/src/sdb.c. Commit Message: Fix #8813 - segfault in dwarf parser
Medium
333
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char colorspace[MaxTextExtent], text[MaxTextExtent]; Image *image; IndexPacket *indexes; long type, x_offset, y, y_offset; MagickBooleanType status; MagickPixelPacket pixel; QuantumAny range; register ssize_t i, x; register PixelPacket *q; ssize_t count; unsigned long depth, height, max_value, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) ResetMagickMemory(text,0,sizeof(text)); (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0) return(ReadTEXTImage(image_info,image,text,exception)); do { width=0; height=0; max_value=0; *colorspace='\0'; count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value, colorspace); if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=width; image->rows=height; for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ; image->depth=depth; LocaleLower(colorspace); i=(ssize_t) strlen(colorspace)-1; image->matte=MagickFalse; if ((i > 0) && (colorspace[i] == 'a')) { colorspace[i]='\0'; image->matte=MagickTrue; } type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace); if (type < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->colorspace=(ColorspaceType) type; (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); (void) SetImageBackgroundColor(image); range=GetQuantumRange(image->depth); for (y=0; y < (ssize_t) image->rows; y++) { double blue, green, index, opacity, red; red=0.0; green=0.0; blue=0.0; index=0.0; opacity=0.0; for (x=0; x < (ssize_t) image->columns; x++) { if (ReadBlobString(image,text) == (char *) NULL) break; switch (image->colorspace) { case GRAYColorspace: { if (image->matte != MagickFalse) { count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&opacity); green=red; blue=red; break; } count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset, &y_offset,&red); green=red; blue=red; break; } case CMYKColorspace: { if (image->matte != MagickFalse) { count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&index,&opacity); break; } count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset, &y_offset,&red,&green,&blue,&index); break; } default: { if (image->matte != MagickFalse) { count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]", &x_offset,&y_offset,&red,&green,&blue,&opacity); break; } count=(ssize_t) sscanf(text, "%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,&y_offset, &red,&green,&blue); break; } } if (strchr(text,'%') != (char *) NULL) { red*=0.01*range; green*=0.01*range; blue*=0.01*range; index*=0.01*range; opacity*=0.01*range; } if (image->colorspace == LabColorspace) { green+=(range+1)/2.0; blue+=(range+1)/2.0; } pixel.red=ScaleAnyToQuantum((QuantumAny) (red+0.5),range); pixel.green=ScaleAnyToQuantum((QuantumAny) (green+0.5),range); pixel.blue=ScaleAnyToQuantum((QuantumAny) (blue+0.5),range); pixel.index=ScaleAnyToQuantum((QuantumAny) (index+0.5),range); pixel.opacity=ScaleAnyToQuantum((QuantumAny) (opacity+0.5),range); q=GetAuthenticPixels(image,x_offset,y_offset,1,1,exception); if (q == (PixelPacket *) NULL) continue; SetPixelRed(q,pixel.red); SetPixelGreen(q,pixel.green); SetPixelBlue(q,pixel.blue); if (image->colorspace == CMYKColorspace) { indexes=GetAuthenticIndexQueue(image); SetPixelIndex(indexes,pixel.index); } if (image->matte != MagickFalse) SetPixelAlpha(q,pixel.opacity); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } (void) ReadBlobString(image,text); if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Buffer overflow in the ReadVIFFImage function in coders/viff.c in ImageMagick before 6.9.4-5 allows remote attackers to cause a denial of service (application crash) via a crafted file. Commit Message:
Medium
963
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int kvm_ioctl_create_device(struct kvm *kvm, struct kvm_create_device *cd) { struct kvm_device_ops *ops = NULL; struct kvm_device *dev; bool test = cd->flags & KVM_CREATE_DEVICE_TEST; int ret; if (cd->type >= ARRAY_SIZE(kvm_device_ops_table)) return -ENODEV; ops = kvm_device_ops_table[cd->type]; if (ops == NULL) return -ENODEV; if (test) return 0; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->ops = ops; dev->kvm = kvm; mutex_lock(&kvm->lock); ret = ops->create(dev, cd->type); if (ret < 0) { mutex_unlock(&kvm->lock); kfree(dev); return ret; } list_add(&dev->vm_node, &kvm->devices); mutex_unlock(&kvm->lock); if (ops->init) ops->init(dev); ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC); if (ret < 0) { ops->destroy(dev); mutex_lock(&kvm->lock); list_del(&dev->vm_node); mutex_unlock(&kvm->lock); return ret; } kvm_get_kvm(kvm); cd->fd = ret; return 0; } Vulnerability Type: DoS +Priv CWE ID: CWE-416 Summary: Use-after-free vulnerability in the kvm_ioctl_create_device function in virt/kvm/kvm_main.c in the Linux kernel before 4.8.13 allows host OS users to cause a denial of service (host OS crash) or possibly gain privileges via crafted ioctl calls on the /dev/kvm device. Commit Message: KVM: use after free in kvm_ioctl_create_device() We should move the ops->destroy(dev) after the list_del(&dev->vm_node) so that we don't use "dev" after freeing it. Fixes: a28ebea2adc4 ("KVM: Protect device ops->create and list_add with kvm->lock") Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Reviewed-by: David Hildenbrand <david@redhat.com> Signed-off-by: Radim Krčmář <rkrcmar@redhat.com>
Low
20,931
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: ScreenLockLibrary* CrosLibrary::GetScreenLockLibrary() { return screen_lock_lib_.GetDefaultImpl(use_stub_impl_); } Vulnerability Type: Exec Code CWE ID: CWE-189 Summary: The Program::getActiveUniformMaxLength function in libGLESv2/Program.cpp in libGLESv2.dll in the WebGLES library in Almost Native Graphics Layer Engine (ANGLE), as used in Mozilla Firefox 4.x before 4.0.1 on Windows and in the GPU process in Google Chrome before 10.0.648.205 on Windows, allows remote attackers to execute arbitrary code via unspecified vectors, related to an *off-by-three* error. Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
Low
14,229
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static Image *ReadHRZImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; register ssize_t x; register PixelPacket *q; register unsigned char *p; ssize_t count, y; size_t length; unsigned char *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); } /* Convert HRZ raster image to pixel packets. */ image->columns=256; image->rows=240; image->depth=8; pixels=(unsigned char *) AcquireQuantumMemory(image->columns,3* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=(size_t) (3*image->columns); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if ((size_t) count != length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=pixels; 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(4**p++)); SetPixelGreen(q,ScaleCharToQuantum(4**p++)); SetPixelBlue(q,ScaleCharToQuantum(4**p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Buffer overflow in the ReadVIFFImage function in coders/viff.c in ImageMagick before 6.9.4-5 allows remote attackers to cause a denial of service (application crash) via a crafted file. Commit Message:
Medium
25,951
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; ps_dec->process_called = 1; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; ps_dec->u4_stop_threads = 0; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; pu1_bitstrm_buf = ps_dec->ps_mem_tab[MEM_REC_BITSBUF].pv_base; u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ /* Since 8 bytes are read ahead, ensure 8 bytes are free at the end of the buffer, which will be memset to 0 after emulation prevention */ buflen = MIN(buflen, (WORD32)(ps_dec->ps_mem_tab[MEM_REC_BITSBUF].u4_mem_size - 8)); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; if(buflen >= MAX_NAL_UNIT_SIZE) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); H264_DEC_DEBUG_PRINT( "\nNal Size exceeded %d, Processing Stopped..\n", MAX_NAL_UNIT_SIZE); ps_dec->i4_error_code = 1 << IVD_CORRUPTEDDATA; ps_dec_op->e_pic_type = -1; /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /*signal end of frame decode for curren frame*/ if(ps_dec->u4_pic_buf_got == 0) { if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return IV_FAIL; } else { ps_dec->u1_pic_decode_done = 1; continue; } } { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; header_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; WORD32 ht_in_mbs; ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag); num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) prev_slice_err = 1; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) || (ret1 == ERROR_INV_SPS_PPS_T)) { ret = ret1; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if (((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) && (ps_dec->u4_pic_buf_got == 1)) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((0 == ps_dec->u4_num_reorder_frames_at_init) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } /*--------------------------------------------------------------------*/ /* Do End of Pic processing. */ /* Should be called only if frame was decoded in previous process call*/ /*--------------------------------------------------------------------*/ if(ps_dec->u4_pic_buf_got == 1) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } else { ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: An information disclosure vulnerability in libavc in Mediaserver could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access data without permission. Product: Android. Versions: 6.0, 6.0.1, 7.0, 7.1.1. Android ID: A-33551775. Commit Message: Decoder: Fixed initialization of first_slice_in_pic To handle some errors, first_slice_in_pic was being set to 2. This is now cleaned up and first_slice_in_pic is set to 1 only once per pic. This will ensure picture level initializations are done only once even in case of error clips Bug: 33717589 Bug: 33551775 Bug: 33716442 Bug: 33677995 Change-Id: If341436b3cbaa724017eedddd88c2e6fac36d8ba
Medium
17,468
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: GpuChannel::~GpuChannel() { #if defined(OS_WIN) if (renderer_process_) CloseHandle(renderer_process_); #endif } Vulnerability Type: DoS CWE ID: Summary: Google Chrome before 20.0.1132.43 on Windows does not properly isolate sandboxed processes, which might allow remote attackers to cause a denial of service (process interference) via unspecified vectors. 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
Low
29,076
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: compare_two_images(Image *a, Image *b, int via_linear, png_const_colorp background) { ptrdiff_t stridea = a->stride; ptrdiff_t strideb = b->stride; png_const_bytep rowa = a->buffer+16; png_const_bytep rowb = b->buffer+16; const png_uint_32 width = a->image.width; const png_uint_32 height = a->image.height; const png_uint_32 formata = a->image.format; const png_uint_32 formatb = b->image.format; const unsigned int a_sample = PNG_IMAGE_SAMPLE_SIZE(formata); const unsigned int b_sample = PNG_IMAGE_SAMPLE_SIZE(formatb); int alpha_added, alpha_removed; int bchannels; int btoa[4]; png_uint_32 y; Transform tr; /* This should never happen: */ if (width != b->image.width || height != b->image.height) return logerror(a, a->file_name, ": width x height changed: ", b->file_name); /* Set up the background and the transform */ transform_from_formats(&tr, a, b, background, via_linear); /* Find the first row and inter-row space. */ if (!(formata & PNG_FORMAT_FLAG_COLORMAP) && (formata & PNG_FORMAT_FLAG_LINEAR)) stridea *= 2; if (!(formatb & PNG_FORMAT_FLAG_COLORMAP) && (formatb & PNG_FORMAT_FLAG_LINEAR)) strideb *= 2; if (stridea < 0) rowa += (height-1) * (-stridea); if (strideb < 0) rowb += (height-1) * (-strideb); /* First shortcut the two colormap case by comparing the image data; if it * matches then we expect the colormaps to match, although this is not * absolutely necessary for an image match. If the colormaps fail to match * then there is a problem in libpng. */ if (formata & formatb & PNG_FORMAT_FLAG_COLORMAP) { /* Only check colormap entries that actually exist; */ png_const_bytep ppa, ppb; int match; png_byte in_use[256], amax = 0, bmax = 0; memset(in_use, 0, sizeof in_use); ppa = rowa; ppb = rowb; /* Do this the slow way to accumulate the 'in_use' flags, don't break out * of the loop until the end; this validates the color-mapped data to * ensure all pixels are valid color-map indexes. */ for (y=0, match=1; y<height && match; ++y, ppa += stridea, ppb += strideb) { png_uint_32 x; for (x=0; x<width; ++x) { png_byte bval = ppb[x]; png_byte aval = ppa[x]; if (bval > bmax) bmax = bval; if (bval != aval) match = 0; in_use[aval] = 1; if (aval > amax) amax = aval; } } /* If the buffers match then the colormaps must too. */ if (match) { /* Do the color-maps match, entry by entry? Only check the 'in_use' * entries. An error here should be logged as a color-map error. */ png_const_bytep a_cmap = (png_const_bytep)a->colormap; png_const_bytep b_cmap = (png_const_bytep)b->colormap; int result = 1; /* match by default */ /* This is used in logpixel to get the error message correct. */ tr.is_palette = 1; for (y=0; y<256; ++y, a_cmap += a_sample, b_cmap += b_sample) if (in_use[y]) { /* The colormap entries should be valid, but because libpng doesn't * do any checking at present the original image may contain invalid * pixel values. These cause an error here (at present) unless * accumulating errors in which case the program just ignores them. */ if (y >= a->image.colormap_entries) { if ((a->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)a->image.colormap_entries); logerror(a, a->file_name, ": bad pixel index: ", pindex); } result = 0; } else if (y >= b->image.colormap_entries) { if ((a->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)b->image.colormap_entries); logerror(b, b->file_name, ": bad pixel index: ", pindex); } result = 0; } /* All the mismatches are logged here; there can only be 256! */ else if (!cmppixel(&tr, a_cmap, b_cmap, 0, y)) result = 0; } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; result = 1; /* force a continue */ } return result; } /* else the image buffers don't match pixel-wise so compare sample values * instead, but first validate that the pixel indexes are in range (but * only if not accumulating, when the error is ignored.) */ else if ((a->opts & ACCUMULATE) == 0) { /* Check the original image first, * TODO: deal with input images with bad pixel values? */ if (amax >= a->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", amax, (unsigned long)a->image.colormap_entries); return logerror(a, a->file_name, ": bad pixel index: ", pindex); } else if (bmax >= b->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", bmax, (unsigned long)b->image.colormap_entries); return logerror(b, b->file_name, ": bad pixel index: ", pindex); } } } /* We can directly compare pixel values without the need to use the read * or transform support (i.e. a memory compare) if: * * 1) The bit depth has not changed. * 2) RGB to grayscale has not been done (the reverse is ok; we just compare * the three RGB values to the original grayscale.) * 3) An alpha channel has not been removed from an 8-bit format, or the * 8-bit alpha value of the pixel was 255 (opaque). * * If an alpha channel has been *added* then it must have the relevant opaque * value (255 or 65535). * * The fist two the tests (in the order given above) (using the boolean * equivalence !a && !b == !(a || b)) */ if (!(((formata ^ formatb) & PNG_FORMAT_FLAG_LINEAR) | (formata & (formatb ^ PNG_FORMAT_FLAG_COLOR) & PNG_FORMAT_FLAG_COLOR))) { /* Was an alpha channel changed? */ const png_uint_32 alpha_changed = (formata ^ formatb) & PNG_FORMAT_FLAG_ALPHA; /* Was an alpha channel removed? (The third test.) If so the direct * comparison is only possible if the input alpha is opaque. */ alpha_removed = (formata & alpha_changed) != 0; /* Was an alpha channel added? */ alpha_added = (formatb & alpha_changed) != 0; /* The channels may have been moved between input and output, this finds * out how, recording the result in the btoa array, which says where in * 'a' to find each channel of 'b'. If alpha was added then btoa[alpha] * ends up as 4 (and is not used.) */ { int i; png_byte aloc[4]; png_byte bloc[4]; /* The following are used only if the formats match, except that * 'bchannels' is a flag for matching formats. btoa[x] says, for each * channel in b, where to find the corresponding value in a, for the * bchannels. achannels may be different for a gray to rgb transform * (a will be 1 or 2, b will be 3 or 4 channels.) */ (void)component_loc(aloc, formata); bchannels = component_loc(bloc, formatb); /* Hence the btoa array. */ for (i=0; i<4; ++i) if (bloc[i] < 4) btoa[bloc[i]] = aloc[i]; /* may be '4' for alpha */ if (alpha_added) alpha_added = bloc[0]; /* location of alpha channel in image b */ else alpha_added = 4; /* Won't match an image b channel */ if (alpha_removed) alpha_removed = aloc[0]; /* location of alpha channel in image a */ else alpha_removed = 4; } } else { /* Direct compare is not possible, cancel out all the corresponding local * variables. */ bchannels = 0; alpha_removed = alpha_added = 4; btoa[3] = btoa[2] = btoa[1] = btoa[0] = 4; /* 4 == not present */ } for (y=0; y<height; ++y, rowa += stridea, rowb += strideb) { png_const_bytep ppa, ppb; png_uint_32 x; for (x=0, ppa=rowa, ppb=rowb; x<width; ++x) { png_const_bytep psa, psb; if (formata & PNG_FORMAT_FLAG_COLORMAP) psa = (png_const_bytep)a->colormap + a_sample * *ppa++; else psa = ppa, ppa += a_sample; if (formatb & PNG_FORMAT_FLAG_COLORMAP) psb = (png_const_bytep)b->colormap + b_sample * *ppb++; else psb = ppb, ppb += b_sample; /* Do the fast test if possible. */ if (bchannels) { /* Check each 'b' channel against either the corresponding 'a' * channel or the opaque alpha value, as appropriate. If * alpha_removed value is set (not 4) then also do this only if the * 'a' alpha channel (alpha_removed) is opaque; only relevant for * the 8-bit case. */ if (formatb & PNG_FORMAT_FLAG_LINEAR) /* 16-bit checks */ { png_const_uint_16p pua = aligncastconst(png_const_uint_16p, psa); png_const_uint_16p pub = aligncastconst(png_const_uint_16p, psb); switch (bchannels) { case 4: if (pua[btoa[3]] != pub[3]) break; case 3: if (pua[btoa[2]] != pub[2]) break; case 2: if (pua[btoa[1]] != pub[1]) break; case 1: if (pua[btoa[0]] != pub[0]) break; if (alpha_added != 4 && pub[alpha_added] != 65535) break; continue; /* x loop */ default: break; /* impossible */ } } else if (alpha_removed == 4 || psa[alpha_removed] == 255) { switch (bchannels) { case 4: if (psa[btoa[3]] != psb[3]) break; case 3: if (psa[btoa[2]] != psb[2]) break; case 2: if (psa[btoa[1]] != psb[1]) break; case 1: if (psa[btoa[0]] != psb[0]) break; if (alpha_added != 4 && psb[alpha_added] != 255) break; continue; /* x loop */ default: break; /* impossible */ } } } /* If we get to here the fast match failed; do the slow match for this * pixel. */ if (!cmppixel(&tr, psa, psb, x, y) && (a->opts & KEEP_GOING) == 0) return 0; /* error case */ } } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; } return 1; } Vulnerability Type: +Priv CWE ID: Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085. Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
Low
11,768
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: sg_fill_request_table(Sg_fd *sfp, sg_req_info_t *rinfo) { Sg_request *srp; int val; unsigned int ms; val = 0; list_for_each_entry(srp, &sfp->rq_list, entry) { if (val > SG_MAX_QUEUE) break; memset(&rinfo[val], 0, SZ_SG_REQ_INFO); rinfo[val].req_state = srp->done + 1; rinfo[val].problem = srp->header.masked_status & srp->header.host_status & srp->header.driver_status; if (srp->done) rinfo[val].duration = srp->header.duration; else { ms = jiffies_to_msecs(jiffies); rinfo[val].duration = (ms > srp->header.duration) ? (ms - srp->header.duration) : 0; } rinfo[val].orphan = srp->orphan; rinfo[val].sg_io_owned = srp->sg_io_owned; rinfo[val].pack_id = srp->header.pack_id; rinfo[val].usr_ptr = srp->header.usr_ptr; val++; } } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The sg_ioctl function in drivers/scsi/sg.c in the Linux kernel before 4.13.4 allows local users to obtain sensitive information from uninitialized kernel heap-memory locations via an SG_GET_REQUEST_TABLE ioctl call for /dev/sg0. Commit Message: scsi: sg: fixup infoleak when using SG_GET_REQUEST_TABLE When calling SG_GET_REQUEST_TABLE ioctl only a half-filled table is returned; the remaining part will then contain stale kernel memory information. This patch zeroes out the entire table to avoid this issue. Signed-off-by: Hannes Reinecke <hare@suse.com> Reviewed-by: Bart Van Assche <bart.vanassche@wdc.com> Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Eric Dumazet <edumazet@google.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>
Low
10,142
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: TabStyle::TabColors GM2TabStyle::CalculateColors() const { const ui::ThemeProvider* theme_provider = tab_->GetThemeProvider(); constexpr float kMinimumActiveContrastRatio = 6.05f; constexpr float kMinimumInactiveContrastRatio = 4.61f; constexpr float kMinimumHoveredContrastRatio = 5.02f; constexpr float kMinimumPressedContrastRatio = 4.41f; float expected_opacity = 0.0f; if (tab_->IsActive()) { expected_opacity = 1.0f; } else if (tab_->IsSelected()) { expected_opacity = kSelectedTabOpacity; } else if (tab_->mouse_hovered()) { expected_opacity = GetHoverOpacity(); } const SkColor bg_color = color_utils::AlphaBlend( tab_->controller()->GetTabBackgroundColor(TAB_ACTIVE), tab_->controller()->GetTabBackgroundColor(TAB_INACTIVE), expected_opacity); SkColor title_color = tab_->controller()->GetTabForegroundColor( expected_opacity > 0.5f ? TAB_ACTIVE : TAB_INACTIVE, bg_color); title_color = color_utils::GetColorWithMinimumContrast(title_color, bg_color); const SkColor base_hovered_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_HOVER); const SkColor base_pressed_color = theme_provider->GetColor( ThemeProperties::COLOR_TAB_CLOSE_BUTTON_BACKGROUND_PRESSED); const auto get_color_for_contrast_ratio = [](SkColor fg_color, SkColor bg_color, float contrast_ratio) { const SkAlpha blend_alpha = color_utils::GetBlendValueWithMinimumContrast( bg_color, fg_color, bg_color, contrast_ratio); return color_utils::AlphaBlend(fg_color, bg_color, blend_alpha); }; const SkColor generated_icon_color = get_color_for_contrast_ratio( title_color, bg_color, tab_->IsActive() ? kMinimumActiveContrastRatio : kMinimumInactiveContrastRatio); const SkColor generated_hovered_color = get_color_for_contrast_ratio( base_hovered_color, bg_color, kMinimumHoveredContrastRatio); const SkColor generated_pressed_color = get_color_for_contrast_ratio( base_pressed_color, bg_color, kMinimumPressedContrastRatio); const SkColor generated_hovered_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_hovered_color); const SkColor generated_pressed_icon_color = color_utils::GetColorWithMinimumContrast(title_color, generated_pressed_color); return {bg_color, title_color, generated_icon_color, generated_hovered_icon_color, generated_pressed_icon_color, generated_hovered_color, generated_pressed_color}; } Vulnerability Type: CWE ID: CWE-20 Summary: The extensions API in Google Chrome prior to 55.0.2883.75 for Mac, Windows and Linux, and 55.0.2883.84 for Android incorrectly handled navigation within PDFs, which allowed a remote attacker to temporarily spoof the contents of the Omnibox (URL bar) via a crafted HTML page containing PDF data. Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <bsep@chromium.org> Reviewed-by: Taylor Bergquist <tbergquist@chromium.org> Cr-Commit-Position: refs/heads/master@{#660498}
Medium
3,121
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: GF_Err urn_Read(GF_Box *s, GF_BitStream *bs) { u32 i, to_read; char *tmpName; GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s; if (! ptr->size ) return GF_OK; to_read = (u32) ptr->size; tmpName = (char*)gf_malloc(sizeof(char) * to_read); if (!tmpName) return GF_OUT_OF_MEM; gf_bs_read_data(bs, tmpName, to_read); i = 0; while ( (tmpName[i] != 0) && (i < to_read) ) { i++; } if (i == to_read) { gf_free(tmpName); return GF_ISOM_INVALID_FILE; } if (i == to_read - 1) { ptr->nameURN = tmpName; ptr->location = NULL; return GF_OK; } ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1)); if (!ptr->nameURN) { gf_free(tmpName); return GF_OUT_OF_MEM; } ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1)); if (!ptr->location) { gf_free(tmpName); gf_free(ptr->nameURN); ptr->nameURN = NULL; return GF_OUT_OF_MEM; } memcpy(ptr->nameURN, tmpName, i + 1); memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1)); gf_free(tmpName); return GF_OK; } Vulnerability Type: CWE ID: CWE-125 Summary: An issue was discovered in MP4Box in GPAC 0.7.1. There is a heap-based buffer over-read in the isomedia/box_dump.c function hdlr_dump. Commit Message: fixed 2 possible heap overflows (inc. #1088)
Low
9,635
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: context_length_arg (char const *str, int *out) { uintmax_t value; if (! (xstrtoumax (str, 0, 10, &value, "") == LONGINT_OK && 0 <= (*out = value) && *out == value)) { error (EXIT_TROUBLE, 0, "%s: %s", str, _("invalid context length argument")); } page size, unless a read yields a partial page. */ static char *buffer; /* Base of buffer. */ static size_t bufalloc; /* Allocated buffer size, counting slop. */ #define INITIAL_BUFSIZE 32768 /* Initial buffer size, not counting slop. */ static int bufdesc; /* File descriptor. */ static char *bufbeg; /* Beginning of user-visible stuff. */ static char *buflim; /* Limit of user-visible stuff. */ static size_t pagesize; /* alignment of memory pages */ static off_t bufoffset; /* Read offset; defined on regular files. */ static off_t after_last_match; /* Pointer after last matching line that would have been output if we were outputting characters. */ /* Return VAL aligned to the next multiple of ALIGNMENT. VAL can be an integer or a pointer. Both args must be free of side effects. */ #define ALIGN_TO(val, alignment) \ ((size_t) (val) % (alignment) == 0 \ ? (val) \ : (val) + ((alignment) - (size_t) (val) % (alignment))) /* Reset the buffer for a new file, returning zero if we should skip it. Initialize on the first time through. */ static int reset (int fd, char const *file, struct stats *stats) { if (! pagesize) { pagesize = getpagesize (); if (pagesize == 0 || 2 * pagesize + 1 <= pagesize) abort (); bufalloc = ALIGN_TO (INITIAL_BUFSIZE, pagesize) + pagesize + 1; buffer = xmalloc (bufalloc); } bufbeg = buflim = ALIGN_TO (buffer + 1, pagesize); bufbeg[-1] = eolbyte; bufdesc = fd; if (S_ISREG (stats->stat.st_mode)) { if (file) bufoffset = 0; else { bufoffset = lseek (fd, 0, SEEK_CUR); if (bufoffset < 0) { suppressible_error (_("lseek failed"), errno); return 0; } } } return 1; } /* Read new stuff into the buffer, saving the specified amount of old stuff. When we're done, 'bufbeg' points to the beginning of the buffer contents, and 'buflim' points just after the end. Return zero if there's an error. */ static int fillbuf (size_t save, struct stats const *stats) { size_t fillsize = 0; int cc = 1; char *readbuf; size_t readsize; /* Offset from start of buffer to start of old stuff that we want to save. */ size_t saved_offset = buflim - save - buffer; if (pagesize <= buffer + bufalloc - buflim) { readbuf = buflim; bufbeg = buflim - save; } else { size_t minsize = save + pagesize; size_t newsize; size_t newalloc; char *newbuf; /* Grow newsize until it is at least as great as minsize. */ for (newsize = bufalloc - pagesize - 1; newsize < minsize; newsize *= 2) if (newsize * 2 < newsize || newsize * 2 + pagesize + 1 < newsize * 2) xalloc_die (); /* Try not to allocate more memory than the file size indicates, as that might cause unnecessary memory exhaustion if the file is large. However, do not use the original file size as a heuristic if we've already read past the file end, as most likely the file is growing. */ if (S_ISREG (stats->stat.st_mode)) { off_t to_be_read = stats->stat.st_size - bufoffset; off_t maxsize_off = save + to_be_read; if (0 <= to_be_read && to_be_read <= maxsize_off && maxsize_off == (size_t) maxsize_off && minsize <= (size_t) maxsize_off && (size_t) maxsize_off < newsize) newsize = maxsize_off; } /* Add enough room so that the buffer is aligned and has room for byte sentinels fore and aft. */ newalloc = newsize + pagesize + 1; newbuf = bufalloc < newalloc ? xmalloc (bufalloc = newalloc) : buffer; readbuf = ALIGN_TO (newbuf + 1 + save, pagesize); bufbeg = readbuf - save; memmove (bufbeg, buffer + saved_offset, save); bufbeg[-1] = eolbyte; if (newbuf != buffer) { free (buffer); buffer = newbuf; } } readsize = buffer + bufalloc - readbuf; readsize -= readsize % pagesize; if (! fillsize) { ssize_t bytesread; while ((bytesread = read (bufdesc, readbuf, readsize)) < 0 && errno == EINTR) continue; if (bytesread < 0) cc = 0; else fillsize = bytesread; } bufoffset += fillsize; #if defined HAVE_DOS_FILE_CONTENTS if (fillsize) fillsize = undossify_input (readbuf, fillsize); #endif buflim = readbuf + fillsize; return cc; } /* Flags controlling the style of output. */ static enum { BINARY_BINARY_FILES, TEXT_BINARY_FILES, WITHOUT_MATCH_BINARY_FILES } binary_files; /* How to handle binary files. */ static int filename_mask; /* If zero, output nulls after filenames. */ static int out_quiet; /* Suppress all normal output. */ static int out_invert; /* Print nonmatching stuff. */ static int out_file; /* Print filenames. */ static int out_line; /* Print line numbers. */ static int out_byte; /* Print byte offsets. */ static int out_before; /* Lines of leading context. */ static int out_after; /* Lines of trailing context. */ static int out_file; /* Print filenames. */ static int out_line; /* Print line numbers. */ static int out_byte; /* Print byte offsets. */ static int out_before; /* Lines of leading context. */ static int out_after; /* Lines of trailing context. */ static int count_matches; /* Count matching lines. */ static int list_files; /* List matching files. */ static int no_filenames; /* Suppress file names. */ static off_t max_count; /* Stop after outputting this many lines from an input file. */ static int line_buffered; /* If nonzero, use line buffering, i.e. fflush everyline out. */ static char const *lastnl; /* Pointer after last newline counted. */ static char const *lastout; /* Pointer after last character output; NULL if no character has been output or if it's conceptually before bufbeg. */ static uintmax_t totalnl; /* Total newline count before lastnl. */ static off_t outleft; /* Maximum number of lines to be output. */ static int pending; /* Pending lines of output. NULL if no character has been output or if it's conceptually before bufbeg. */ static uintmax_t totalnl; /* Total newline count before lastnl. */ static off_t outleft; /* Maximum number of lines to be output. */ static int pending; /* Pending lines of output. Always kept 0 if out_quiet is true. */ static int done_on_match; /* Stop scanning file on first match. */ static int exit_on_match; /* Exit on first match. */ /* Add two numbers that count input bytes or lines, and report an error if the addition overflows. */ static uintmax_t add_count (uintmax_t a, uintmax_t b) { uintmax_t sum = a + b; if (sum < a) error (EXIT_TROUBLE, 0, _("input is too large to count")); return sum; } static void nlscan (char const *lim) { size_t newlines = 0; char const *beg; for (beg = lastnl; beg < lim; beg++) { beg = memchr (beg, eolbyte, lim - beg); if (!beg) break; newlines++; } totalnl = add_count (totalnl, newlines); lastnl = lim; } /* Print the current filename. */ static void print_filename (void) { pr_sgr_start_if (filename_color); fputs (filename, stdout); pr_sgr_end_if (filename_color); } /* Print a character separator. */ static void print_sep (char sep) { pr_sgr_start_if (sep_color); fputc (sep, stdout); pr_sgr_end_if (sep_color); } /* Print a line number or a byte offset. */ static void print_offset (uintmax_t pos, int min_width, const char *color) { /* Do not rely on printf to print pos, since uintmax_t may be longer than long, and long long is not portable. */ char buf[sizeof pos * CHAR_BIT]; char *p = buf + sizeof buf; do { *--p = '0' + pos % 10; --min_width; } while ((pos /= 10) != 0); /* Do this to maximize the probability of alignment across lines. */ if (align_tabs) while (--min_width >= 0) *--p = ' '; pr_sgr_start_if (color); fwrite (p, 1, buf + sizeof buf - p, stdout); pr_sgr_end_if (color); } /* Print a whole line head (filename, line, byte). */ static void print_line_head (char const *beg, char const *lim, int sep) { int pending_sep = 0; if (out_file) { print_filename (); if (filename_mask) pending_sep = 1; else fputc (0, stdout); } if (out_line) { if (lastnl < lim) { nlscan (beg); totalnl = add_count (totalnl, 1); lastnl = lim; } if (pending_sep) print_sep (sep); print_offset (totalnl, 4, line_num_color); pending_sep = 1; } if (out_byte) { uintmax_t pos = add_count (totalcc, beg - bufbeg); #if defined HAVE_DOS_FILE_CONTENTS pos = dossified_pos (pos); #endif if (pending_sep) print_sep (sep); print_offset (pos, 6, byte_num_color); pending_sep = 1; } if (pending_sep) { /* This assumes sep is one column wide. Try doing this any other way with Unicode (and its combining and wide characters) filenames and you're wasting your efforts. */ if (align_tabs) fputs ("\t\b", stdout); print_sep (sep); } } static const char * print_line_middle (const char *beg, const char *lim, const char *line_color, const char *match_color) { size_t match_size; size_t match_offset; const char *cur = beg; const char *mid = NULL; while (cur < lim && ((match_offset = execute (beg, lim - beg, &match_size, beg + (cur - beg))) != (size_t) -1)) { char const *b = beg + match_offset; /* Avoid matching the empty line at the end of the buffer. */ if (b == lim) break; /* Avoid hanging on grep --color "" foo */ if (match_size == 0) { /* Make minimal progress; there may be further non-empty matches. */ /* XXX - Could really advance by one whole multi-octet character. */ match_size = 1; if (!mid) mid = cur; } else { /* This function is called on a matching line only, but is it selected or rejected/context? */ if (only_matching) print_line_head (b, lim, (out_invert ? SEP_CHAR_REJECTED : SEP_CHAR_SELECTED)); else { pr_sgr_start (line_color); if (mid) { cur = mid; mid = NULL; } fwrite (cur, sizeof (char), b - cur, stdout); } pr_sgr_start_if (match_color); fwrite (b, sizeof (char), match_size, stdout); pr_sgr_end_if (match_color); if (only_matching) fputs ("\n", stdout); } cur = b + match_size; } if (only_matching) cur = lim; else if (mid) cur = mid; return cur; } static const char * print_line_tail (const char *beg, const char *lim, const char *line_color) { size_t eol_size; size_t tail_size; eol_size = (lim > beg && lim[-1] == eolbyte); eol_size += (lim - eol_size > beg && lim[-(1 + eol_size)] == '\r'); tail_size = lim - eol_size - beg; if (tail_size > 0) { pr_sgr_start (line_color); fwrite (beg, 1, tail_size, stdout); beg += tail_size; pr_sgr_end (line_color); } return beg; } static void prline (char const *beg, char const *lim, int sep) { int matching; const char *line_color; const char *match_color; if (!only_matching) print_line_head (beg, lim, sep); matching = (sep == SEP_CHAR_SELECTED) ^ !!out_invert; if (color_option) { line_color = (((sep == SEP_CHAR_SELECTED) ^ (out_invert && (color_option < 0))) ? selected_line_color : context_line_color); match_color = (sep == SEP_CHAR_SELECTED ? selected_match_color : context_match_color); } else line_color = match_color = NULL; /* Shouldn't be used. */ if ((only_matching && matching) || (color_option && (*line_color || *match_color))) { /* We already know that non-matching lines have no match (to colorize). */ if (matching && (only_matching || *match_color)) beg = print_line_middle (beg, lim, line_color, match_color); /* FIXME: this test may be removable. */ if (!only_matching && *line_color) beg = print_line_tail (beg, lim, line_color); } if (!only_matching && lim > beg) fwrite (beg, 1, lim - beg, stdout); if (ferror (stdout)) { write_error_seen = 1; error (EXIT_TROUBLE, 0, _("write error")); } lastout = lim; if (line_buffered) fflush (stdout); } /* Print pending lines of trailing context prior to LIM. Trailing context ends at the next matching line when OUTLEFT is 0. */ static void prpending (char const *lim) { if (!lastout) lastout = bufbeg; while (pending > 0 && lastout < lim) { char const *nl = memchr (lastout, eolbyte, lim - lastout); size_t match_size; --pending; if (outleft || ((execute (lastout, nl + 1 - lastout, &match_size, NULL) == (size_t) -1) == !out_invert)) prline (lastout, nl + 1, SEP_CHAR_REJECTED); else pending = 0; } } /* Print the lines between BEG and LIM. Deal with context crap. If NLINESP is non-null, store a count of lines between BEG and LIM. */ static void prtext (char const *beg, char const *lim, int *nlinesp) { /* Print the lines between BEG and LIM. Deal with context crap. If NLINESP is non-null, store a count of lines between BEG and LIM. */ static void prtext (char const *beg, char const *lim, int *nlinesp) { static int used; /* avoid printing SEP_STR_GROUP before any output */ char const *bp, *p; char eol = eolbyte; int i, n; if (!out_quiet && pending > 0) prpending (beg); /* Deal with leading context crap. */ bp = lastout ? lastout : bufbeg; for (i = 0; i < out_before; ++i) if (p > bp) do --p; while (p[-1] != eol); /* We print the SEP_STR_GROUP separator only if our output is discontiguous from the last output in the file. */ if ((out_before || out_after) && used && p != lastout && group_separator) { pr_sgr_start_if (sep_color); fputs (group_separator, stdout); pr_sgr_end_if (sep_color); fputc ('\n', stdout); } while (p < beg) { char const *nl = memchr (p, eol, beg - p); nl++; prline (p, nl, SEP_CHAR_REJECTED); p = nl; } } if (nlinesp) { /* Caller wants a line count. */ for (n = 0; p < lim && n < outleft; n++) { char const *nl = memchr (p, eol, lim - p); nl++; if (!out_quiet) prline (p, nl, SEP_CHAR_SELECTED); p = nl; } *nlinesp = n; /* relying on it that this function is never called when outleft = 0. */ after_last_match = bufoffset - (buflim - p); } else if (!out_quiet) prline (beg, lim, SEP_CHAR_SELECTED); pending = out_quiet ? 0 : out_after; used = 1; } static size_t do_execute (char const *buf, size_t size, size_t *match_size, char const *start_ptr) { size_t result; const char *line_next; /* With the current implementation, using --ignore-case with a multi-byte character set is very inefficient when applied to a large buffer containing many matches. We can avoid much of the wasted effort by matching line-by-line. FIXME: this is just an ugly workaround, and it doesn't really belong here. Also, PCRE is always using this same per-line matching algorithm. Either we fix -i, or we should refactor this code---for example, we could add another function pointer to struct matcher to split the buffer passed to execute. It would perform the memchr if line-by-line matching is necessary, or just return buf + size otherwise. */ if (MB_CUR_MAX == 1 || !match_icase) return execute (buf, size, match_size, start_ptr); for (line_next = buf; line_next < buf + size; ) { const char *line_buf = line_next; const char *line_end = memchr (line_buf, eolbyte, (buf + size) - line_buf); if (line_end == NULL) line_next = line_end = buf + size; else line_next = line_end + 1; if (start_ptr && start_ptr >= line_end) continue; result = execute (line_buf, line_next - line_buf, match_size, start_ptr); if (result != (size_t) -1) return (line_buf - buf) + result; } return (size_t) -1; } /* Scan the specified portion of the buffer, matching lines (or between matching lines if OUT_INVERT is true). Return a count of lines printed. */ static int grepbuf (char const *beg, char const *lim) /* Scan the specified portion of the buffer, matching lines (or between matching lines if OUT_INVERT is true). Return a count of lines printed. */ static int grepbuf (char const *beg, char const *lim) { int nlines, n; char const *p; size_t match_offset; size_t match_size; { char const *b = p + match_offset; char const *endp = b + match_size; /* Avoid matching the empty line at the end of the buffer. */ if (b == lim) break; if (!out_invert) { prtext (b, endp, (int *) 0); nlines++; break; if (!out_invert) { prtext (b, endp, (int *) 0); nlines++; outleft--; if (!outleft || done_on_match) } } else if (p < b) { prtext (p, b, &n); nlines += n; outleft -= n; if (!outleft) return nlines; } p = endp; } if (out_invert && p < lim) { prtext (p, lim, &n); nlines += n; outleft -= n; } return nlines; } /* Search a given file. Normally, return a count of lines printed; but if the file is a directory and we search it recursively, then return -2 if there was a match, and -1 otherwise. */ static int grep (int fd, char const *file, struct stats *stats) /* Search a given file. Normally, return a count of lines printed; but if the file is a directory and we search it recursively, then return -2 if there was a match, and -1 otherwise. */ static int grep (int fd, char const *file, struct stats *stats) { int nlines, i; int not_text; size_t residue, save; char oldc; return 0; if (file && directories == RECURSE_DIRECTORIES && S_ISDIR (stats->stat.st_mode)) { /* Close fd now, so that we don't open a lot of file descriptors when we recurse deeply. */ if (close (fd) != 0) suppressible_error (file, errno); return grepdir (file, stats) - 2; } totalcc = 0; lastout = 0; totalnl = 0; outleft = max_count; after_last_match = 0; pending = 0; nlines = 0; residue = 0; save = 0; if (! fillbuf (save, stats)) { suppressible_error (filename, errno); return 0; } not_text = (((binary_files == BINARY_BINARY_FILES && !out_quiet) || binary_files == WITHOUT_MATCH_BINARY_FILES) && memchr (bufbeg, eol ? '\0' : '\200', buflim - bufbeg)); if (not_text && binary_files == WITHOUT_MATCH_BINARY_FILES) return 0; done_on_match += not_text; out_quiet += not_text; for (;;) { lastnl = bufbeg; if (lastout) lastout = bufbeg; beg = bufbeg + save; /* no more data to scan (eof) except for maybe a residue -> break */ if (beg == buflim) break; /* Determine new residue (the length of an incomplete line at the end of the buffer, 0 means there is no incomplete last line). */ oldc = beg[-1]; beg[-1] = eol; for (lim = buflim; lim[-1] != eol; lim--) continue; beg[-1] = oldc; if (lim == beg) lim = beg - residue; beg -= residue; residue = buflim - lim; if (beg < lim) { if (outleft) nlines += grepbuf (beg, lim); if (pending) prpending (lim); if ((!outleft && !pending) || (nlines && done_on_match && !out_invert)) goto finish_grep; } /* The last OUT_BEFORE lines at the end of the buffer will be needed as leading context if there is a matching line at the begin of the next data. Make beg point to their begin. */ i = 0; beg = lim; while (i < out_before && beg > bufbeg && beg != lastout) { ++i; do --beg; while (beg[-1] != eol); } /* detect if leading context is discontinuous from last printed line. */ if (beg != lastout) lastout = 0; /* Handle some details and read more data to scan. */ save = residue + lim - beg; if (out_byte) totalcc = add_count (totalcc, buflim - bufbeg - save); if (out_line) nlscan (beg); if (! fillbuf (save, stats)) { suppressible_error (filename, errno); goto finish_grep; } } if (residue) { *buflim++ = eol; if (outleft) nlines += grepbuf (bufbeg + save - residue, buflim); if (pending) prpending (buflim); } finish_grep: done_on_match -= not_text; out_quiet -= not_text; if ((not_text & ~out_quiet) && nlines != 0) printf (_("Binary file %s matches\n"), filename); return nlines; } static int grepfile (char const *file, struct stats *stats) { int desc; int count; int status; grepfile (char const *file, struct stats *stats) { int desc; int count; int status; filename = (file ? file : label ? label : _("(standard input)")); /* Don't open yet, since that might have side effects on a device. */ desc = -1; } else { /* When skipping directories, don't worry about directories that can't be opened. */ desc = open (file, O_RDONLY); if (desc < 0 && directories != SKIP_DIRECTORIES) { suppressible_error (file, errno); return 1; } } if (desc < 0 ? stat (file, &stats->stat) != 0 : fstat (desc, &stats->stat) != 0) { suppressible_error (filename, errno); if (file) close (desc); return 1; } if ((directories == SKIP_DIRECTORIES && S_ISDIR (stats->stat.st_mode)) || (devices == SKIP_DEVICES && (S_ISCHR (stats->stat.st_mode) || S_ISBLK (stats->stat.st_mode) || S_ISSOCK (stats->stat.st_mode) || S_ISFIFO (stats->stat.st_mode)))) { if (file) close (desc); return 1; } /* If there is a regular file on stdout and the current file refers to the same i-node, we have to report the problem and skip it. Otherwise when matching lines from some other input reach the disk before we open this file, we can end up reading and matching those lines and appending them to the file from which we're reading. Then we'd have what appears to be an infinite loop that'd terminate only upon filling the output file system or reaching a quota. However, there is no risk of an infinite loop if grep is generating no output, i.e., with --silent, --quiet, -q. Similarly, with any of these: --max-count=N (-m) (for N >= 2) --files-with-matches (-l) --files-without-match (-L) there is no risk of trouble. For --max-count=1, grep stops after printing the first match, so there is no risk of malfunction. But even --max-count=2, with input==output, while there is no risk of infloop, there is a race condition that could result in "alternate" output. */ if (!out_quiet && list_files == 0 && 1 < max_count && S_ISREG (out_stat.st_mode) && out_stat.st_ino && SAME_INODE (stats->stat, out_stat)) { if (! suppress_errors) error (0, 0, _("input file %s is also the output"), quote (filename)); errseen = 1; if (file) close (desc); return 1; } if (desc < 0) { desc = open (file, O_RDONLY); if (desc < 0) { suppressible_error (file, errno); return 1; } } #if defined SET_BINARY /* Set input to binary mode. Pipes are simulated with files on DOS, so this includes the case of "foo | grep bar". */ if (!isatty (desc)) SET_BINARY (desc); #endif count = grep (desc, file, stats); if (count < 0) status = count + 2; else { if (count_matches) { if (out_file) { print_filename (); if (filename_mask) print_sep (SEP_CHAR_SELECTED); else fputc (0, stdout); } printf ("%d\n", count); } else fputc (0, stdout); } printf ("%d\n", count); } status = !count; if (! file) { off_t required_offset = outleft ? bufoffset : after_last_match; if (required_offset != bufoffset && lseek (desc, required_offset, SEEK_SET) < 0 && S_ISREG (stats->stat.st_mode)) suppressible_error (filename, errno); } else while (close (desc) != 0) if (errno != EINTR) { suppressible_error (file, errno); break; } } Vulnerability Type: Exec Code Overflow CWE ID: CWE-189 Summary: Multiple integer overflows in GNU Grep before 2.11 might allow context-dependent attackers to execute arbitrary code via vectors involving a long input line that triggers a heap-based buffer overflow. Commit Message:
Medium
9,585
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: PHP_METHOD(Phar, extractTo) { char *error = NULL; php_stream *fp; php_stream_statbuf ssb; phar_entry_info *entry; char *pathto, *filename; size_t pathto_len, filename_len; int ret, i; int nelems; zval *zval_files = NULL; zend_bool overwrite = 0; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|z!b", &pathto, &pathto_len, &zval_files, &overwrite) == FAILURE) { return; } fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, NULL); if (!fp) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, %s cannot be found", phar_obj->archive->fname); return; } php_stream_close(fp); if (pathto_len < 1) { zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, extraction path must be non-zero length"); return; } if (pathto_len >= MAXPATHLEN) { char *tmp = estrndup(pathto, 50); /* truncate for error message */ zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp); efree(tmp); return; } if (php_stream_stat_path(pathto, &ssb) < 0) { ret = php_stream_mkdir(pathto, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL); if (!ret) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to create path \"%s\" for extraction", pathto); return; } } else if (!(ssb.sb.st_mode & S_IFDIR)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto); return; } if (zval_files) { switch (Z_TYPE_P(zval_files)) { case IS_NULL: goto all_files; case IS_STRING: filename = Z_STRVAL_P(zval_files); filename_len = Z_STRLEN_P(zval_files); break; case IS_ARRAY: nelems = zend_hash_num_elements(Z_ARRVAL_P(zval_files)); if (nelems == 0 ) { RETURN_FALSE; } for (i = 0; i < nelems; i++) { zval *zval_file; if ((zval_file = zend_hash_index_find(Z_ARRVAL_P(zval_files), i)) != NULL) { switch (Z_TYPE_P(zval_file)) { case IS_STRING: break; default: zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, array of filenames to extract contains non-string value"); return; } if (NULL == (entry = zend_hash_find_ptr(&phar_obj->archive->manifest, Z_STR_P(zval_file)))) { zend_throw_exception_ex(phar_ce_PharException, 0, "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", Z_STRVAL_P(zval_file), phar_obj->archive->fname); } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error); efree(error); return; } } } RETURN_TRUE; default: zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Invalid argument, expected a filename (string) or array of filenames"); return; } if (NULL == (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, filename, filename_len))) { zend_throw_exception_ex(phar_ce_PharException, 0, "Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", filename, phar_obj->archive->fname); return; } if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error); efree(error); return; } } else { phar_archive_data *phar; all_files: phar = phar_obj->archive; /* Extract all files */ if (!zend_hash_num_elements(&(phar->manifest))) { RETURN_TRUE; } ZEND_HASH_FOREACH_PTR(&phar->manifest, entry) { if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Extraction from phar \"%s\" failed: %s", phar->fname, error); efree(error); return; } } ZEND_HASH_FOREACH_END(); } RETURN_TRUE; } Vulnerability Type: Exec Code CWE ID: CWE-20 Summary: The Phar extension in PHP before 5.5.34, 5.6.x before 5.6.20, and 7.x before 7.0.5 allows remote attackers to execute arbitrary code via a crafted filename, as demonstrated by mishandling of \0 characters by the phar_analyze_path function in ext/phar/phar.c. Commit Message:
Low
2,926
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg) { const unsigned char *p; int plen; if (alg == NULL) return NULL; if (OBJ_obj2nid(alg->algorithm) != NID_mgf1) return NULL; if (alg->parameter->type != V_ASN1_SEQUENCE) return NULL; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; return d2i_X509_ALGOR(NULL, &p, plen); } Vulnerability Type: DoS CWE ID: Summary: crypto/rsa/rsa_ameth.c in OpenSSL 1.0.1 before 1.0.1q and 1.0.2 before 1.0.2e allows remote attackers to cause a denial of service (NULL pointer dereference and application crash) via an RSA PSS ASN.1 signature that lacks a mask generation function parameter. Commit Message:
Low
12,348
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char l, n = 0; char callsign[11]; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; if (*p == FAC_CCITT_DEST_NSAP) { memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->source_call, callsign); } if (*p == FAC_CCITT_SRC_NSAP) { memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->dest_call, callsign); } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; } Vulnerability Type: DoS Overflow Mem. Corr. CWE ID: CWE-20 Summary: The rose_parse_ccitt function in net/rose/rose_subr.c in the Linux kernel before 2.6.39 does not validate the FAC_CCITT_DEST_NSAP and FAC_CCITT_SRC_NSAP fields, which allows remote attackers to (1) cause a denial of service (integer underflow, heap memory corruption, and panic) via a small length value in data sent to a ROSE socket, or (2) conduct stack-based buffer overflow attacks via a large length value in data sent to a ROSE socket. Commit Message: ROSE: prevent heap corruption with bad facilities When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for a remote host to provide more digipeaters than expected, resulting in heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and abort facilities parsing on failure. Additionally, when parsing the FAC_CCITT_DEST_NSAP and FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length of less than 10, resulting in an underflow in a memcpy size, causing a kernel panic due to massive heap corruption. A length of greater than 20 results in a stack overflow of the callsign array. Abort facilities parsing on these invalid length values. Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com> Cc: stable@kernel.org Signed-off-by: David S. Miller <davem@davemloft.net>
Low
21,026
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void RenderFrameHostImpl::RegisterMojoInterfaces() { #if !defined(OS_ANDROID) registry_->AddInterface(base::Bind(&InstalledAppProviderImplDefault::Create)); #endif // !defined(OS_ANDROID) PermissionControllerImpl* permission_controller = PermissionControllerImpl::FromBrowserContext( GetProcess()->GetBrowserContext()); if (delegate_) { auto* geolocation_context = delegate_->GetGeolocationContext(); if (geolocation_context) { geolocation_service_.reset(new GeolocationServiceImpl( geolocation_context, permission_controller, this)); registry_->AddInterface( base::Bind(&GeolocationServiceImpl::Bind, base::Unretained(geolocation_service_.get()))); } } registry_->AddInterface<device::mojom::WakeLock>(base::Bind( &RenderFrameHostImpl::BindWakeLockRequest, base::Unretained(this))); #if defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebNfc)) { registry_->AddInterface<device::mojom::NFC>(base::Bind( &RenderFrameHostImpl::BindNFCRequest, base::Unretained(this))); } #endif if (!permission_service_context_) permission_service_context_.reset(new PermissionServiceContext(this)); registry_->AddInterface( base::Bind(&PermissionServiceContext::CreateService, base::Unretained(permission_service_context_.get()))); registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindPresentationServiceRequest, base::Unretained(this))); registry_->AddInterface( base::Bind(&MediaSessionServiceImpl::Create, base::Unretained(this))); registry_->AddInterface(base::Bind( base::IgnoreResult(&RenderFrameHostImpl::CreateWebBluetoothService), base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebUsbService, base::Unretained(this))); registry_->AddInterface<media::mojom::InterfaceFactory>( base::Bind(&RenderFrameHostImpl::BindMediaInterfaceFactoryRequest, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebSocket, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateDedicatedWorkerHostFactory, base::Unretained(this))); registry_->AddInterface(base::Bind(&SharedWorkerConnectorImpl::Create, process_->GetID(), routing_id_)); registry_->AddInterface(base::BindRepeating(&device::GamepadMonitor::Create)); registry_->AddInterface<device::mojom::VRService>(base::Bind( &WebvrServiceProvider::BindWebvrService, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioInputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioOutputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::Bind(&CreateFrameResourceCoordinator, base::Unretained(this))); if (BrowserMainLoop::GetInstance()) { MediaStreamManager* media_stream_manager = BrowserMainLoop::GetInstance()->media_stream_manager(); registry_->AddInterface( base::Bind(&MediaDevicesDispatcherHost::Create, GetProcess()->GetID(), GetRoutingID(), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); registry_->AddInterface( base::BindRepeating( &RenderFrameHostImpl::CreateMediaStreamDispatcherHost, base::Unretained(this), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); } #if BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::Bind(&RemoterFactoryImpl::Bind, GetProcess()->GetID(), GetRoutingID())); #endif // BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::BindRepeating( &KeyboardLockServiceImpl::CreateMojoService, base::Unretained(this))); registry_->AddInterface(base::Bind(&ImageCaptureImpl::Create)); #if !defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebAuth)) { registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindAuthenticatorRequest, base::Unretained(this))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableWebAuthTestingAPI)) { auto* environment_singleton = ScopedVirtualAuthenticatorEnvironment::GetInstance(); registry_->AddInterface(base::BindRepeating( &ScopedVirtualAuthenticatorEnvironment::AddBinding, base::Unretained(environment_singleton))); } } #endif // !defined(OS_ANDROID) sensor_provider_proxy_.reset( new SensorProviderProxyImpl(permission_controller, this)); registry_->AddInterface( base::Bind(&SensorProviderProxyImpl::Bind, base::Unretained(sensor_provider_proxy_.get()))); media::VideoDecodePerfHistory::SaveCallback save_stats_cb; if (GetSiteInstance()->GetBrowserContext()->GetVideoDecodePerfHistory()) { save_stats_cb = GetSiteInstance() ->GetBrowserContext() ->GetVideoDecodePerfHistory() ->GetSaveCallback(); } registry_->AddInterface(base::BindRepeating( &media::MediaMetricsProvider::Create, frame_tree_node_->IsMainFrame(), base::BindRepeating( &RenderFrameHostDelegate::GetUkmSourceIdForLastCommittedSource, base::Unretained(delegate_)), std::move(save_stats_cb))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( cc::switches::kEnableGpuBenchmarking)) { registry_->AddInterface( base::Bind(&InputInjectorImpl::Create, weak_ptr_factory_.GetWeakPtr())); } registry_->AddInterface(base::BindRepeating( &QuotaDispatcherHost::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface( base::BindRepeating(SpeechRecognitionDispatcherHost::Create, GetProcess()->GetID(), routing_id_), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); file_system_manager_.reset(new FileSystemManagerImpl( GetProcess()->GetID(), routing_id_, GetProcess()->GetStoragePartition()->GetFileSystemContext(), ChromeBlobStorageContext::GetFor(GetProcess()->GetBrowserContext()))); registry_->AddInterface( base::BindRepeating(&FileSystemManagerImpl::BindRequest, base::Unretained(file_system_manager_.get())), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); if (Portal::IsEnabled()) { registry_->AddInterface(base::BindRepeating(IgnoreResult(&Portal::Create), base::Unretained(this))); } registry_->AddInterface(base::BindRepeating( &BackgroundFetchServiceImpl::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface(base::BindRepeating(&ContactsManagerImpl::Create)); registry_->AddInterface( base::BindRepeating(&FileChooserImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&AudioContextManagerImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&WakeLockServiceImpl::Create, base::Unretained(this))); } Vulnerability Type: CWE ID: CWE-189 Summary: Incorrect handling of negative zero in V8 in Google Chrome prior to 72.0.3626.81 allowed a remote attacker to perform arbitrary read/write via a crafted HTML page. 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 <emircan@chromium.org> Reviewed-by: Ken Buchanan <kenrb@chromium.org> Reviewed-by: Olga Sharonova <olka@chromium.org> Commit-Queue: Guido Urdaneta <guidou@chromium.org> Cr-Commit-Position: refs/heads/master@{#616347}
Medium
11,316
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int sgi_clock_get(clockid_t clockid, struct timespec *tp) { u64 nsec; nsec = rtc_time() * sgi_clock_period + sgi_clock_offset.tv_nsec; tp->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &tp->tv_nsec) + sgi_clock_offset.tv_sec; return 0; }; Vulnerability Type: DoS CWE ID: CWE-189 Summary: The div_long_long_rem implementation in include/asm-x86/div64.h in the Linux kernel before 2.6.26 on the x86 platform allows local users to cause a denial of service (Divide Error Fault and panic) via a clock_gettime system call. Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <zippel@linux-m68k.org> Cc: Ralf Baechle <ralf@linux-mips.org> Cc: Ingo Molnar <mingo@elte.hu> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: john stultz <johnstul@us.ibm.com> Cc: Christoph Lameter <clameter@sgi.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Low
21,150
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void MemoryInstrumentation::GetVmRegionsForHeapProfiler( RequestGlobalDumpCallback callback) { const auto& coordinator = GetCoordinatorBindingForCurrentThread(); coordinator->GetVmRegionsForHeapProfiler(callback); } Vulnerability Type: CWE ID: CWE-269 Summary: Lack of access control checks in Instrumentation in Google Chrome prior to 65.0.3325.146 allowed a remote attacker who had compromised the renderer process to obtain memory metadata from privileged processes . Commit Message: memory-infra: split up memory-infra coordinator service into two This allows for heap profiler to use its own service with correct capabilities and all other instances to use the existing coordinator service. Bug: 792028 Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd Reviewed-on: https://chromium-review.googlesource.com/836896 Commit-Queue: Lalit Maganti <lalitm@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: oysteine <oysteine@chromium.org> Reviewed-by: Albert J. Wong <ajwong@chromium.org> Reviewed-by: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#529059}
Medium
29,028
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: ZSTD_compressSequences_internal(seqStore_t* seqStorePtr, ZSTD_entropyCTables_t const* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, ZSTD_CCtx_params const* cctxParams, void* dst, size_t dstCapacity, void* workspace, size_t wkspSize, const int bmi2) { const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN; ZSTD_strategy const strategy = cctxParams->cParams.strategy; U32 count[MaxSeq+1]; FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable; FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable; FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable; U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */ const seqDef* const sequences = seqStorePtr->sequencesStart; const BYTE* const ofCodeTable = seqStorePtr->ofCode; const BYTE* const llCodeTable = seqStorePtr->llCode; const BYTE* const mlCodeTable = seqStorePtr->mlCode; BYTE* const ostart = (BYTE*)dst; BYTE* const oend = ostart + dstCapacity; BYTE* op = ostart; size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart; BYTE* seqHead; BYTE* lastNCount = NULL; ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog))); /* Compress literals */ { const BYTE* const literals = seqStorePtr->litStart; size_t const litSize = seqStorePtr->lit - literals; int const disableLiteralCompression = (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0); size_t const cSize = ZSTD_compressLiterals( &prevEntropy->huf, &nextEntropy->huf, cctxParams->cParams.strategy, disableLiteralCompression, op, dstCapacity, literals, litSize, workspace, wkspSize, bmi2); if (ZSTD_isError(cSize)) return cSize; assert(cSize <= dstCapacity); op += cSize; } /* Sequences Header */ if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/) return ERROR(dstSize_tooSmall); if (nbSeq < 0x7F) *op++ = (BYTE)nbSeq; else if (nbSeq < LONGNBSEQ) op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2; else op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3; if (nbSeq==0) { /* Copy the old tables over as if we repeated them */ memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse)); return op - ostart; } /* seqHead : flags for FSE encoding type */ seqHead = op++; /* convert length/distances into codes */ ZSTD_seqToCodes(seqStorePtr); /* build CTable for Literal Lengths */ { U32 max = MaxLL; size_t const mostFrequent = HIST_countFast_wksp(count, &max, llCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ DEBUGLOG(5, "Building LL table"); nextEntropy->fse.litlength_repeatMode = prevEntropy->fse.litlength_repeatMode; LLtype = ZSTD_selectEncodingType(&nextEntropy->fse.litlength_repeatMode, count, max, mostFrequent, nbSeq, LLFSELog, prevEntropy->fse.litlengthCTable, LL_defaultNorm, LL_defaultNormLog, ZSTD_defaultAllowed, strategy); assert(set_basic < set_compressed && set_rle < set_compressed); assert(!(LLtype < set_compressed && nextEntropy->fse.litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_LitLength, LLFSELog, (symbolEncodingType_e)LLtype, count, max, llCodeTable, nbSeq, LL_defaultNorm, LL_defaultNormLog, MaxLL, prevEntropy->fse.litlengthCTable, sizeof(prevEntropy->fse.litlengthCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (LLtype == set_compressed) lastNCount = op; op += countSize; } } /* build CTable for Offsets */ { U32 max = MaxOff; size_t const mostFrequent = HIST_countFast_wksp(count, &max, ofCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */ ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed; DEBUGLOG(5, "Building OF table"); nextEntropy->fse.offcode_repeatMode = prevEntropy->fse.offcode_repeatMode; Offtype = ZSTD_selectEncodingType(&nextEntropy->fse.offcode_repeatMode, count, max, mostFrequent, nbSeq, OffFSELog, prevEntropy->fse.offcodeCTable, OF_defaultNorm, OF_defaultNormLog, defaultPolicy, strategy); assert(!(Offtype < set_compressed && nextEntropy->fse.offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)Offtype, count, max, ofCodeTable, nbSeq, OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff, prevEntropy->fse.offcodeCTable, sizeof(prevEntropy->fse.offcodeCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (Offtype == set_compressed) lastNCount = op; op += countSize; } } /* build CTable for MatchLengths */ { U32 max = MaxML; size_t const mostFrequent = HIST_countFast_wksp(count, &max, mlCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ DEBUGLOG(5, "Building ML table"); nextEntropy->fse.matchlength_repeatMode = prevEntropy->fse.matchlength_repeatMode; MLtype = ZSTD_selectEncodingType(&nextEntropy->fse.matchlength_repeatMode, count, max, mostFrequent, nbSeq, MLFSELog, prevEntropy->fse.matchlengthCTable, ML_defaultNorm, ML_defaultNormLog, ZSTD_defaultAllowed, strategy); assert(!(MLtype < set_compressed && nextEntropy->fse.matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_MatchLength, MLFSELog, (symbolEncodingType_e)MLtype, count, max, mlCodeTable, nbSeq, ML_defaultNorm, ML_defaultNormLog, MaxML, prevEntropy->fse.matchlengthCTable, sizeof(prevEntropy->fse.matchlengthCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (MLtype == set_compressed) lastNCount = op; op += countSize; } } *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2)); { size_t const bitstreamSize = ZSTD_encodeSequences( op, oend - op, CTable_MatchLength, mlCodeTable, CTable_OffsetBits, ofCodeTable, CTable_LitLength, llCodeTable, sequences, nbSeq, longOffsets, bmi2); if (ZSTD_isError(bitstreamSize)) return bitstreamSize; op += bitstreamSize; /* zstd versions <= 1.3.4 mistakenly report corruption when * FSE_readNCount() recieves a buffer < 4 bytes. * Fixed by https://github.com/facebook/zstd/pull/1146. * This can happen when the last set_compressed table present is 2 * bytes and the bitstream is only one byte. * In this exceedingly rare case, we will simply emit an uncompressed * block, since it isn't worth optimizing. */ if (lastNCount && (op - lastNCount) < 4) { /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */ assert(op - lastNCount == 3); DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by " "emitting an uncompressed block."); return 0; } } return op - ostart; } Vulnerability Type: CWE ID: CWE-362 Summary: A race condition in the one-pass compression functions of Zstandard prior to version 1.3.8 could allow an attacker to write bytes out of bounds if an output buffer smaller than the recommended size was used. Commit Message: fixed T36302429
Medium
3,737
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m, const struct iovec *iv, unsigned long total_len, size_t count, int noblock) { struct sk_buff *skb; struct macvlan_dev *vlan; unsigned long len = total_len; int err; struct virtio_net_hdr vnet_hdr = { 0 }; int vnet_hdr_len = 0; int copylen; bool zerocopy = false; if (q->flags & IFF_VNET_HDR) { vnet_hdr_len = q->vnet_hdr_sz; err = -EINVAL; if (len < vnet_hdr_len) goto err; len -= vnet_hdr_len; err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0, sizeof(vnet_hdr)); if (err < 0) goto err; if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 > vnet_hdr.hdr_len) vnet_hdr.hdr_len = vnet_hdr.csum_start + vnet_hdr.csum_offset + 2; err = -EINVAL; if (vnet_hdr.hdr_len > len) goto err; } err = -EINVAL; if (unlikely(len < ETH_HLEN)) goto err; if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY)) zerocopy = true; if (zerocopy) { /* There are 256 bytes to be copied in skb, so there is enough * room for skb expand head in case it is used. * The rest buffer is mapped from userspace. */ copylen = vnet_hdr.hdr_len; if (!copylen) copylen = GOODCOPY_LEN; } else copylen = len; skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen, vnet_hdr.hdr_len, noblock, &err); if (!skb) goto err; if (zerocopy) err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count); else err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len, len); if (err) goto err_kfree; skb_set_network_header(skb, ETH_HLEN); skb_reset_mac_header(skb); skb->protocol = eth_hdr(skb)->h_proto; if (vnet_hdr_len) { err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr); if (err) goto err_kfree; } rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = m->msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; } if (vlan) macvlan_start_xmit(skb, vlan->dev); else kfree_skb(skb); rcu_read_unlock_bh(); return total_len; err_kfree: kfree_skb(skb); err: rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); if (vlan) vlan->dev->stats.tx_dropped++; rcu_read_unlock_bh(); return err; } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: Buffer overflow in the macvtap device driver in the Linux kernel before 3.4.5, when running in certain configurations, allows privileged KVM guest users to cause a denial of service (crash) via a long descriptor with a long vector length. Commit Message: macvtap: zerocopy: validate vectors before building skb There're several reasons that the vectors need to be validated: - Return error when caller provides vectors whose num is greater than UIO_MAXIOV. - Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS. - Return error when userspace provides vectors whose total length may exceed - MAX_SKB_FRAGS * PAGE_SIZE. Signed-off-by: Jason Wang <jasowang@redhat.com> Signed-off-by: Michael S. Tsirkin <mst@redhat.com>
Medium
26,952
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void *jas_malloc(size_t size) { void *result; JAS_DBGLOG(101, ("jas_malloc called with %zu\n", size)); result = malloc(size); JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result)); return result; } Vulnerability Type: Overflow CWE ID: CWE-190 Summary: Integer overflow in the jpc_dec_tiledecode function in jpc_dec.c in JasPer before 1.900.12 allows remote attackers to have unspecified impact via a crafted image file, which triggers a heap-based buffer overflow. Commit Message: Fixed an integer overflow problem.
Medium
14,740
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams( int version, const std::string& selection, const std::string& base_page_url, int now_on_tap_version) : version(version), start(base::string16::npos), end(base::string16::npos), selection(selection), base_page_url(base_page_url), now_on_tap_version(now_on_tap_version) {} Vulnerability Type: DoS CWE ID: Summary: Multiple unspecified vulnerabilities in Google Chrome before 38.0.2125.101 allow attackers to cause a denial of service or possibly have other impact via unknown vectors. Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899}
Low
12,586
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void BufferQueueConsumer::dump(String8& result, const char* prefix) const { const IPCThreadState* ipc = IPCThreadState::self(); const pid_t pid = ipc->getCallingPid(); const uid_t uid = ipc->getCallingUid(); if ((uid != AID_SHELL) && !PermissionCache::checkPermission(String16( "android.permission.DUMP"), pid, uid)) { result.appendFormat("Permission Denial: can't dump BufferQueueConsumer " "from pid=%d, uid=%d\n", pid, uid); } else { mCore->dump(result, prefix); } } Vulnerability Type: Bypass +Info CWE ID: CWE-264 Summary: libs/gui/BufferQueueConsumer.cpp in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-04-01 does not check for the android.permission.DUMP permission, which allows attackers to obtain sensitive information, and consequently bypass an unspecified protection mechanism, via a dump request, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 27046057. Commit Message: Add SN logging Bug 27046057 Change-Id: Iede7c92e59e60795df1ec7768ebafd6b090f1c27
Low
27,228
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) { inv_txfm_(out, dst, stride, tx_type_); } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. 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
Low
15,949
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int sd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct gendisk *disk = bdev->bd_disk; struct scsi_disk *sdkp = scsi_disk(disk); struct scsi_device *sdp = sdkp->device; void __user *p = (void __user *)arg; int error; SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, " "cmd=0x%x\n", disk->disk_name, cmd)); /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ error = scsi_nonblockable_ioctl(sdp, cmd, p, (mode & FMODE_NDELAY) != 0); if (!scsi_block_when_processing_errors(sdp) || !error) goto out; /* * Send SCSI addressing ioctls directly to mid level, send other * ioctls to block level and then onto mid level if they can't be * resolved. */ switch (cmd) { case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: error = scsi_ioctl(sdp, cmd, p); break; default: error = scsi_cmd_blk_ioctl(bdev, mode, cmd, p); if (error != -ENOTTY) break; error = scsi_ioctl(sdp, cmd, p); break; } out: return error; } Vulnerability Type: Bypass CWE ID: CWE-264 Summary: The Linux kernel before 3.2.2 does not properly restrict SG_IO ioctl calls, which allows local users to bypass intended restrictions on disk read and write operations by sending a SCSI command to (1) a partition block device or (2) an LVM volume. Commit Message: block: fail SCSI passthrough ioctls on partition devices Linux allows executing the SG_IO ioctl on a partition or LVM volume, and will pass the command to the underlying block device. This is well-known, but it is also a large security problem when (via Unix permissions, ACLs, SELinux or a combination thereof) a program or user needs to be granted access only to part of the disk. This patch lets partitions forward a small set of harmless ioctls; others are logged with printk so that we can see which ioctls are actually sent. In my tests only CDROM_GET_CAPABILITY actually occurred. Of course it was being sent to a (partition on a) hard disk, so it would have failed with ENOTTY and the patch isn't changing anything in practice. Still, I'm treating it specially to avoid spamming the logs. In principle, this restriction should include programs running with CAP_SYS_RAWIO. If for example I let a program access /dev/sda2 and /dev/sdb, it still should not be able to read/write outside the boundaries of /dev/sda2 independent of the capabilities. However, for now programs with CAP_SYS_RAWIO will still be allowed to send the ioctls. Their actions will still be logged. This patch does not affect the non-libata IDE driver. That driver however already tests for bd != bd->bd_contains before issuing some ioctl; it could be restricted further to forbid these ioctls even for programs running with CAP_SYS_ADMIN/CAP_SYS_RAWIO. Cc: linux-scsi@vger.kernel.org Cc: Jens Axboe <axboe@kernel.dk> Cc: James Bottomley <JBottomley@parallels.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> [ Make it also print the command name when warning - Linus ] Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Low
13,815
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: ChildProcessTerminationInfo ChildProcessLauncherHelper::GetTerminationInfo( const ChildProcessLauncherHelper::Process& process, bool known_dead) { ChildProcessTerminationInfo info; if (!java_peer_avaiable_on_client_thread_) return info; Java_ChildProcessLauncherHelperImpl_getTerminationInfo( AttachCurrentThread(), java_peer_, reinterpret_cast<intptr_t>(&info)); base::android::ApplicationState app_state = base::android::ApplicationStatusListener::GetState(); bool app_foreground = app_state == base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES || app_state == base::android::APPLICATION_STATE_HAS_PAUSED_ACTIVITIES; if (app_foreground && (info.binding_state == base::android::ChildBindingState::MODERATE || info.binding_state == base::android::ChildBindingState::STRONG)) { info.status = base::TERMINATION_STATUS_OOM_PROTECTED; } else { info.status = base::TERMINATION_STATUS_NORMAL_TERMINATION; } return info; } Vulnerability Type: CWE ID: CWE-664 Summary: Process lifetime issue in Chrome in Google Chrome on Android prior to 74.0.3729.108 allowed a remote attacker to potentially persist an exploited process via a crafted HTML page. Commit Message: android: Stop child process in GetTerminationInfo Android currently abuses TerminationStatus to pass whether process is "oom protected" rather than whether it has died or not. This confuses cross-platform code about the state process. Only TERMINATION_STATUS_STILL_RUNNING is treated as still running, which android never passes. Also it appears to be ok to kill the process in getTerminationInfo as it's only called when the child process is dead or dying. Also posix kills the process on some calls. Bug: 940245 Change-Id: Id165711848c279bbe77ef8a784c8cf0b14051877 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1516284 Reviewed-by: Robert Sesek <rsesek@chromium.org> Reviewed-by: ssid <ssid@chromium.org> Commit-Queue: Bo <boliu@chromium.org> Cr-Commit-Position: refs/heads/master@{#639639}
Medium
27,906
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data, UINT32 scanline) { UINT16 x; UINT16 y; UINT16 rw; BYTE ccl; const BYTE* src; BYTE* yplane = NULL; BYTE* coplane = NULL; BYTE* cgplane = NULL; BYTE* aplane = NULL; INT16 r_val; INT16 g_val; INT16 b_val; BYTE a_val; UINT32 tempWidth; tempWidth = ROUND_UP_TO(context->width, 8); rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width); ccl = context->ColorLossLevel; for (y = 0; y < context->height; y++) { src = data + (context->height - 1 - y) * scanline; yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; aplane = context->priv->PlaneBuffers[3] + y * context->width; for (x = 0; x < context->width; x++) { switch (context->format) { case PIXEL_FORMAT_BGRX32: b_val = *src++; g_val = *src++; r_val = *src++; src++; a_val = 0xFF; break; case PIXEL_FORMAT_BGRA32: b_val = *src++; g_val = *src++; r_val = *src++; a_val = *src++; break; case PIXEL_FORMAT_RGBX32: r_val = *src++; g_val = *src++; b_val = *src++; src++; a_val = 0xFF; break; case PIXEL_FORMAT_RGBA32: r_val = *src++; g_val = *src++; b_val = *src++; a_val = *src++; break; case PIXEL_FORMAT_BGR24: b_val = *src++; g_val = *src++; r_val = *src++; a_val = 0xFF; break; case PIXEL_FORMAT_RGB24: r_val = *src++; g_val = *src++; b_val = *src++; a_val = 0xFF; break; case PIXEL_FORMAT_BGR16: b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)); g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)); r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)); a_val = 0xFF; src += 2; break; case PIXEL_FORMAT_RGB16: r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5)); g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3)); b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07)); a_val = 0xFF; src += 2; break; case PIXEL_FORMAT_A4: { int shift; BYTE idx; shift = (7 - (x % 8)); idx = ((*src) >> shift) & 1; idx |= (((*(src + 1)) >> shift) & 1) << 1; idx |= (((*(src + 2)) >> shift) & 1) << 2; idx |= (((*(src + 3)) >> shift) & 1) << 3; idx *= 3; r_val = (INT16) context->palette[idx]; g_val = (INT16) context->palette[idx + 1]; b_val = (INT16) context->palette[idx + 2]; if (shift == 0) src += 4; } a_val = 0xFF; break; case PIXEL_FORMAT_RGB8: { int idx = (*src) * 3; r_val = (INT16) context->palette[idx]; g_val = (INT16) context->palette[idx + 1]; b_val = (INT16) context->palette[idx + 2]; src++; } a_val = 0xFF; break; default: r_val = g_val = b_val = a_val = 0; break; } *yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2)); /* Perform color loss reduction here */ *coplane++ = (BYTE)((r_val - b_val) >> ccl); *cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl); *aplane++ = a_val; } if (context->ChromaSubsamplingLevel && (x % 2) == 1) { *yplane = *(yplane - 1); *coplane = *(coplane - 1); *cgplane = *(cgplane - 1); } } if (context->ChromaSubsamplingLevel && (y % 2) == 1) { yplane = context->priv->PlaneBuffers[0] + y * rw; coplane = context->priv->PlaneBuffers[1] + y * rw; cgplane = context->priv->PlaneBuffers[2] + y * rw; CopyMemory(yplane, yplane - rw, rw); CopyMemory(coplane, coplane - rw, rw); CopyMemory(cgplane, cgplane - rw, rw); } } Vulnerability Type: Exec Code Mem. Corr. CWE ID: CWE-787 Summary: FreeRDP prior to version 2.0.0-rc4 contains an Out-Of-Bounds Write of up to 4 bytes in function nsc_rle_decode() that results in a memory corruption and possibly even a remote code execution. Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies.
Low
12,958
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc) { struct scsi_device *SDev; struct scsi_sense_hdr sshdr; int result, err = 0, retries = 0; SDev = cd->device; retry: if (!scsi_block_when_processing_errors(SDev)) { err = -ENODEV; goto out; } result = scsi_execute(SDev, cgc->cmd, cgc->data_direction, cgc->buffer, cgc->buflen, (unsigned char *)cgc->sense, &sshdr, cgc->timeout, IOCTL_RETRIES, 0, 0, NULL); /* Minimal error checking. Ignore cases we know about, and report the rest. */ if (driver_byte(result) != 0) { switch (sshdr.sense_key) { case UNIT_ATTENTION: SDev->changed = 1; if (!cgc->quiet) sr_printk(KERN_INFO, cd, "disc change detected.\n"); if (retries++ < 10) goto retry; err = -ENOMEDIUM; break; case NOT_READY: /* This happens if there is no disc in drive */ if (sshdr.asc == 0x04 && sshdr.ascq == 0x01) { /* sense: Logical unit is in process of becoming ready */ if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready yet.\n"); if (retries++ < 10) { /* sleep 2 sec and try again */ ssleep(2); goto retry; } else { /* 20 secs are enough? */ err = -ENOMEDIUM; break; } } if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready. Make sure there " "is a disc in the drive.\n"); err = -ENOMEDIUM; break; case ILLEGAL_REQUEST: err = -EIO; if (sshdr.asc == 0x20 && sshdr.ascq == 0x00) /* sense: Invalid command operation code */ err = -EDRIVE_CANT_DO_THIS; break; default: err = -EIO; } } /* Wake up a process waiting for device */ out: cgc->stat = err; return err; } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: The sr_do_ioctl function in drivers/scsi/sr_ioctl.c in the Linux kernel through 4.16.12 allows local users to cause a denial of service (stack-based buffer overflow) or possibly have unspecified other impact because sense buffers have different sizes at the CDROM layer and the SCSI layer, as demonstrated by a CDROMREADMODE2 ioctl call. Commit Message: sr: pass down correctly sized SCSI sense buffer We're casting the CDROM layer request_sense to the SCSI sense buffer, but the former is 64 bytes and the latter is 96 bytes. As we generally allocate these on the stack, we end up blowing up the stack. Fix this by wrapping the scsi_execute() call with a properly sized sense buffer, and copying back the bits for the CDROM layer. Cc: stable@vger.kernel.org Reported-by: Piotr Gabriel Kosinski <pg.kosinski@gmail.com> Reported-by: Daniel Shapira <daniel@twistlock.com> Tested-by: Kees Cook <keescook@chromium.org> Fixes: 82ed4db499b8 ("block: split scsi_request out of struct request") Signed-off-by: Jens Axboe <axboe@kernel.dk>
Low
25,203
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void WebGraphicsContext3DCommandBufferImpl::FlipVertically( uint8* framebuffer, unsigned int width, unsigned int height) { uint8* scanline = scanline_.get(); if (!scanline) return; unsigned int row_bytes = width * 4; unsigned int count = height / 2; for (unsigned int i = 0; i < count; i++) { uint8* row_a = framebuffer + i * row_bytes; uint8* row_b = framebuffer + (height - i - 1) * row_bytes; memcpy(scanline, row_b, row_bytes); memcpy(row_b, row_a, row_bytes); memcpy(row_a, scanline, row_bytes); } } Vulnerability Type: DoS Overflow Mem. Corr. CWE ID: CWE-119 Summary: The WebGL implementation in Google Chrome before 17.0.963.83 does not properly handle CANVAS elements, which allows remote attackers to cause a denial of service (memory corruption) or possibly have unspecified other impact via unknown vectors. Commit Message: Fix mismanagement in handling of temporary scanline for vertical flip. BUG=116637 TEST=manual test from bug report with ASAN Review URL: https://chromiumcodereview.appspot.com/9617038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125301 0039d316-1c4b-4281-b951-d872f2087c98
Low
3,594
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: long Chapters::Atom::ParseDisplay( IMkvReader* pReader, long long pos, long long size) { if (!ExpandDisplaysArray()) return -1; Display& d = m_displays[m_displays_count++]; d.Init(); return d.Parse(pReader, pos, size); } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. 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
Low
11,767
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: SchedulerObject::remove(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!abortJob(id.cluster, id.proc, reason.c_str(), true // Always perform within a transaction )) { text = "Failed to remove job"; return false; } return true; } Vulnerability Type: DoS CWE ID: CWE-20 Summary: aviary/jobcontrol.py in Condor, as used in Red Hat Enterprise MRG 2.3, when removing a job, allows remote attackers to cause a denial of service (condor_schedd restart) via square brackets in the cproc option. Commit Message:
Medium
15,979
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int xstateregs_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { struct fpu *fpu = &target->thread.fpu; struct xregs_state *xsave; int ret; if (!boot_cpu_has(X86_FEATURE_XSAVE)) return -ENODEV; /* * A whole standard-format XSAVE buffer is needed: */ if ((pos != 0) || (count < fpu_user_xstate_size)) return -EFAULT; xsave = &fpu->state.xsave; fpu__activate_fpstate_write(fpu); if (boot_cpu_has(X86_FEATURE_XSAVES)) { if (kbuf) ret = copy_kernel_to_xstate(xsave, kbuf); else ret = copy_user_to_xstate(xsave, ubuf); } else { ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, xsave, 0, -1); } /* * In case of failure, mark all states as init: */ if (ret) fpstate_init(&fpu->state); /* * mxcsr reserved bits must be masked to zero for security reasons. */ xsave->i387.mxcsr &= mxcsr_feature_mask; xsave->header.xfeatures &= xfeatures_mask; /* * These bits must be zero. */ memset(&xsave->header.reserved, 0, 48); return ret; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The x86/fpu (Floating Point Unit) subsystem in the Linux kernel before 4.13.5, when a processor supports the xsave feature but not the xsaves feature, does not correctly handle attempts to set reserved bits in the xstate header via the ptrace() or rt_sigreturn() system call, allowing local users to read the FPU registers of other processes on the system, related to arch/x86/kernel/fpu/regset.c and arch/x86/kernel/fpu/signal.c. 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 <dvyukov@google.com> Signed-off-by: Eric Biggers <ebiggers@google.com> Reviewed-by: Kees Cook <keescook@chromium.org> Reviewed-by: Rik van Riel <riel@redhat.com> Acked-by: Dave Hansen <dave.hansen@linux.intel.com> Cc: <stable@vger.kernel.org> [v3.17+] Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Andy Lutomirski <luto@amacapital.net> Cc: Andy Lutomirski <luto@kernel.org> Cc: Borislav Petkov <bp@alien8.de> Cc: Eric Biggers <ebiggers3@gmail.com> Cc: Fenghua Yu <fenghua.yu@intel.com> Cc: Kevin Hao <haokexin@gmail.com> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Michael Halcrow <mhalcrow@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Wanpeng Li <wanpeng.li@hotmail.com> Cc: Yu-cheng Yu <yu-cheng.yu@intel.com> Cc: kernel-hardening@lists.openwall.com Fixes: 0b29643a5843 ("x86/xsaves: Change compacted format xsave area header") Link: http://lkml.kernel.org/r/20170922174156.16780-2-ebiggers3@gmail.com Link: http://lkml.kernel.org/r/20170923130016.21448-25-mingo@kernel.org Signed-off-by: Ingo Molnar <mingo@kernel.org>
Low
17,979
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: bool ContainOnlyOneKeyboardLayout( const ImeConfigValue& value) { return (value.type == ImeConfigValue::kValueTypeStringList && value.string_list_value.size() == 1 && chromeos::input_method::IsKeyboardLayout( value.string_list_value[0])); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Google Chrome before 13.0.782.107 does not properly handle nested functions in PDF documents, which allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via a crafted document. Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
Low
11,866
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: sequential_row(standard_display *dp, png_structp pp, png_infop pi, PNG_CONST int iImage, PNG_CONST int iDisplay) { PNG_CONST int npasses = dp->npasses; PNG_CONST int do_interlace = dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7; PNG_CONST png_uint_32 height = standard_height(pp, dp->id); PNG_CONST png_uint_32 width = standard_width(pp, dp->id); PNG_CONST png_store* ps = dp->ps; int pass; for (pass=0; pass<npasses; ++pass) { png_uint_32 y; png_uint_32 wPass = PNG_PASS_COLS(width, pass); for (y=0; y<height; ++y) { if (do_interlace) { /* wPass may be zero or this row may not be in this pass. * png_read_row must not be called in either case. */ if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass)) { /* Read the row into a pair of temporary buffers, then do the * merge here into the output rows. */ png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX]; /* The following aids (to some extent) error detection - we can * see where png_read_row wrote. Use opposite values in row and * display to make this easier. Don't use 0xff (which is used in * the image write code to fill unused bits) or 0 (which is a * likely value to overwrite unused bits with). */ memset(row, 0xc5, sizeof row); memset(display, 0x5c, sizeof display); png_read_row(pp, row, display); if (iImage >= 0) deinterlace_row(store_image_row(ps, pp, iImage, y), row, dp->pixel_size, dp->w, pass); if (iDisplay >= 0) deinterlace_row(store_image_row(ps, pp, iDisplay, y), display, dp->pixel_size, dp->w, pass); } } else png_read_row(pp, iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL, iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL); } } /* And finish the read operation (only really necessary if the caller wants * to find additional data in png_info from chunks after the last IDAT.) */ png_read_end(pp, pi); } Vulnerability Type: +Priv CWE ID: Summary: Unspecified vulnerability in libpng before 1.6.20, as used in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-07-01, allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 23265085. Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
Low
26,181
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void WallpaperManager::SetDefaultWallpaperPath( const base::FilePath& default_small_wallpaper_file, std::unique_ptr<gfx::ImageSkia> small_wallpaper_image, const base::FilePath& default_large_wallpaper_file, std::unique_ptr<gfx::ImageSkia> large_wallpaper_image) { default_small_wallpaper_file_ = default_small_wallpaper_file; default_large_wallpaper_file_ = default_large_wallpaper_file; ash::WallpaperController* controller = ash::Shell::Get()->wallpaper_controller(); const bool need_update_screen = default_wallpaper_image_.get() && controller->WallpaperIsAlreadyLoaded(default_wallpaper_image_->image(), false /* compare_layouts */, wallpaper::WALLPAPER_LAYOUT_CENTER); default_wallpaper_image_.reset(); if (GetAppropriateResolution() == WALLPAPER_RESOLUTION_SMALL) { if (small_wallpaper_image) { default_wallpaper_image_.reset( new user_manager::UserImage(*small_wallpaper_image)); default_wallpaper_image_->set_file_path(default_small_wallpaper_file); } } else { if (large_wallpaper_image) { default_wallpaper_image_.reset( new user_manager::UserImage(*large_wallpaper_image)); default_wallpaper_image_->set_file_path(default_large_wallpaper_file); } } if (need_update_screen) DoSetDefaultWallpaper(EmptyAccountId(), MovableOnDestroyCallbackHolder()); } Vulnerability Type: XSS +Info CWE ID: CWE-200 Summary: The XSSAuditor::canonicalize function in core/html/parser/XSSAuditor.cpp in the XSS auditor in Blink, as used in Google Chrome before 44.0.2403.89, does not properly choose a truncation point, which makes it easier for remote attackers to obtain sensitive information via an unspecified linear-time attack. Commit Message: [reland] Do not set default wallpaper unless it should do so. TBR=bshe@chromium.org, alemate@chromium.org Bug: 751382 Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda Reviewed-on: https://chromium-review.googlesource.com/619754 Commit-Queue: Xiaoqian Dai <xdai@chromium.org> Reviewed-by: Alexander Alekseev <alemate@chromium.org> Reviewed-by: Biao She <bshe@chromium.org> Cr-Original-Commit-Position: refs/heads/master@{#498325} Reviewed-on: https://chromium-review.googlesource.com/646430 Cr-Commit-Position: refs/heads/master@{#498982}
Low
10,389
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int php_stream_memory_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */ { php_stream_memory_data *ms = (php_stream_memory_data*)stream->abstract; size_t newsize; switch(option) { case PHP_STREAM_OPTION_TRUNCATE_API: switch (value) { case PHP_STREAM_TRUNCATE_SUPPORTED: return PHP_STREAM_OPTION_RETURN_OK; case PHP_STREAM_TRUNCATE_SET_SIZE: if (ms->mode & TEMP_STREAM_READONLY) { return PHP_STREAM_OPTION_RETURN_ERR; } newsize = *(size_t*)ptrparam; if (newsize <= ms->fsize) { if (newsize < ms->fpos) { ms->fpos = newsize; } } else { ms->data = erealloc(ms->data, newsize); memset(ms->data+ms->fsize, 0, newsize - ms->fsize); ms->fsize = newsize; } ms->fsize = newsize; return PHP_STREAM_OPTION_RETURN_OK; } default: return PHP_STREAM_OPTION_RETURN_NOTIMPL; } } /* }}} */ Vulnerability Type: CWE ID: CWE-20 Summary: In PHP before 5.5.32, 5.6.x before 5.6.18, and 7.x before 7.0.3, all of the return values of stream_get_meta_data can be controlled if the input can be controlled (e.g., during file uploads). For example, a "$uri = stream_get_meta_data(fopen($file, "r"))['uri']" call mishandles the case where $file is data:text/plain;uri=eviluri, -- in other words, metadata can be set by an attacker. Commit Message:
Low
5,065
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void ncq_err(NCQTransferState *ncq_tfs) { IDEState *ide_state = &ncq_tfs->drive->port.ifs[0]; ide_state->error = ABRT_ERR; ide_state->status = READY_STAT | ERR_STAT; ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag); } Vulnerability Type: DoS Exec Code CWE ID: Summary: Use-after-free vulnerability in hw/ide/ahci.c in QEMU, when built with IDE AHCI Emulation support, allows guest OS users to cause a denial of service (instance crash) or possibly execute arbitrary code via an invalid AHCI Native Command Queuing (NCQ) AIO command. Commit Message:
Medium
23,964
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static __init int seqgen_init(void) { rekey_seq_generator(NULL); return 0; } Vulnerability Type: DoS CWE ID: Summary: The (1) IPv4 and (2) IPv6 implementations in the Linux kernel before 3.1 use a modified MD4 algorithm to generate sequence numbers and Fragment Identification values, which makes it easier for remote attackers to cause a denial of service (disrupted networking) or hijack network sessions by predicting these values and sending crafted packets. Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <dan@doxpara.com> Tested-by: Willy Tarreau <w@1wt.eu> Signed-off-by: David S. Miller <davem@davemloft.net>
Medium
10,793
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) { struct r_bin_t *rbin = arch->rbin; int i; int *methods = NULL; int sym_count = 0; if (!bin || bin->methods_list) { return false; } bin->code_from = UT64_MAX; bin->code_to = 0; bin->methods_list = r_list_newf ((RListFree)free); if (!bin->methods_list) { return false; } bin->imports_list = r_list_newf ((RListFree)free); if (!bin->imports_list) { r_list_free (bin->methods_list); return false; } bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free); if (!bin->classes_list) { r_list_free (bin->methods_list); r_list_free (bin->imports_list); return false; } if (bin->header.method_size>bin->size) { bin->header.method_size = 0; return false; } /* WrapDown the header sizes to avoid huge allocations */ bin->header.method_size = R_MIN (bin->header.method_size, bin->size); bin->header.class_size = R_MIN (bin->header.class_size, bin->size); bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size); if (bin->header.strings_size > bin->size) { eprintf ("Invalid strings size\n"); return false; } if (bin->classes) { ut64 amount = sizeof (int) * bin->header.method_size; if (amount > UT32_MAX || amount < bin->header.method_size) { return false; } methods = calloc (1, amount + 1); for (i = 0; i < bin->header.class_size; i++) { char *super_name, *class_name; struct dex_class_t *c = &bin->classes[i]; class_name = dex_class_name (bin, c); super_name = dex_class_super_name (bin, c); if (dexdump) { rbin->cb_printf ("Class #%d -\n", i); } parse_class (arch, bin, c, i, methods, &sym_count); free (class_name); free (super_name); } } if (methods) { int import_count = 0; int sym_count = bin->methods_list->length; for (i = 0; i < bin->header.method_size; i++) { int len = 0; if (methods[i]) { continue; } if (bin->methods[i].class_id > bin->header.types_size - 1) { continue; } if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) { continue; } char *class_name = getstr ( bin, bin->types[bin->methods[i].class_id] .descriptor_id); if (!class_name) { free (class_name); continue; } len = strlen (class_name); if (len < 1) { continue; } class_name[len - 1] = 0; // remove last char ";" char *method_name = dex_method_name (bin, i); char *signature = dex_method_signature (bin, i); if (method_name && *method_name) { RBinImport *imp = R_NEW0 (RBinImport); imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature); imp->type = r_str_const ("FUNC"); imp->bind = r_str_const ("NONE"); imp->ordinal = import_count++; r_list_append (bin->imports_list, imp); RBinSymbol *sym = R_NEW0 (RBinSymbol); sym->name = r_str_newf ("imp.%s", imp->name); sym->type = r_str_const ("FUNC"); sym->bind = r_str_const ("NONE"); sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ; sym->ordinal = sym_count++; r_list_append (bin->methods_list, sym); sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0); } free (method_name); free (signature); free (class_name); } free (methods); } return true; } Vulnerability Type: DoS CWE ID: CWE-125 Summary: The dex_loadcode function in libr/bin/p/bin_dex.c in radare2 1.2.1 allows remote attackers to cause a denial of service (out-of-bounds read and application crash) via a crafted DEX file. Commit Message: fix #6857
Medium
216
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: status_t BnGraphicBufferProducer::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case REQUEST_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferIdx = data.readInt32(); sp<GraphicBuffer> buffer; int result = requestBuffer(bufferIdx, &buffer); reply->writeInt32(buffer != 0); if (buffer != 0) { reply->write(*buffer); } reply->writeInt32(result); return NO_ERROR; } case SET_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int bufferCount = data.readInt32(); int result = setBufferCount(bufferCount); reply->writeInt32(result); return NO_ERROR; } case DEQUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool async = static_cast<bool>(data.readInt32()); uint32_t width = data.readUint32(); uint32_t height = data.readUint32(); PixelFormat format = static_cast<PixelFormat>(data.readInt32()); uint32_t usage = data.readUint32(); int buf = 0; sp<Fence> fence; int result = dequeueBuffer(&buf, &fence, async, width, height, format, usage); reply->writeInt32(buf); reply->writeInt32(fence != NULL); if (fence != NULL) { reply->write(*fence); } reply->writeInt32(result); return NO_ERROR; } case DETACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int slot = data.readInt32(); int result = detachBuffer(slot); reply->writeInt32(result); return NO_ERROR; } case DETACH_NEXT_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<GraphicBuffer> buffer; sp<Fence> fence; int32_t result = detachNextBuffer(&buffer, &fence); reply->writeInt32(result); if (result == NO_ERROR) { reply->writeInt32(buffer != NULL); if (buffer != NULL) { reply->write(*buffer); } reply->writeInt32(fence != NULL); if (fence != NULL) { reply->write(*fence); } } return NO_ERROR; } case ATTACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<GraphicBuffer> buffer = new GraphicBuffer(); data.read(*buffer.get()); int slot = 0; int result = attachBuffer(&slot, buffer); reply->writeInt32(slot); reply->writeInt32(result); return NO_ERROR; } case QUEUE_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); QueueBufferInput input(data); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); memset(output, 0, sizeof(QueueBufferOutput)); status_t result = queueBuffer(buf, input, output); reply->writeInt32(result); return NO_ERROR; } case CANCEL_BUFFER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int buf = data.readInt32(); sp<Fence> fence = new Fence(); data.read(*fence.get()); cancelBuffer(buf, fence); return NO_ERROR; } case QUERY: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int value = 0; int what = data.readInt32(); int res = query(what, &value); reply->writeInt32(value); reply->writeInt32(res); return NO_ERROR; } case CONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<IProducerListener> listener; if (data.readInt32() == 1) { listener = IProducerListener::asInterface(data.readStrongBinder()); } int api = data.readInt32(); bool producerControlledByApp = data.readInt32(); QueueBufferOutput* const output = reinterpret_cast<QueueBufferOutput *>( reply->writeInplace(sizeof(QueueBufferOutput))); status_t res = connect(listener, api, producerControlledByApp, output); reply->writeInt32(res); return NO_ERROR; } case DISCONNECT: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); int api = data.readInt32(); status_t res = disconnect(api); reply->writeInt32(res); return NO_ERROR; } case SET_SIDEBAND_STREAM: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); sp<NativeHandle> stream; if (data.readInt32()) { stream = NativeHandle::create(data.readNativeHandle(), true); } status_t result = setSidebandStream(stream); reply->writeInt32(result); return NO_ERROR; } case ALLOCATE_BUFFERS: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool async = static_cast<bool>(data.readInt32()); uint32_t width = data.readUint32(); uint32_t height = data.readUint32(); PixelFormat format = static_cast<PixelFormat>(data.readInt32()); uint32_t usage = data.readUint32(); allocateBuffers(async, width, height, format, usage); return NO_ERROR; } case ALLOW_ALLOCATION: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); bool allow = static_cast<bool>(data.readInt32()); status_t result = allowAllocation(allow); reply->writeInt32(result); return NO_ERROR; } case SET_GENERATION_NUMBER: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); uint32_t generationNumber = data.readUint32(); status_t result = setGenerationNumber(generationNumber); reply->writeInt32(result); return NO_ERROR; } case GET_CONSUMER_NAME: { CHECK_INTERFACE(IGraphicBufferProducer, data, reply); reply->writeString8(getConsumerName()); return NO_ERROR; } } return BBinder::onTransact(code, data, reply, flags); } Vulnerability Type: +Info CWE ID: CWE-200 Summary: mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-05-01 does not initialize certain data structures, which allows attackers to obtain sensitive information via a crafted application, related to IGraphicBufferConsumer.cpp and IGraphicBufferProducer.cpp, aka internal bug 27555981. Commit Message: BQ: fix some uninitialized variables Bug 27555981 Bug 27556038 Change-Id: I436b6fec589677d7e36c0e980f6e59808415dc0e
Medium
4,740
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt) { struct iovec *l2_hdr, *l3_hdr; size_t bytes_read; size_t full_ip6hdr_len; uint16_t l3_proto; assert(pkt); l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG]; l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG]; bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base, ETH_MAX_L2_HDR_LEN); if (bytes_read < ETH_MAX_L2_HDR_LEN) { l2_hdr->iov_len = 0; return false; } else { l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base); } l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len); l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base); pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p; /* copy optional IPv4 header data */ bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len + sizeof(struct ip_header), l3_hdr->iov_base + sizeof(struct ip_header), l3_hdr->iov_len - sizeof(struct ip_header)); if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } break; case ETH_P_IPV6: if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, &pkt->l4proto, &full_ip6hdr_len)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_base = g_malloc(full_ip6hdr_len); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, full_ip6hdr_len); if (bytes_read < full_ip6hdr_len) { l3_hdr->iov_len = 0; return false; } else { l3_hdr->iov_len = full_ip6hdr_len; } break; default: l3_hdr->iov_len = 0; break; } Vulnerability Type: CWE ID: CWE-20 Summary: QEMU (aka Quick Emulator) built with a VMWARE VMXNET3 paravirtual NIC emulator support is vulnerable to crash issue. It occurs when a guest sends a Layer-2 packet smaller than 22 bytes. A privileged (CAP_SYS_RAWIO) guest user could use this flaw to crash the QEMU process instance resulting in DoS. Commit Message:
Low
2,562
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: GLboolean WebGLRenderingContextBase::isBuffer(WebGLBuffer* buffer) { if (!buffer || isContextLost()) return 0; if (!buffer->HasEverBeenBound()) return 0; if (buffer->IsDeleted()) return 0; return ContextGL()->IsBuffer(buffer->Object()); } Vulnerability Type: Overflow CWE ID: CWE-119 Summary: Insufficient data validation in WebGL in Google Chrome prior to 68.0.3440.75 allowed a remote attacker to potentially exploit heap corruption via a crafted HTML page. Commit Message: Validate all incoming WebGLObjects. A few entry points were missing the correct validation. Tested with improved conformance tests in https://github.com/KhronosGroup/WebGL/pull/2654 . Bug: 848914 Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008 Reviewed-on: https://chromium-review.googlesource.com/1086718 Reviewed-by: Kai Ninomiya <kainino@chromium.org> Reviewed-by: Antoine Labour <piman@chromium.org> Commit-Queue: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#565016}
Medium
21,717
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { FD_t payload = rpmtePayload(te); rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int saveerrno = errno; int rc = 0; int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0; int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0; int firsthardlink = -1; int skip; rpmFileAction action; char *tid = NULL; const char *suffix; char *fpath = NULL; if (fi == NULL) { rc = RPMERR_BAD_MAGIC; goto exit; } /* transaction id used for temporary path suffix while installing */ rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts)); /* Detect and create directories not explicitly in package. */ rc = fsmMkdirs(files, fs, plugins); while (!rc) { /* Read next payload header. */ rc = rpmfiNext(fi); if (rc < 0) { if (rc == RPMERR_ITER_END) rc = 0; break; } action = rpmfsGetAction(fs, rpmfiFX(fi)); skip = XFA_SKIPPING(action); suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid; if (action != FA_TOUCH) { fpath = fsmFsPath(fi, suffix); } else { fpath = fsmFsPath(fi, ""); } /* Remap file perms, owner, and group. */ rc = rpmfiStat(fi, 1, &sb); fsmDebug(fpath, action, &sb); /* Exit on error. */ if (rc) break; /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (rc) { skip = 1; } else { setFileState(fs, rpmfiFX(fi)); } if (!skip) { int setmeta = 1; /* Directories replacing something need early backup */ if (!suffix) { rc = fsmBackup(fi, action); } /* Assume file does't exist when tmp suffix is in use */ if (!suffix) { rc = fsmVerify(fpath, fi); } else { rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT; } if (S_ISREG(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMkfile(fi, fpath, files, psm, nodigest, &setmeta, &firsthardlink); } } else if (S_ISDIR(sb.st_mode)) { if (rc == RPMERR_ENOENT) { mode_t mode = sb.st_mode; mode &= ~07777; mode |= 00700; rc = fsmMkdir(fpath, mode); } } else if (S_ISLNK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmSymlink(rpmfiFLink(fi), fpath); } } else if (S_ISFIFO(sb.st_mode)) { /* This mimics cpio S_ISSOCK() behavior but probably isn't right */ if (rc == RPMERR_ENOENT) { rc = fsmMkfifo(fpath, 0000); } } else if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode) || S_ISSOCK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev); } } else { /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!IS_DEV_LOG(fpath)) rc = RPMERR_UNKNOWN_FILETYPE; } /* Set permissions, timestamps etc for non-hardlink entries */ if (!rc && setmeta) { rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps); } } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) { /* we skip the hard linked file containing the content */ /* write the content to the first used instead */ char *fn = rpmfilesFN(files, firsthardlink); rc = expandRegular(fi, fn, psm, 0, nodigest, 0); firsthardlink = -1; free(fn); } if (rc) { if (!skip) { /* XXX only erase if temp fn w suffix is in use */ if (suffix && (action != FA_TOUCH)) { (void) fsmRemove(fpath, sb.st_mode); } errno = saveerrno; } } else { /* Notify on success. */ rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi)); if (!skip) { /* Backup file if needed. Directories are handled earlier */ if (suffix) rc = fsmBackup(fi, action); if (!rc) rc = fsmCommit(&fpath, fi, action, suffix); } } if (rc) *failedFile = xstrdup(fpath); /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); fpath = _free(fpath); } rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ)); rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST)); exit: /* No need to bother with close errors on read */ rpmfiArchiveClose(fi); rpmfiFree(fi); Fclose(payload); free(tid); free(fpath); return rc; } Vulnerability Type: +Priv CWE ID: CWE-59 Summary: It was found that rpm did not properly handle RPM installations when a destination path was a symbolic link to a directory, possibly changing ownership and permissions of an arbitrary directory, and RPM files being placed in an arbitrary destination. An attacker, with write access to a directory in which a subdirectory will be installed, could redirect that directory to an arbitrary location and gain root privilege. Commit Message: Restrict following symlinks to directories by ownership (CVE-2017-7500) Only follow directory symlinks owned by target directory owner or root. This prevents privilege escalation from user-writable directories via directory symlinks to privileged directories on package upgrade, while still allowing admin to arrange disk usage with symlinks. The rationale is that if you can create symlinks owned by user X you *are* user X (or root), and if you also own directory Y you can do whatever with it already, including change permissions. So when you create a symlink to that directory, the link ownership acts as a simple stamp of authority that you indeed want rpm to treat this symlink as it were the directory that you own. Such a permission can only be given by you or root, which is just the way we want it. Plus it's almost ridiculously simple as far as rules go, compared to trying to calculate something from the source vs destination directory permissions etc. In the normal case, the user arranging diskspace with symlinks is indeed root so nothing changes, the only real change here is to links created by non-privileged users which should be few and far between in practise. Unfortunately our test-suite runs as a regular user via fakechroot and thus the testcase for this fails under the new rules. Adjust the testcase to get the ownership straight and add a second case for the illegal behavior, basically the same as the old one but with different expectations.
Low
16,271
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: std::string MakeMediaAccessRequest(int index) { const int render_process_id = 1; const int render_frame_id = 1; const int page_request_id = 1; const url::Origin security_origin; MediaStreamManager::MediaAccessRequestCallback callback = base::BindOnce(&MediaStreamManagerTest::ResponseCallback, base::Unretained(this), index); StreamControls controls(true, true); return media_stream_manager_->MakeMediaAccessRequest( render_process_id, render_frame_id, page_request_id, controls, security_origin, std::move(callback)); } Vulnerability Type: CWE ID: CWE-189 Summary: Incorrect handling of negative zero in V8 in Google Chrome prior to 72.0.3626.81 allowed a remote attacker to perform arbitrary read/write via a crafted HTML page. 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 <emircan@chromium.org> Reviewed-by: Ken Buchanan <kenrb@chromium.org> Reviewed-by: Olga Sharonova <olka@chromium.org> Commit-Queue: Guido Urdaneta <guidou@chromium.org> Cr-Commit-Position: refs/heads/master@{#616347}
Medium
380
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: bool InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const { return x >= frameLeft && x <= frameRight && y >= frameTop && y <= frameBottom; } Vulnerability Type: CWE ID: CWE-264 Summary: The Framework UI permission-dialog implementation in Android 6.x before 2016-06-01 allows attackers to conduct tapjacking attacks and access arbitrary private-storage files by creating a partially overlapping window, aka internal bug 26677796. Commit Message: Add new MotionEvent flag for partially obscured windows. Due to more complex window layouts resulting in lots of overlapping windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to only be set when the point at which the window was touched is obscured. Unfortunately, this doesn't prevent tapjacking attacks that overlay the dialog's text, making a potentially dangerous operation seem innocuous. To avoid this on particularly sensitive dialogs, introduce a new flag that really does tell you when your window is being even partially overlapped. We aren't exposing this as API since we plan on making the original flag more robust. This is really a workaround for system dialogs since we generally know their layout and screen position, and that they're unlikely to be overlapped by other applications. Bug: 26677796 Change-Id: I9e336afe90f262ba22015876769a9c510048fd47
Low
9,842
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: WebRunnerContentBrowserClient::CreateBrowserMainParts( const content::MainFunctionParams& parameters) { DCHECK(context_channel_); return new WebRunnerBrowserMainParts(std::move(context_channel_)); } Vulnerability Type: Bypass CWE ID: CWE-264 Summary: The PendingScript::notifyFinished function in WebKit/Source/core/dom/PendingScript.cpp in Google Chrome before 49.0.2623.75 relies on memory-cache information about integrity-check occurrences instead of integrity-check successes, which allows remote attackers to bypass the Subresource Integrity (aka SRI) protection mechanism by triggering two loads of the same resource. 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 <kmarshall@chromium.org> Reviewed-by: Wez <wez@chromium.org> Reviewed-by: Fabrice de Gans-Riberi <fdegans@chromium.org> Reviewed-by: Scott Violet <sky@chromium.org> Cr-Commit-Position: refs/heads/master@{#584155}
Low
15,434
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void DownloadManagerImpl::DownloadUrl( std::unique_ptr<download::DownloadUrlParameters> params, std::unique_ptr<storage::BlobDataHandle> blob_data_handle, scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) { if (params->post_id() >= 0) { DCHECK(params->prefer_cache()); DCHECK_EQ("POST", params->method()); } download::RecordDownloadCountWithSource( download::DownloadCountTypes::DOWNLOAD_TRIGGERED_COUNT, params->download_source()); auto* rfh = RenderFrameHost::FromID(params->render_process_host_id(), params->render_frame_host_routing_id()); BeginDownloadInternal(std::move(params), std::move(blob_data_handle), std::move(blob_url_loader_factory), true, rfh ? rfh->GetSiteInstance()->GetSiteURL() : GURL()); } Vulnerability Type: Bypass CWE ID: CWE-284 Summary: Inappropriate implementation in Blink in Google Chrome prior to 74.0.3729.108 allowed a remote attacker to bypass same origin policy via a crafted HTML page. Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <japhet@chromium.org> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <clamy@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#629547}
Medium
22,300
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void ChromeMockRenderThread::OnMsgOpenChannelToExtension( int routing_id, const std::string& source_extension_id, const std::string& target_extension_id, const std::string& channel_name, int* port_id) { *port_id = 0; } Vulnerability Type: +Info CWE ID: CWE-200 Summary: The IPC implementation in Google Chrome before 22.0.1229.79 allows attackers to obtain potentially sensitive information about memory addresses via unspecified vectors. 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
Low
23,461
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static void recalculate_apic_map(struct kvm *kvm) { struct kvm_apic_map *new, *old = NULL; struct kvm_vcpu *vcpu; int i; new = kzalloc(sizeof(struct kvm_apic_map), GFP_KERNEL); mutex_lock(&kvm->arch.apic_map_lock); if (!new) goto out; new->ldr_bits = 8; /* flat mode is default */ new->cid_shift = 8; new->cid_mask = 0; new->lid_mask = 0xff; kvm_for_each_vcpu(i, vcpu, kvm) { struct kvm_lapic *apic = vcpu->arch.apic; u16 cid, lid; u32 ldr; if (!kvm_apic_present(vcpu)) continue; /* * All APICs have to be configured in the same mode by an OS. * We take advatage of this while building logical id loockup * table. After reset APICs are in xapic/flat mode, so if we * find apic with different setting we assume this is the mode * OS wants all apics to be in; build lookup table accordingly. */ if (apic_x2apic_mode(apic)) { new->ldr_bits = 32; new->cid_shift = 16; new->cid_mask = new->lid_mask = 0xffff; } else if (kvm_apic_sw_enabled(apic) && !new->cid_mask /* flat mode */ && kvm_apic_get_reg(apic, APIC_DFR) == APIC_DFR_CLUSTER) { new->cid_shift = 4; new->cid_mask = 0xf; new->lid_mask = 0xf; } new->phys_map[kvm_apic_id(apic)] = apic; ldr = kvm_apic_get_reg(apic, APIC_LDR); cid = apic_cluster_id(new, ldr); lid = apic_logical_id(new, ldr); if (lid) new->logical_map[cid][ffs(lid) - 1] = apic; } out: old = rcu_dereference_protected(kvm->arch.apic_map, lockdep_is_held(&kvm->arch.apic_map_lock)); rcu_assign_pointer(kvm->arch.apic_map, new); mutex_unlock(&kvm->arch.apic_map_lock); if (old) kfree_rcu(old, rcu); kvm_vcpu_request_scan_ioapic(kvm); } Vulnerability Type: DoS CWE ID: CWE-189 Summary: The recalculate_apic_map function in arch/x86/kvm/lapic.c in the KVM subsystem in the Linux kernel through 3.12.5 allows guest OS users to cause a denial of service (host OS crash) via a crafted ICR write operation in x2apic mode. Commit Message: KVM: x86: fix guest-initiated crash with x2apic (CVE-2013-6376) A guest can cause a BUG_ON() leading to a host kernel crash. When the guest writes to the ICR to request an IPI, while in x2apic mode the following things happen, the destination is read from ICR2, which is a register that the guest can control. kvm_irq_delivery_to_apic_fast uses the high 16 bits of ICR2 as the cluster id. A BUG_ON is triggered, which is a protection against accessing map->logical_map with an out-of-bounds access and manages to avoid that anything really unsafe occurs. The logic in the code is correct from real HW point of view. The problem is that KVM supports only one cluster with ID 0 in clustered mode, but the code that has the bug does not take this into account. Reported-by: Lars Bull <larsbull@google.com> Cc: stable@vger.kernel.org Signed-off-by: Gleb Natapov <gleb@redhat.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Medium
26,879
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
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 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32438598"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_LEVEL band %d", param2); } break; } *(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, param2); break; case EQ_PARAM_CENTER_FREQ: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32436341"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_CENTER_FREQ band %d", param2); } break; } *(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, param2); break; case EQ_PARAM_BAND_FREQ_RANGE: param2 = *pParamTemp; if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { status = -EINVAL; if (param2 < 0) { android_errorWriteLog(0x534e4554, "32247948"); ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_FREQ_RANGE band %d", param2); } 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 Vulnerability Type: +Info CWE ID: CWE-200 Summary: An information disclosure vulnerability in lvm/wrapper/Bundle/EffectBundle.cpp in libeffects in the Qualcomm audio post processor could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access sensitive data without permission. Product: Android. Versions: 5.0.2, 5.1.1, 6.0, 6.0.1, 7.0, 7.1. Android ID: A-32588016. Commit Message: Fix security vulnerability: Effect command might allow negative indexes Bug: 32448258 Bug: 32095626 Test: Use POC bug or cts security test Change-Id: I69f24eac5866f8d9090fc4c0ebe58c2c297b63df (cherry picked from commit 01183402d757f0c28bfd5e3b127b3809dfd67459)
Medium
3,819
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
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; } Vulnerability Type: DoS Overflow CWE ID: CWE-190 Summary: OpenSSL through 1.0.2h incorrectly uses pointer arithmetic for heap-buffer boundary checks, which might allow remote attackers to cause a denial of service (integer overflow and application crash) or possibly have unspecified other impact by leveraging unexpected malloc behavior, related to s3_srvr.c, ssl_sess.c, and t1_lib.c. Commit Message:
Low
27,910
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: BufferMeta(const sp<IMemory> &mem, bool is_backup = false) : mMem(mem), mIsBackup(is_backup) { } Vulnerability Type: Overflow +Priv CWE ID: CWE-119 Summary: omx/OMXNodeInstance.cpp in libstagefright in mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-08-01 does not validate the buffer port, which allows attackers to gain privileges via a crafted application, aka internal bug 28816827. Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5
Low
24,935
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: bool CreateIpcChannel( const std::string& channel_name, const std::string& pipe_security_descriptor, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, IPC::Listener* delegate, scoped_ptr<IPC::ChannelProxy>* channel_out) { SECURITY_ATTRIBUTES security_attributes; security_attributes.nLength = sizeof(security_attributes); security_attributes.bInheritHandle = FALSE; ULONG security_descriptor_length = 0; if (!ConvertStringSecurityDescriptorToSecurityDescriptor( UTF8ToUTF16(pipe_security_descriptor).c_str(), SDDL_REVISION_1, reinterpret_cast<PSECURITY_DESCRIPTOR*>( &security_attributes.lpSecurityDescriptor), &security_descriptor_length)) { LOG_GETLASTERROR(ERROR) << "Failed to create a security descriptor for the Chromoting IPC channel"; return false; } std::string pipe_name(kChromePipeNamePrefix); pipe_name.append(channel_name); base::win::ScopedHandle pipe; pipe.Set(CreateNamedPipe( UTF8ToUTF16(pipe_name).c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, IPC::Channel::kReadBufferSize, IPC::Channel::kReadBufferSize, 5000, &security_attributes)); if (!pipe.IsValid()) { LOG_GETLASTERROR(ERROR) << "Failed to create the server end of the Chromoting IPC channel"; LocalFree(security_attributes.lpSecurityDescriptor); return false; } LocalFree(security_attributes.lpSecurityDescriptor); channel_out->reset(new IPC::ChannelProxy( IPC::ChannelHandle(pipe), IPC::Channel::MODE_SERVER, delegate, io_task_runner)); return true; } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Use-after-free vulnerability in Google Chrome before 24.0.1312.52 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors involving PDF fields. 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
Medium
10,446
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: long Tracks::Parse() { assert(m_trackEntries == NULL); assert(m_trackEntriesEnd == NULL); const long long stop = m_start + m_size; IMkvReader* const pReader = m_pSegment->m_pReader; int count = 0; long long pos = m_start; while (pos < stop) { long long id, size; const long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) //error return status; if (size == 0) //weird continue; if (id == 0x2E) //TrackEntry ID ++count; pos += size; //consume payload assert(pos <= stop); } assert(pos == stop); if (count <= 0) return 0; //success m_trackEntries = new (std::nothrow) Track*[count]; if (m_trackEntries == NULL) return -1; m_trackEntriesEnd = m_trackEntries; pos = m_start; while (pos < stop) { const long long element_start = pos; long long id, payload_size; const long status = ParseElementHeader( pReader, pos, stop, id, payload_size); if (status < 0) //error return status; if (payload_size == 0) //weird continue; const long long payload_stop = pos + payload_size; assert(payload_stop <= stop); //checked in ParseElement const long long element_size = payload_stop - element_start; if (id == 0x2E) //TrackEntry ID { Track*& pTrack = *m_trackEntriesEnd; pTrack = NULL; const long status = ParseTrackEntry( pos, payload_size, element_start, element_size, pTrack); if (status) return status; if (pTrack) ++m_trackEntriesEnd; } pos = payload_stop; assert(pos <= stop); } assert(pos == stop); return 0; //success } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. 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
Low
20,553
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: TestWCDelegateForDialogsAndFullscreen() : is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {} Vulnerability Type: CWE ID: Summary: A JavaScript focused window could overlap the fullscreen notification in Fullscreen in Google Chrome prior to 66.0.3359.117 allowed a remote attacker to obscure the full screen warning via a crafted HTML page. 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 <nasko@chromium.org> Reviewed-by: Philip Jägenstedt <foolip@chromium.org> Commit-Queue: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#533790}
???
7,484
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void BrowserEventRouter::DispatchTabUpdatedEvent( WebContents* contents, DictionaryValue* changed_properties) { DCHECK(changed_properties); DCHECK(contents); scoped_ptr<ListValue> args_base(new ListValue()); args_base->AppendInteger(ExtensionTabUtil::GetTabId(contents)); args_base->Append(changed_properties); Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext()); scoped_ptr<Event> event(new Event(events::kOnTabUpdated, args_base.Pass())); event->restrict_to_profile = profile; event->user_gesture = EventRouter::USER_GESTURE_NOT_ENABLED; event->will_dispatch_callback = base::Bind(&WillDispatchTabUpdatedEvent, contents); ExtensionSystem::Get(profile)->event_router()->BroadcastEvent(event.Pass()); } Vulnerability Type: CWE ID: CWE-264 Summary: Google Chrome before 26.0.1410.43 does not ensure that an extension has the tabs (aka APIPermission::kTab) permission before providing a URL to this extension, which has unspecified impact and remote attack vectors. 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
Low
17,279
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void ChromeDownloadManagerDelegate::CheckIfSuggestedPathExists( int32 download_id, const FilePath& unverified_path, bool should_prompt, bool is_forced_path, content::DownloadDangerType danger_type, const FilePath& default_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath target_path(unverified_path); file_util::CreateDirectory(default_path); FilePath dir = target_path.DirName(); FilePath filename = target_path.BaseName(); if (!file_util::PathIsWritable(dir)) { VLOG(1) << "Unable to write to directory \"" << dir.value() << "\""; should_prompt = true; PathService::Get(chrome::DIR_USER_DOCUMENTS, &dir); target_path = dir.Append(filename); } bool should_uniquify = (!is_forced_path && (danger_type == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS || should_prompt)); bool should_overwrite = (should_uniquify || is_forced_path); bool should_create_marker = (should_uniquify && !should_prompt); if (should_uniquify) { int uniquifier = download_util::GetUniquePathNumberWithCrDownload(target_path); if (uniquifier > 0) { target_path = target_path.InsertBeforeExtensionASCII( StringPrintf(" (%d)", uniquifier)); } else if (uniquifier == -1) { VLOG(1) << "Unable to find a unique path for suggested path \"" << target_path.value() << "\""; should_prompt = true; } } if (should_create_marker) file_util::WriteFile(download_util::GetCrDownloadPath(target_path), "", 0); DownloadItem::TargetDisposition disposition; if (should_prompt) disposition = DownloadItem::TARGET_DISPOSITION_PROMPT; else if (should_overwrite) disposition = DownloadItem::TARGET_DISPOSITION_OVERWRITE; else disposition = DownloadItem::TARGET_DISPOSITION_UNIQUIFY; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ChromeDownloadManagerDelegate::OnPathExistenceAvailable, this, download_id, target_path, disposition, danger_type)); } Vulnerability Type: DoS Overflow CWE ID: CWE-119 Summary: The PDF functionality in Google Chrome before 22.0.1229.79 allows remote attackers to cause a denial of service or possibly have unspecified other impact via vectors that trigger out-of-bounds write operations. Commit Message: Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 R=asanka@chromium.org Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
Medium
17,907
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod2(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); size_t argsCount = exec->argumentCount(); if (argsCount <= 1) { impl->overloadedMethod(objArg); return JSValue::encode(jsUndefined()); } int intArg(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(objArg, intArg); return JSValue::encode(jsUndefined()); } Vulnerability Type: DoS CWE ID: CWE-20 Summary: The HTML parser in Google Chrome before 12.0.742.112 does not properly address *lifetime and re-entrancy issues,* which allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors. Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
Low
5,277
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void GM2TabStyle::PaintTabBackground(gfx::Canvas* canvas, bool active, int fill_id, int y_inset, const SkPath* clip) const { DCHECK(!y_inset || fill_id); const SkColor active_color = tab_->controller()->GetTabBackgroundColor(TAB_ACTIVE); const SkColor inactive_color = tab_->GetThemeProvider()->GetDisplayProperty( ThemeProperties::SHOULD_FILL_BACKGROUND_TAB_COLOR) ? tab_->controller()->GetTabBackgroundColor(TAB_INACTIVE) : SK_ColorTRANSPARENT; const SkColor stroke_color = tab_->controller()->GetToolbarTopSeparatorColor(); const bool paint_hover_effect = !active && IsHoverActive(); const float stroke_thickness = GetStrokeThickness(active); PaintTabBackgroundFill(canvas, active, paint_hover_effect, active_color, inactive_color, fill_id, y_inset); if (stroke_thickness > 0) { gfx::ScopedCanvas scoped_canvas(clip ? canvas : nullptr); if (clip) canvas->sk_canvas()->clipPath(*clip, SkClipOp::kDifference, true); PaintBackgroundStroke(canvas, active, stroke_color); } PaintSeparators(canvas); } Vulnerability Type: CWE ID: CWE-20 Summary: The extensions API in Google Chrome prior to 55.0.2883.75 for Mac, Windows and Linux, and 55.0.2883.84 for Android incorrectly handled navigation within PDFs, which allowed a remote attacker to temporarily spoof the contents of the Omnibox (URL bar) via a crafted HTML page containing PDF data. Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <bsep@chromium.org> Reviewed-by: Taylor Bergquist <tbergquist@chromium.org> Cr-Commit-Position: refs/heads/master@{#660498}
Medium
9,185
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: static int __do_page_fault(struct mm_struct *mm, unsigned long addr, unsigned int mm_flags, unsigned long vm_flags, struct task_struct *tsk) { struct vm_area_struct *vma; int fault; vma = find_vma(mm, addr); fault = VM_FAULT_BADMAP; if (unlikely(!vma)) goto out; if (unlikely(vma->vm_start > addr)) goto check_stack; /* * Ok, we have a good vm_area for this memory access, so we can handle * it. */ good_area: /* * Check that the permissions on the VMA allow for the fault which * occurred. */ if (!(vma->vm_flags & vm_flags)) { fault = VM_FAULT_BADACCESS; goto out; } return handle_mm_fault(mm, vma, addr & PAGE_MASK, mm_flags); check_stack: if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr)) goto good_area; out: return fault; } Vulnerability Type: +Priv CWE ID: CWE-19 Summary: arch/arm64/include/asm/pgtable.h in the Linux kernel before 3.15-rc5-next-20140519, as used in Android before 2016-07-05 on Nexus 5X and 6P devices, mishandles execute-only pages, which allows attackers to gain privileges via a crafted application, aka Android internal bug 28557020. Commit Message: Revert "arm64: Introduce execute-only page access permissions" This reverts commit bc07c2c6e9ed125d362af0214b6313dca180cb08. While the aim is increased security for --x memory maps, it does not protect against kernel level reads. Until SECCOMP is implemented for arm64, revert this patch to avoid giving a false idea of execute-only mappings. Signed-off-by: Catalin Marinas <catalin.marinas@arm.com>
Medium
19,546
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: status_t BnOMX::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case LIVES_LOCALLY: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); pid_t pid = (pid_t)data.readInt32(); reply->writeInt32(livesLocally(node, pid)); return OK; } case LIST_NODES: { CHECK_OMX_INTERFACE(IOMX, data, reply); List<ComponentInfo> list; listNodes(&list); reply->writeInt32(list.size()); for (List<ComponentInfo>::iterator it = list.begin(); it != list.end(); ++it) { ComponentInfo &cur = *it; reply->writeString8(cur.mName); reply->writeInt32(cur.mRoles.size()); for (List<String8>::iterator role_it = cur.mRoles.begin(); role_it != cur.mRoles.end(); ++role_it) { reply->writeString8(*role_it); } } return NO_ERROR; } case ALLOCATE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); const char *name = data.readCString(); sp<IOMXObserver> observer = interface_cast<IOMXObserver>(data.readStrongBinder()); node_id node; status_t err = allocateNode(name, observer, &node); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)node); } return NO_ERROR; } case FREE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); reply->writeInt32(freeNode(node)); return NO_ERROR; } case SEND_COMMAND: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_COMMANDTYPE cmd = static_cast<OMX_COMMANDTYPE>(data.readInt32()); OMX_S32 param = data.readInt32(); reply->writeInt32(sendCommand(node, cmd, param)); return NO_ERROR; } case GET_PARAMETER: case SET_PARAMETER: case GET_CONFIG: case SET_CONFIG: case SET_INTERNAL_OPTION: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32()); size_t size = data.readInt64(); status_t err = NO_MEMORY; void *params = calloc(size, 1); if (params) { err = data.read(params, size); if (err != OK) { android_errorWriteLog(0x534e4554, "26914474"); } else { switch (code) { case GET_PARAMETER: err = getParameter(node, index, params, size); break; case SET_PARAMETER: err = setParameter(node, index, params, size); break; case GET_CONFIG: err = getConfig(node, index, params, size); break; case SET_CONFIG: err = setConfig(node, index, params, size); break; case SET_INTERNAL_OPTION: { InternalOptionType type = (InternalOptionType)data.readInt32(); err = setInternalOption(node, index, type, params, size); break; } default: TRESPASS(); } } } reply->writeInt32(err); if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { reply->write(params, size); } free(params); params = NULL; return NO_ERROR; } case GET_STATE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_STATETYPE state = OMX_StateInvalid; status_t err = getState(node, &state); reply->writeInt32(state); reply->writeInt32(err); return NO_ERROR; } case ENABLE_GRAPHIC_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = enableGraphicBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case GET_GRAPHIC_BUFFER_USAGE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_U32 usage = 0; status_t err = getGraphicBufferUsage(node, port_index, &usage); reply->writeInt32(err); reply->writeInt32(usage); return NO_ERROR; } case USE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = useBuffer(node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case USE_GRAPHIC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer; status_t err = useGraphicBuffer( node, port_index, graphicBuffer, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case UPDATE_GRAPHIC_BUFFER_IN_META: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer = (buffer_id)data.readInt32(); status_t err = updateGraphicBufferInMeta( node, port_index, graphicBuffer, buffer); reply->writeInt32(err); return NO_ERROR; } case CREATE_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IGraphicBufferProducer> bufferProducer; MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = createInputSurface(node, port_index, &bufferProducer, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, "26324358"); } reply->writeInt32(type); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); } return NO_ERROR; } case CREATE_PERSISTENT_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); sp<IGraphicBufferProducer> bufferProducer; sp<IGraphicBufferConsumer> bufferConsumer; status_t err = createPersistentInputSurface( &bufferProducer, &bufferConsumer); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); reply->writeStrongBinder(IInterface::asBinder(bufferConsumer)); } return NO_ERROR; } case SET_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IGraphicBufferConsumer> bufferConsumer = interface_cast<IGraphicBufferConsumer>(data.readStrongBinder()); MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = setInputSurface(node, port_index, bufferConsumer, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, "26324358"); } reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case SIGNAL_END_OF_INPUT_STREAM: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); status_t err = signalEndOfInputStream(node); reply->writeInt32(err); return NO_ERROR; } case STORE_META_DATA_IN_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = storeMetaDataInBuffers(node, port_index, enable, &type); reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case PREPARE_FOR_ADAPTIVE_PLAYBACK: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); OMX_U32 max_width = data.readInt32(); OMX_U32 max_height = data.readInt32(); status_t err = prepareForAdaptivePlayback( node, port_index, enable, max_width, max_height); reply->writeInt32(err); return NO_ERROR; } case CONFIGURE_VIDEO_TUNNEL_MODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); OMX_U32 audio_hw_sync = data.readInt32(); native_handle_t *sideband_handle = NULL; status_t err = configureVideoTunnelMode( node, port_index, tunneled, audio_hw_sync, &sideband_handle); reply->writeInt32(err); if(err == OK){ reply->writeNativeHandle(sideband_handle); } return NO_ERROR; } case ALLOC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) { ALOGE("b/24310423"); reply->writeInt32(INVALID_OPERATION); return NO_ERROR; } size_t size = data.readInt64(); buffer_id buffer; void *buffer_data; status_t err = allocateBuffer( node, port_index, size, &buffer, &buffer_data); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); reply->writeInt64((uintptr_t)buffer_data); } return NO_ERROR; } case ALLOC_BUFFER_WITH_BACKUP: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp<IMemory> params = interface_cast<IMemory>(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = allocateBufferWithBackup( node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case FREE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); reply->writeInt32(freeBuffer(node, port_index, buffer)); return NO_ERROR; } case FILL_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(fillBuffer(node, buffer, fenceFd)); return NO_ERROR; } case EMPTY_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); OMX_U32 range_offset = data.readInt32(); OMX_U32 range_length = data.readInt32(); OMX_U32 flags = data.readInt32(); OMX_TICKS timestamp = data.readInt64(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(emptyBuffer( node, buffer, range_offset, range_length, flags, timestamp, fenceFd)); return NO_ERROR; } case GET_EXTENSION_INDEX: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); const char *parameter_name = data.readCString(); OMX_INDEXTYPE index; status_t err = getExtensionIndex(node, parameter_name, &index); reply->writeInt32(err); if (err == OK) { reply->writeInt32(index); } return OK; } default: return BBinder::onTransact(code, data, reply, flags); } } Vulnerability Type: Overflow +Priv CWE ID: CWE-119 Summary: mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, and 6.x before 2016-06-01 does not validate OMX buffer sizes, which allows attackers to gain privileges via a crafted application, as demonstrated by obtaining Signature or SignatureOrSystem access, aka internal bug 27207275. Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
Medium
25,585
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void AutoFillMetrics::Log(QualityMetric metric) const { DCHECK(metric < NUM_QUALITY_METRICS); UMA_HISTOGRAM_ENUMERATION("AutoFill.Quality", metric, NUM_QUALITY_METRICS); } Vulnerability Type: DoS CWE ID: CWE-399 Summary: Use-after-free vulnerability in the frame-loader implementation in Google Chrome before 10.0.648.204 allows remote attackers to cause a denial of service or possibly have unspecified other impact via unknown vectors. Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98
Low
9,493
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: DictionaryValue* ExtensionTabUtil::CreateTabValue( const WebContents* contents, TabStripModel* tab_strip, int tab_index, IncludePrivacySensitiveFields include_privacy_sensitive_fields) { NOTIMPLEMENTED(); return NULL; } Vulnerability Type: CWE ID: CWE-264 Summary: Google Chrome before 26.0.1410.43 does not ensure that an extension has the tabs (aka APIPermission::kTab) permission before providing a URL to this extension, which has unspecified impact and remote attack vectors. 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
Low
16,524
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: status_t OMXNodeInstance::getConfig( OMX_INDEXTYPE index, void *params, size_t /* size */) { Mutex::Autolock autoLock(mLock); OMX_ERRORTYPE err = OMX_GetConfig(mHandle, index, params); OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index; if (err != OMX_ErrorNoMore) { CLOG_IF_ERROR(getConfig, err, "%s(%#x)", asString(extIndex), index); } return StatusFromOMXError(err); } Vulnerability Type: +Info CWE ID: CWE-200 Summary: An information disclosure vulnerability in libstagefright in Mediaserver in Android 4.x before 4.4.4, 5.0.x before 5.0.2, 5.1.x before 5.1.1, 6.x before 2016-11-01, and 7.0 before 2016-11-01 could enable a local malicious application to access data outside of its permission levels. This issue is rated as Moderate because it could be used to access sensitive data without permission. Android ID: A-29422020. Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
Medium
29,124
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void AppCacheHost::SelectCache(const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending() && !was_select_cache_called_); was_select_cache_called_ = true; if (!is_cache_selection_enabled_) { FinishCacheSelection(NULL, NULL); return; } origin_in_use_ = document_url.GetOrigin(); if (service()->quota_manager_proxy() && !origin_in_use_.is_empty()) service()->quota_manager_proxy()->NotifyOriginInUse(origin_in_use_); if (main_resource_blocked_) frontend_->OnContentBlocked(host_id_, blocked_manifest_url_); if (cache_document_was_loaded_from != kAppCacheNoCacheId) { LoadSelectedCache(cache_document_was_loaded_from); return; } if (!manifest_url.is_empty() && (manifest_url.GetOrigin() == document_url.GetOrigin())) { DCHECK(!first_party_url_.is_empty()); AppCachePolicy* policy = service()->appcache_policy(); if (policy && !policy->CanCreateAppCache(manifest_url, first_party_url_)) { FinishCacheSelection(NULL, NULL); std::vector<int> host_ids(1, host_id_); frontend_->OnEventRaised(host_ids, APPCACHE_CHECKING_EVENT); frontend_->OnErrorEventRaised( host_ids, AppCacheErrorDetails( "Cache creation was blocked by the content policy", APPCACHE_POLICY_ERROR, GURL(), 0, false /*is_cross_origin*/)); frontend_->OnContentBlocked(host_id_, manifest_url); return; } set_preferred_manifest_url(manifest_url); new_master_entry_url_ = document_url; LoadOrCreateGroup(manifest_url); return; } FinishCacheSelection(NULL, NULL); } Vulnerability Type: DoS CWE ID: Summary: Use-after-free vulnerability in the AppCache implementation in Google Chrome before 47.0.2526.73 allows remote attackers with renderer access to cause a denial of service or possibly have unspecified other impact by leveraging incorrect AppCacheUpdateJob behavior associated with duplicate cache selection. Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815}
Low
23,980
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); set_cpu_used_ = GET_PARAM(2); } Vulnerability Type: DoS Exec Code Overflow Mem. Corr. CWE ID: CWE-119 Summary: libvpx in mediaserver in Android 4.x before 4.4.4, 5.x before 5.1.1 LMY49H, and 6.0 before 2016-03-01 allows remote attackers to execute arbitrary code or cause a denial of service (memory corruption) via a crafted media file, related to libwebm/mkvparser.cpp and other files, aka internal bug 23452792. 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
Low
13,305
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: int main(int argc, char *argv[]) { int free_query_string = 0; int exit_status = SUCCESS; int cgi = 0, c, i, len; zend_file_handle file_handle; char *s; /* temporary locals */ int behavior = PHP_MODE_STANDARD; int no_headers = 0; int orig_optind = php_optind; char *orig_optarg = php_optarg; char *script_file = NULL; int ini_entries_len = 0; /* end of temporary locals */ #ifdef ZTS void ***tsrm_ls; #endif int max_requests = 500; int requests = 0; int fastcgi; char *bindpath = NULL; int fcgi_fd = 0; fcgi_request *request = NULL; int repeats = 1; int benchmark = 0; #if HAVE_GETTIMEOFDAY struct timeval start, end; #else time_t start, end; #endif #ifndef PHP_WIN32 int status = 0; #endif char *query_string; char *decoded_query_string; int skip_getopt = 0; #if 0 && defined(PHP_DEBUG) /* IIS is always making things more difficult. This allows * us to stop PHP and attach a debugger before much gets started */ { char szMessage [256]; wsprintf (szMessage, "Please attach a debugger to the process 0x%X [%d] (%s) and click OK", GetCurrentProcessId(), GetCurrentProcessId(), argv[0]); MessageBox(NULL, szMessage, "CGI Debug Time!", MB_OK|MB_SERVICE_NOTIFICATION); } #endif #ifdef HAVE_SIGNAL_H #if defined(SIGPIPE) && defined(SIG_IGN) signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so that sockets created via fsockopen() don't kill PHP if the remote site closes it. in apache|apxs mode apache does that for us! thies@thieso.net 20000419 */ #endif #endif #ifdef ZTS tsrm_startup(1, 1, 0, NULL); tsrm_ls = ts_resource(0); #endif sapi_startup(&cgi_sapi_module); fastcgi = fcgi_is_fastcgi(); cgi_sapi_module.php_ini_path_override = NULL; #ifdef PHP_WIN32 _fmode = _O_BINARY; /* sets default for file streams to binary */ setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */ #endif if (!fastcgi) { /* Make sure we detect we are a cgi - a bit redundancy here, * but the default case is that we have to check only the first one. */ if (getenv("SERVER_SOFTWARE") || getenv("SERVER_NAME") || getenv("GATEWAY_INTERFACE") || getenv("REQUEST_METHOD") ) { cgi = 1; } } if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) { /* we've got query string that has no = - apache CGI will pass it to command line */ unsigned char *p; decoded_query_string = strdup(query_string); php_url_decode(decoded_query_string, strlen(decoded_query_string)); for (p = decoded_query_string; *p && *p <= ' '; p++) { /* skip all leading spaces */ } if(*p == '-') { skip_getopt = 1; } free(decoded_query_string); } while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) { switch (c) { case 'c': if (cgi_sapi_module.php_ini_path_override) { free(cgi_sapi_module.php_ini_path_override); } cgi_sapi_module.php_ini_path_override = strdup(php_optarg); break; case 'n': cgi_sapi_module.php_ini_ignore = 1; break; case 'd': { /* define ini entries on command line */ int len = strlen(php_optarg); char *val; if ((val = strchr(php_optarg, '='))) { val++; if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') { cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0")); memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg)); ini_entries_len += (val - php_optarg); memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1); ini_entries_len++; memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg)); ini_entries_len += len - (val - php_optarg); memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0")); ini_entries_len += sizeof("\n\0\"") - 2; } else { cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0")); memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len); memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0")); ini_entries_len += len + sizeof("\n\0") - 2; } } else { cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0")); memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len); memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0")); ini_entries_len += len + sizeof("=1\n\0") - 2; } break; } /* if we're started on command line, check to see if * we are being started as an 'external' fastcgi * server by accepting a bindpath parameter. */ case 'b': if (!fastcgi) { bindpath = strdup(php_optarg); } break; case 's': /* generate highlighted HTML from source */ behavior = PHP_MODE_HIGHLIGHT; break; } } php_optind = orig_optind; php_optarg = orig_optarg; if (fastcgi || bindpath) { /* Override SAPI callbacks */ cgi_sapi_module.ub_write = sapi_fcgi_ub_write; cgi_sapi_module.flush = sapi_fcgi_flush; cgi_sapi_module.read_post = sapi_fcgi_read_post; cgi_sapi_module.getenv = sapi_fcgi_getenv; cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies; } #ifdef ZTS SG(request_info).path_translated = NULL; #endif cgi_sapi_module.executable_location = argv[0]; if (!cgi && !fastcgi && !bindpath) { cgi_sapi_module.additional_functions = additional_functions; } /* startup after we get the above ini override se we get things right */ if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) { #ifdef ZTS tsrm_shutdown(); #endif return FAILURE; } /* check force_cgi after startup, so we have proper output */ if (cgi && CGIG(force_redirect)) { /* Apache will generate REDIRECT_STATUS, * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS. * redirect.so and installation instructions available from * http://www.koehntopp.de/php. * -- kk@netuse.de */ if (!getenv("REDIRECT_STATUS") && !getenv ("HTTP_REDIRECT_STATUS") && /* this is to allow a different env var to be configured * in case some server does something different than above */ (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env))) ) { zend_try { SG(sapi_headers).http_response_code = 400; PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\ <p>This PHP CGI binary was compiled with force-cgi-redirect enabled. This\n\ means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\ set, e.g. via an Apache Action directive.</p>\n\ <p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\ manual page for CGI security</a>.</p>\n\ <p>For more information about changing this behaviour or re-enabling this webserver,\n\ consult the installation file that came with this distribution, or visit \n\ <a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n"); } zend_catch { } zend_end_try(); #if defined(ZTS) && !defined(PHP_DEBUG) /* XXX we're crashing here in msvc6 debug builds at * php_message_handler_for_zend:839 because * SG(request_info).path_translated is an invalid pointer. * It still happens even though I set it to null, so something * weird is going on. */ tsrm_shutdown(); #endif return FAILURE; } } if (bindpath) { fcgi_fd = fcgi_listen(bindpath, 128); if (fcgi_fd < 0) { fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath); #ifdef ZTS tsrm_shutdown(); #endif return FAILURE; } fastcgi = fcgi_is_fastcgi(); } if (fastcgi) { /* How many times to run PHP scripts before dying */ if (getenv("PHP_FCGI_MAX_REQUESTS")) { max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS")); if (max_requests < 0) { fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n"); return FAILURE; } } /* make php call us to get _ENV vars */ php_php_import_environment_variables = php_import_environment_variables; php_import_environment_variables = cgi_php_import_environment_variables; /* library is already initialized, now init our request */ request = fcgi_init_request(fcgi_fd); #ifndef PHP_WIN32 /* Pre-fork, if required */ if (getenv("PHP_FCGI_CHILDREN")) { char * children_str = getenv("PHP_FCGI_CHILDREN"); children = atoi(children_str); if (children < 0) { fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n"); return FAILURE; } fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str)); /* This is the number of concurrent requests, equals FCGI_MAX_CONNS */ fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, children_str, strlen(children_str)); } else { fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1); fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, "1", sizeof("1")-1); } if (children) { int running = 0; pid_t pid; /* Create a process group for ourself & children */ setsid(); pgroup = getpgrp(); #ifdef DEBUG_FASTCGI fprintf(stderr, "Process group %d\n", pgroup); #endif /* Set up handler to kill children upon exit */ act.sa_flags = 0; act.sa_handler = fastcgi_cleanup; if (sigaction(SIGTERM, &act, &old_term) || sigaction(SIGINT, &act, &old_int) || sigaction(SIGQUIT, &act, &old_quit) ) { perror("Can't set signals"); exit(1); } if (fcgi_in_shutdown()) { goto parent_out; } while (parent) { do { #ifdef DEBUG_FASTCGI fprintf(stderr, "Forking, %d running\n", running); #endif pid = fork(); switch (pid) { case 0: /* One of the children. * Make sure we don't go round the * fork loop any more */ parent = 0; /* don't catch our signals */ sigaction(SIGTERM, &old_term, 0); sigaction(SIGQUIT, &old_quit, 0); sigaction(SIGINT, &old_int, 0); break; case -1: perror("php (pre-forking)"); exit(1); break; default: /* Fine */ running++; break; } } while (parent && (running < children)); if (parent) { #ifdef DEBUG_FASTCGI fprintf(stderr, "Wait for kids, pid %d\n", getpid()); #endif parent_waiting = 1; while (1) { if (wait(&status) >= 0) { running--; break; } else if (exit_signal) { break; } } if (exit_signal) { #if 0 while (running > 0) { while (wait(&status) < 0) { } running--; } #endif goto parent_out; } } } } else { parent = 0; } #endif /* WIN32 */ } zend_first_try { while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) { switch (c) { case 'T': benchmark = 1; repeats = atoi(php_optarg); #ifdef HAVE_GETTIMEOFDAY gettimeofday(&start, NULL); #else time(&start); #endif break; case 'h': case '?': if (request) { fcgi_destroy_request(request); } fcgi_shutdown(); no_headers = 1; SG(headers_sent) = 1; php_cgi_usage(argv[0]); php_output_end_all(TSRMLS_C); exit_status = 0; goto out; } } php_optind = orig_optind; php_optarg = orig_optarg; /* start of FAST CGI loop */ /* Initialise FastCGI request structure */ #ifdef PHP_WIN32 /* attempt to set security impersonation for fastcgi * will only happen on NT based OS, others will ignore it. */ if (fastcgi && CGIG(impersonate)) { fcgi_impersonate(); } #endif while (!fastcgi || fcgi_accept_request(request) >= 0) { SG(server_context) = fastcgi ? (void *) request : (void *) 1; init_request_info(request TSRMLS_CC); CG(interactive) = 0; if (!cgi && !fastcgi) { while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) { switch (c) { case 'a': /* interactive mode */ printf("Interactive mode enabled\n\n"); CG(interactive) = 1; break; case 'C': /* don't chdir to the script directory */ SG(options) |= SAPI_OPTION_NO_CHDIR; break; case 'e': /* enable extended info output */ CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO; break; case 'f': /* parse file */ if (script_file) { efree(script_file); } script_file = estrdup(php_optarg); no_headers = 1; break; case 'i': /* php info & quit */ if (script_file) { efree(script_file); } if (php_request_startup(TSRMLS_C) == FAILURE) { SG(server_context) = NULL; php_module_shutdown(TSRMLS_C); return FAILURE; } if (no_headers) { SG(headers_sent) = 1; SG(request_info).no_headers = 1; } php_print_info(0xFFFFFFFF TSRMLS_CC); php_request_shutdown((void *) 0); fcgi_shutdown(); exit_status = 0; goto out; case 'l': /* syntax check mode */ no_headers = 1; behavior = PHP_MODE_LINT; break; case 'm': /* list compiled in modules */ if (script_file) { efree(script_file); } SG(headers_sent) = 1; php_printf("[PHP Modules]\n"); print_modules(TSRMLS_C); php_printf("\n[Zend Modules]\n"); print_extensions(TSRMLS_C); php_printf("\n"); php_output_end_all(TSRMLS_C); fcgi_shutdown(); exit_status = 0; goto out; #if 0 /* not yet operational, see also below ... */ case '': /* generate indented source mode*/ behavior=PHP_MODE_INDENT; break; #endif case 'q': /* do not generate HTTP headers */ no_headers = 1; break; case 'v': /* show php version & quit */ if (script_file) { efree(script_file); } no_headers = 1; if (php_request_startup(TSRMLS_C) == FAILURE) { SG(server_context) = NULL; php_module_shutdown(TSRMLS_C); return FAILURE; } if (no_headers) { SG(headers_sent) = 1; SG(request_info).no_headers = 1; } #if ZEND_DEBUG php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version()); #else php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2014 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version()); #endif php_request_shutdown((void *) 0); fcgi_shutdown(); exit_status = 0; goto out; case 'w': behavior = PHP_MODE_STRIP; break; case 'z': /* load extension file */ zend_load_extension(php_optarg); break; default: break; } } if (script_file) { /* override path_translated if -f on command line */ STR_FREE(SG(request_info).path_translated); SG(request_info).path_translated = script_file; /* before registering argv to module exchange the *new* argv[0] */ /* we can achieve this without allocating more memory */ SG(request_info).argc = argc - (php_optind - 1); SG(request_info).argv = &argv[php_optind - 1]; SG(request_info).argv[0] = script_file; } else if (argc > php_optind) { /* file is on command line, but not in -f opt */ STR_FREE(SG(request_info).path_translated); SG(request_info).path_translated = estrdup(argv[php_optind]); /* arguments after the file are considered script args */ SG(request_info).argc = argc - php_optind; SG(request_info).argv = &argv[php_optind]; } if (no_headers) { SG(headers_sent) = 1; SG(request_info).no_headers = 1; } /* all remaining arguments are part of the query string * this section of code concatenates all remaining arguments * into a single string, seperating args with a & * this allows command lines like: * * test.php v1=test v2=hello+world! * test.php "v1=test&v2=hello world!" * test.php v1=test "v2=hello world!" */ if (!SG(request_info).query_string && argc > php_optind) { int slen = strlen(PG(arg_separator).input); len = 0; for (i = php_optind; i < argc; i++) { if (i < (argc - 1)) { len += strlen(argv[i]) + slen; } else { len += strlen(argv[i]); } } len += 2; s = malloc(len); *s = '\0'; /* we are pretending it came from the environment */ for (i = php_optind; i < argc; i++) { strlcat(s, argv[i], len); if (i < (argc - 1)) { strlcat(s, PG(arg_separator).input, len); } } SG(request_info).query_string = s; free_query_string = 1; } } /* end !cgi && !fastcgi */ /* we never take stdin if we're (f)cgi, always rely on the web server giving us the info we need in the environment. */ if (SG(request_info).path_translated || cgi || fastcgi) { file_handle.type = ZEND_HANDLE_FILENAME; file_handle.filename = SG(request_info).path_translated; file_handle.handle.fp = NULL; } else { file_handle.filename = "-"; file_handle.type = ZEND_HANDLE_FP; file_handle.handle.fp = stdin; } file_handle.opened_path = NULL; file_handle.free_filename = 0; /* request startup only after we've done all we can to * get path_translated */ if (php_request_startup(TSRMLS_C) == FAILURE) { if (fastcgi) { fcgi_finish_request(request, 1); } SG(server_context) = NULL; php_module_shutdown(TSRMLS_C); return FAILURE; } if (no_headers) { SG(headers_sent) = 1; SG(request_info).no_headers = 1; } /* at this point path_translated will be set if: 1. we are running from shell and got filename was there 2. we are running as cgi or fastcgi */ if (cgi || fastcgi || SG(request_info).path_translated) { if (php_fopen_primary_script(&file_handle TSRMLS_CC) == FAILURE) { zend_try { if (errno == EACCES) { SG(sapi_headers).http_response_code = 403; PUTS("Access denied.\n"); } else { SG(sapi_headers).http_response_code = 404; PUTS("No input file specified.\n"); } } zend_catch { } zend_end_try(); /* we want to serve more requests if this is fastcgi * so cleanup and continue, request shutdown is * handled later */ if (fastcgi) { goto fastcgi_request_done; } STR_FREE(SG(request_info).path_translated); if (free_query_string && SG(request_info).query_string) { free(SG(request_info).query_string); SG(request_info).query_string = NULL; } php_request_shutdown((void *) 0); SG(server_context) = NULL; php_module_shutdown(TSRMLS_C); sapi_shutdown(); #ifdef ZTS tsrm_shutdown(); #endif return FAILURE; } } if (CGIG(check_shebang_line)) { /* #!php support */ switch (file_handle.type) { case ZEND_HANDLE_FD: if (file_handle.handle.fd < 0) { break; } file_handle.type = ZEND_HANDLE_FP; file_handle.handle.fp = fdopen(file_handle.handle.fd, "rb"); /* break missing intentionally */ case ZEND_HANDLE_FP: if (!file_handle.handle.fp || (file_handle.handle.fp == stdin)) { break; } c = fgetc(file_handle.handle.fp); if (c == '#') { while (c != '\n' && c != '\r' && c != EOF) { c = fgetc(file_handle.handle.fp); /* skip to end of line */ } /* handle situations where line is terminated by \r\n */ if (c == '\r') { if (fgetc(file_handle.handle.fp) != '\n') { long pos = ftell(file_handle.handle.fp); fseek(file_handle.handle.fp, pos - 1, SEEK_SET); } } CG(start_lineno) = 2; } else { rewind(file_handle.handle.fp); } break; case ZEND_HANDLE_STREAM: c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); if (c == '#') { while (c != '\n' && c != '\r' && c != EOF) { c = php_stream_getc((php_stream*)file_handle.handle.stream.handle); /* skip to end of line */ } /* handle situations where line is terminated by \r\n */ if (c == '\r') { if (php_stream_getc((php_stream*)file_handle.handle.stream.handle) != '\n') { long pos = php_stream_tell((php_stream*)file_handle.handle.stream.handle); php_stream_seek((php_stream*)file_handle.handle.stream.handle, pos - 1, SEEK_SET); } } CG(start_lineno) = 2; } else { php_stream_rewind((php_stream*)file_handle.handle.stream.handle); } break; case ZEND_HANDLE_MAPPED: if (file_handle.handle.stream.mmap.buf[0] == '#') { int i = 1; c = file_handle.handle.stream.mmap.buf[i++]; while (c != '\n' && c != '\r' && c != EOF) { c = file_handle.handle.stream.mmap.buf[i++]; } if (c == '\r') { if (file_handle.handle.stream.mmap.buf[i] == '\n') { i++; } } file_handle.handle.stream.mmap.buf += i; file_handle.handle.stream.mmap.len -= i; } } } switch (behavior) { case PHP_MODE_STANDARD: php_execute_script(&file_handle TSRMLS_CC); break; case PHP_MODE_LINT: PG(during_request_startup) = 0; exit_status = php_lint_script(&file_handle TSRMLS_CC); if (exit_status == SUCCESS) { zend_printf("No syntax errors detected in %s\n", file_handle.filename); } else { zend_printf("Errors parsing %s\n", file_handle.filename); } break; case PHP_MODE_STRIP: if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) { zend_strip(TSRMLS_C); zend_file_handle_dtor(&file_handle TSRMLS_CC); php_output_teardown(); } return SUCCESS; break; case PHP_MODE_HIGHLIGHT: { zend_syntax_highlighter_ini syntax_highlighter_ini; if (open_file_for_scanning(&file_handle TSRMLS_CC) == SUCCESS) { php_get_highlight_struct(&syntax_highlighter_ini); zend_highlight(&syntax_highlighter_ini TSRMLS_CC); if (fastcgi) { goto fastcgi_request_done; } zend_file_handle_dtor(&file_handle TSRMLS_CC); php_output_teardown(); } return SUCCESS; } break; #if 0 /* Zeev might want to do something with this one day */ case PHP_MODE_INDENT: open_file_for_scanning(&file_handle TSRMLS_CC); zend_indent(); zend_file_handle_dtor(&file_handle TSRMLS_CC); php_output_teardown(); return SUCCESS; break; #endif } fastcgi_request_done: { STR_FREE(SG(request_info).path_translated); php_request_shutdown((void *) 0); if (exit_status == 0) { exit_status = EG(exit_status); } if (free_query_string && SG(request_info).query_string) { free(SG(request_info).query_string); SG(request_info).query_string = NULL; } } if (!fastcgi) { if (benchmark) { repeats--; if (repeats > 0) { script_file = NULL; php_optind = orig_optind; php_optarg = orig_optarg; continue; } } break; } /* only fastcgi will get here */ requests++; if (max_requests && (requests == max_requests)) { fcgi_finish_request(request, 1); if (bindpath) { free(bindpath); } if (max_requests != 1) { /* no need to return exit_status of the last request */ exit_status = 0; } break; } /* end of fastcgi loop */ } if (request) { fcgi_destroy_request(request); } fcgi_shutdown(); if (cgi_sapi_module.php_ini_path_override) { free(cgi_sapi_module.php_ini_path_override); } if (cgi_sapi_module.ini_entries) { free(cgi_sapi_module.ini_entries); } } zend_catch { exit_status = 255; } zend_end_try(); out: if (benchmark) { int sec; #ifdef HAVE_GETTIMEOFDAY int usec; gettimeofday(&end, NULL); sec = (int)(end.tv_sec - start.tv_sec); if (end.tv_usec >= start.tv_usec) { usec = (int)(end.tv_usec - start.tv_usec); } else { sec -= 1; usec = (int)(end.tv_usec + 1000000 - start.tv_usec); } fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec); #else time(&end); sec = (int)(end - start); fprintf(stderr, "\nElapsed time: %d sec\n", sec); #endif } #ifndef PHP_WIN32 parent_out: #endif SG(server_context) = NULL; php_module_shutdown(TSRMLS_C); sapi_shutdown(); #ifdef ZTS tsrm_shutdown(); #endif #if defined(PHP_WIN32) && ZEND_DEBUG && 0 _CrtDumpMemoryLeaks(); #endif return exit_status; } Vulnerability Type: Exec Code Overflow +Info CWE ID: CWE-119 Summary: sapi/cgi/cgi_main.c in the CGI component in PHP through 5.4.36, 5.5.x through 5.5.20, and 5.6.x through 5.6.4, when mmap is used to read a .php file, does not properly consider the mapping's length during processing of an invalid file that begins with a # character and lacks a newline character, which causes an out-of-bounds read and might (1) allow remote attackers to obtain sensitive information from php-cgi process memory by leveraging the ability to upload a .php file or (2) trigger unexpected code execution if a valid PHP script is present in memory locations adjacent to the mapping. Commit Message:
Low
23,814
Analyze the following vulnerable code snippet, vulnerability type with description, the commit message and the CWE ID. Determine the impact category of this vulnerability. Output 'High' or 'Medium' or 'Low' only.
Code: void QuicClientPromisedInfo::OnPromiseHeaders(const SpdyHeaderBlock& headers) { SpdyHeaderBlock::const_iterator it = headers.find(kHttp2MethodHeader); DCHECK(it != headers.end()); if (!(it->second == "GET" || it->second == "HEAD")) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid method " << it->second; Reset(QUIC_INVALID_PROMISE_METHOD); return; } if (!SpdyUtils::UrlIsValid(headers)) { QUIC_DVLOG(1) << "Promise for stream " << id_ << " has invalid URL " << url_; Reset(QUIC_INVALID_PROMISE_URL); return; } if (!session_->IsAuthorized(SpdyUtils::GetHostNameFromHeaderBlock(headers))) { Reset(QUIC_UNAUTHORIZED_PROMISE_URL); return; } request_headers_.reset(new SpdyHeaderBlock(headers.Clone())); } Vulnerability Type: Exec Code Overflow CWE ID: CWE-119 Summary: A stack buffer overflow in the QUIC networking stack in Google Chrome prior to 62.0.3202.89 allowed a remote attacker to gain code execution via a malicious server. Commit Message: Fix Stack Buffer Overflow in QuicClientPromisedInfo::OnPromiseHeaders BUG=777728 Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet Change-Id: I6a80db88aafdf20c7abd3847404b818565681310 Reviewed-on: https://chromium-review.googlesource.com/748425 Reviewed-by: Zhongyi Shi <zhongyi@chromium.org> Commit-Queue: Ryan Hamilton <rch@chromium.org> Cr-Commit-Position: refs/heads/master@{#513105}
Low
10,995