instruction
stringclasses
1 value
input
stringlengths
222
112k
output
stringlengths
21
113k
__index_level_0__
int64
15
30k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int iowarrior_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(interface); struct iowarrior *dev = NULL; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; int i; int retval = -ENOMEM; /* allocate memory for our device state and initialize it */ dev = kzalloc(sizeof(struct iowarrior), GFP_KERNEL); if (dev == NULL) { dev_err(&interface->dev, "Out of memory\n"); return retval; } mutex_init(&dev->mutex); atomic_set(&dev->intr_idx, 0); atomic_set(&dev->read_idx, 0); spin_lock_init(&dev->intr_idx_lock); atomic_set(&dev->overflow_flag, 0); init_waitqueue_head(&dev->read_wait); atomic_set(&dev->write_busy, 0); init_waitqueue_head(&dev->write_wait); dev->udev = udev; dev->interface = interface; iface_desc = interface->cur_altsetting; dev->product_id = le16_to_cpu(udev->descriptor.idProduct); /* set up the endpoint information */ for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) { endpoint = &iface_desc->endpoint[i].desc; if (usb_endpoint_is_int_in(endpoint)) dev->int_in_endpoint = endpoint; if (usb_endpoint_is_int_out(endpoint)) /* this one will match for the IOWarrior56 only */ dev->int_out_endpoint = endpoint; } /* we have to check the report_size often, so remember it in the endianness suitable for our machine */ dev->report_size = usb_endpoint_maxp(dev->int_in_endpoint); if ((dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) && (dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW56)) /* IOWarrior56 has wMaxPacketSize different from report size */ dev->report_size = 7; /* create the urb and buffer for reading */ dev->int_in_urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->int_in_urb) { dev_err(&interface->dev, "Couldn't allocate interrupt_in_urb\n"); goto error; } dev->int_in_buffer = kmalloc(dev->report_size, GFP_KERNEL); if (!dev->int_in_buffer) { dev_err(&interface->dev, "Couldn't allocate int_in_buffer\n"); goto error; } usb_fill_int_urb(dev->int_in_urb, dev->udev, usb_rcvintpipe(dev->udev, dev->int_in_endpoint->bEndpointAddress), dev->int_in_buffer, dev->report_size, iowarrior_callback, dev, dev->int_in_endpoint->bInterval); /* create an internal buffer for interrupt data from the device */ dev->read_queue = kmalloc(((dev->report_size + 1) * MAX_INTERRUPT_BUFFER), GFP_KERNEL); if (!dev->read_queue) { dev_err(&interface->dev, "Couldn't allocate read_queue\n"); goto error; } /* Get the serial-number of the chip */ memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial)); usb_string(udev, udev->descriptor.iSerialNumber, dev->chip_serial, sizeof(dev->chip_serial)); if (strlen(dev->chip_serial) != 8) memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial)); /* Set the idle timeout to 0, if this is interface 0 */ if (dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) { usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0A, USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); } /* allow device read and ioctl */ dev->present = 1; /* we can register the device now, as it is ready */ usb_set_intfdata(interface, dev); retval = usb_register_dev(interface, &iowarrior_class); if (retval) { /* something prevented us from registering this driver */ dev_err(&interface->dev, "Not able to get a minor for this device.\n"); usb_set_intfdata(interface, NULL); goto error; } dev->minor = interface->minor; /* let the user know what node this device is now attached to */ dev_info(&interface->dev, "IOWarrior product=0x%x, serial=%s interface=%d " "now attached to iowarrior%d\n", dev->product_id, dev->chip_serial, iface_desc->desc.bInterfaceNumber, dev->minor - IOWARRIOR_MINOR_BASE); return retval; error: iowarrior_delete(dev); return retval; } Commit Message: USB: iowarrior: fix oops with malicious USB descriptors The iowarrior driver expects at least one valid endpoint. If given malicious descriptors that specify 0 for the number of endpoints, it will crash in the probe function. Ensure there is at least one endpoint on the interface before using it. The full report of this issue can be found here: http://seclists.org/bugtraq/2016/Mar/87 Reported-by: Ralf Spenneberg <ralf@spenneberg.net> Cc: stable <stable@vger.kernel.org> Signed-off-by: Josh Boyer <jwboyer@fedoraproject.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID:
static int iowarrior_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev(interface); struct iowarrior *dev = NULL; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; int i; int retval = -ENOMEM; /* allocate memory for our device state and initialize it */ dev = kzalloc(sizeof(struct iowarrior), GFP_KERNEL); if (dev == NULL) { dev_err(&interface->dev, "Out of memory\n"); return retval; } mutex_init(&dev->mutex); atomic_set(&dev->intr_idx, 0); atomic_set(&dev->read_idx, 0); spin_lock_init(&dev->intr_idx_lock); atomic_set(&dev->overflow_flag, 0); init_waitqueue_head(&dev->read_wait); atomic_set(&dev->write_busy, 0); init_waitqueue_head(&dev->write_wait); dev->udev = udev; dev->interface = interface; iface_desc = interface->cur_altsetting; dev->product_id = le16_to_cpu(udev->descriptor.idProduct); if (iface_desc->desc.bNumEndpoints < 1) { dev_err(&interface->dev, "Invalid number of endpoints\n"); retval = -EINVAL; goto error; } /* set up the endpoint information */ for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) { endpoint = &iface_desc->endpoint[i].desc; if (usb_endpoint_is_int_in(endpoint)) dev->int_in_endpoint = endpoint; if (usb_endpoint_is_int_out(endpoint)) /* this one will match for the IOWarrior56 only */ dev->int_out_endpoint = endpoint; } /* we have to check the report_size often, so remember it in the endianness suitable for our machine */ dev->report_size = usb_endpoint_maxp(dev->int_in_endpoint); if ((dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) && (dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW56)) /* IOWarrior56 has wMaxPacketSize different from report size */ dev->report_size = 7; /* create the urb and buffer for reading */ dev->int_in_urb = usb_alloc_urb(0, GFP_KERNEL); if (!dev->int_in_urb) { dev_err(&interface->dev, "Couldn't allocate interrupt_in_urb\n"); goto error; } dev->int_in_buffer = kmalloc(dev->report_size, GFP_KERNEL); if (!dev->int_in_buffer) { dev_err(&interface->dev, "Couldn't allocate int_in_buffer\n"); goto error; } usb_fill_int_urb(dev->int_in_urb, dev->udev, usb_rcvintpipe(dev->udev, dev->int_in_endpoint->bEndpointAddress), dev->int_in_buffer, dev->report_size, iowarrior_callback, dev, dev->int_in_endpoint->bInterval); /* create an internal buffer for interrupt data from the device */ dev->read_queue = kmalloc(((dev->report_size + 1) * MAX_INTERRUPT_BUFFER), GFP_KERNEL); if (!dev->read_queue) { dev_err(&interface->dev, "Couldn't allocate read_queue\n"); goto error; } /* Get the serial-number of the chip */ memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial)); usb_string(udev, udev->descriptor.iSerialNumber, dev->chip_serial, sizeof(dev->chip_serial)); if (strlen(dev->chip_serial) != 8) memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial)); /* Set the idle timeout to 0, if this is interface 0 */ if (dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) { usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0A, USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); } /* allow device read and ioctl */ dev->present = 1; /* we can register the device now, as it is ready */ usb_set_intfdata(interface, dev); retval = usb_register_dev(interface, &iowarrior_class); if (retval) { /* something prevented us from registering this driver */ dev_err(&interface->dev, "Not able to get a minor for this device.\n"); usb_set_intfdata(interface, NULL); goto error; } dev->minor = interface->minor; /* let the user know what node this device is now attached to */ dev_info(&interface->dev, "IOWarrior product=0x%x, serial=%s interface=%d " "now attached to iowarrior%d\n", dev->product_id, dev->chip_serial, iface_desc->desc.bInterfaceNumber, dev->minor - IOWARRIOR_MINOR_BASE); return retval; error: iowarrior_delete(dev); return retval; }
8,153
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip_checkentry(&e->ip)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-264
check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip_checkentry(&e->ip)) return -EINVAL; err = xt_check_entry_offsets(e, e->elems, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }
29,256
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: ScreenLockLibrary* CrosLibrary::GetScreenLockLibrary() { return screen_lock_lib_.GetDefaultImpl(use_stub_impl_); } 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 CWE ID: CWE-189
ScreenLockLibrary* CrosLibrary::GetScreenLockLibrary() {
14,229
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: int ext4_orphan_del(handle_t *handle, struct inode *inode) { struct list_head *prev; struct ext4_inode_info *ei = EXT4_I(inode); struct ext4_sb_info *sbi; __u32 ino_next; struct ext4_iloc iloc; int err = 0; if (!EXT4_SB(inode->i_sb)->s_journal) return 0; mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock); if (list_empty(&ei->i_orphan)) goto out; ino_next = NEXT_ORPHAN(inode); prev = ei->i_orphan.prev; sbi = EXT4_SB(inode->i_sb); jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino); list_del_init(&ei->i_orphan); /* If we're on an error path, we may not have a valid * transaction handle with which to update the orphan list on * disk, but we still need to remove the inode from the linked * list in memory. */ if (!handle) goto out; err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) goto out_err; if (prev == &sbi->s_orphan) { jbd_debug(4, "superblock will point to %u\n", ino_next); BUFFER_TRACE(sbi->s_sbh, "get_write_access"); err = ext4_journal_get_write_access(handle, sbi->s_sbh); if (err) goto out_brelse; sbi->s_es->s_last_orphan = cpu_to_le32(ino_next); err = ext4_handle_dirty_super(handle, inode->i_sb); } else { struct ext4_iloc iloc2; struct inode *i_prev = &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode; jbd_debug(4, "orphan inode %lu will point to %u\n", i_prev->i_ino, ino_next); err = ext4_reserve_inode_write(handle, i_prev, &iloc2); if (err) goto out_brelse; NEXT_ORPHAN(i_prev) = ino_next; err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2); } if (err) goto out_brelse; NEXT_ORPHAN(inode) = 0; err = ext4_mark_iloc_dirty(handle, inode, &iloc); out_err: ext4_std_error(inode->i_sb, err); out: mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock); return err; out_brelse: brelse(iloc.bh); goto out_err; } Commit Message: ext4: avoid hang when mounting non-journal filesystems with orphan list When trying to mount a file system which does not contain a journal, but which does have a orphan list containing an inode which needs to be truncated, the mount call with hang forever in ext4_orphan_cleanup() because ext4_orphan_del() will return immediately without removing the inode from the orphan list, leading to an uninterruptible loop in kernel code which will busy out one of the CPU's on the system. This can be trivially reproduced by trying to mount the file system found in tests/f_orphan_extents_inode/image.gz from the e2fsprogs source tree. If a malicious user were to put this on a USB stick, and mount it on a Linux desktop which has automatic mounts enabled, this could be considered a potential denial of service attack. (Not a big deal in practice, but professional paranoids worry about such things, and have even been known to allocate CVE numbers for such problems.) Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> Reviewed-by: Zheng Liu <wenqing.lz@taobao.com> Cc: stable@vger.kernel.org CWE ID: CWE-399
int ext4_orphan_del(handle_t *handle, struct inode *inode) { struct list_head *prev; struct ext4_inode_info *ei = EXT4_I(inode); struct ext4_sb_info *sbi; __u32 ino_next; struct ext4_iloc iloc; int err = 0; if ((!EXT4_SB(inode->i_sb)->s_journal) && !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) return 0; mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock); if (list_empty(&ei->i_orphan)) goto out; ino_next = NEXT_ORPHAN(inode); prev = ei->i_orphan.prev; sbi = EXT4_SB(inode->i_sb); jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino); list_del_init(&ei->i_orphan); /* If we're on an error path, we may not have a valid * transaction handle with which to update the orphan list on * disk, but we still need to remove the inode from the linked * list in memory. */ if (!handle) goto out; err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) goto out_err; if (prev == &sbi->s_orphan) { jbd_debug(4, "superblock will point to %u\n", ino_next); BUFFER_TRACE(sbi->s_sbh, "get_write_access"); err = ext4_journal_get_write_access(handle, sbi->s_sbh); if (err) goto out_brelse; sbi->s_es->s_last_orphan = cpu_to_le32(ino_next); err = ext4_handle_dirty_super(handle, inode->i_sb); } else { struct ext4_iloc iloc2; struct inode *i_prev = &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode; jbd_debug(4, "orphan inode %lu will point to %u\n", i_prev->i_ino, ino_next); err = ext4_reserve_inode_write(handle, i_prev, &iloc2); if (err) goto out_brelse; NEXT_ORPHAN(i_prev) = ino_next; err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2); } if (err) goto out_brelse; NEXT_ORPHAN(inode) = 0; err = ext4_mark_iloc_dirty(handle, inode, &iloc); out_err: ext4_std_error(inode->i_sb, err); out: mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock); return err; out_brelse: brelse(iloc.bh); goto out_err; }
22,772
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static bool new_idmap_permitted(const struct file *file, struct user_namespace *ns, int cap_setid, struct uid_gid_map *new_map) { /* Allow mapping to your own filesystem ids */ if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) { u32 id = new_map->extent[0].lower_first; if (cap_setid == CAP_SETUID) { kuid_t uid = make_kuid(ns->parent, id); if (uid_eq(uid, current_fsuid())) return true; } else if (cap_setid == CAP_SETGID) { kgid_t gid = make_kgid(ns->parent, id); if (gid_eq(gid, current_fsgid())) return true; } } /* Allow anyone to set a mapping that doesn't require privilege */ if (!cap_valid(cap_setid)) return true; /* Allow the specified ids if we have the appropriate capability * (CAP_SETUID or CAP_SETGID) over the parent user namespace. * And the opener of the id file also had the approprpiate capability. */ if (ns_capable(ns->parent, cap_setid) && file_ns_capable(file, ns->parent, cap_setid)) return true; return false; } Commit Message: userns: Check uid_map's opener's fsuid, not the current fsuid Signed-off-by: Andy Lutomirski <luto@amacapital.net> CWE ID: CWE-264
static bool new_idmap_permitted(const struct file *file, struct user_namespace *ns, int cap_setid, struct uid_gid_map *new_map) { /* Allow mapping to your own filesystem ids */ if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) { u32 id = new_map->extent[0].lower_first; if (cap_setid == CAP_SETUID) { kuid_t uid = make_kuid(ns->parent, id); if (uid_eq(uid, file->f_cred->fsuid)) return true; } else if (cap_setid == CAP_SETGID) { kgid_t gid = make_kgid(ns->parent, id); if (gid_eq(gid, file->f_cred->fsgid)) return true; } } /* Allow anyone to set a mapping that doesn't require privilege */ if (!cap_valid(cap_setid)) return true; /* Allow the specified ids if we have the appropriate capability * (CAP_SETUID or CAP_SETGID) over the parent user namespace. * And the opener of the id file also had the approprpiate capability. */ if (ns_capable(ns->parent, cap_setid) && file_ns_capable(file, ns->parent, cap_setid)) return true; return false; }
26,768
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: ContentEncoding::GetEncryptionByIndex(unsigned long idx) const { const ptrdiff_t count = encryption_entries_end_ - encryption_entries_; assert(count >= 0); if (idx >= static_cast<unsigned long>(count)) return NULL; return encryption_entries_[idx]; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
ContentEncoding::GetEncryptionByIndex(unsigned long idx) const { const ContentEncoding::ContentEncryption* ContentEncoding::GetEncryptionByIndex( unsigned long idx) const { const ptrdiff_t count = encryption_entries_end_ - encryption_entries_; assert(count >= 0); if (idx >= static_cast<unsigned long>(count)) return NULL; return encryption_entries_[idx]; }
7,937
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_KeyTransRecipientInfo *ktri = ri->d.ktri; EVP_PKEY *pkey = ktri->pkey; unsigned char *ek = NULL; size_t eklen; int ret = 0; CMS_EncryptedContentInfo *ec; ec = cms->d.envelopedData->encryptedContentInfo; CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY); return 0; return 0; } Commit Message: CWE ID: CWE-311
static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_KeyTransRecipientInfo *ktri = ri->d.ktri; EVP_PKEY *pkey = ktri->pkey; unsigned char *ek = NULL; size_t eklen; int ret = 0; size_t fixlen = 0; CMS_EncryptedContentInfo *ec; ec = cms->d.envelopedData->encryptedContentInfo; CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY); return 0; return 0; }
17,909
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: fbPictureInit (ScreenPtr pScreen, PictFormatPtr formats, int nformats) { srcRepeat = FALSE; if (maskTransform) maskRepeat = FALSE; if (!miComputeCompositeRegion (&region, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (&region); pbox = REGION_RECTS (&region); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk - pMask->pDrawable->y, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; y_msk += pMask->pDrawable->y; } if (srcRepeat) { y_src = mod (y_src - pSrc->pDrawable->y, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; y_src += pSrc->pDrawable->y; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk - pMask->pDrawable->x, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; x_msk += pMask->pDrawable->x; } if (srcRepeat) { x_src = mod (x_src - pSrc->pDrawable->x, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; x_src += pSrc->pDrawable->x; } (*func) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, &region); } Commit Message: CWE ID: CWE-189
fbPictureInit (ScreenPtr pScreen, PictFormatPtr formats, int nformats) { srcRepeat = FALSE; if (maskTransform) maskRepeat = FALSE; fbWalkCompositeRegion (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height, srcRepeat, maskRepeat, func); }
18,947
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: char *cJSON_PrintUnformatted( cJSON *item ) { return print_value( item, 0, 0 ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
char *cJSON_PrintUnformatted( cJSON *item ) char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);} char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);} char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt) { printbuffer p; p.buffer=(char*)cJSON_malloc(prebuffer); p.length=prebuffer; p.offset=0; return print_value(item,0,fmt,&p); }
1,554
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void GpuCommandBufferStub::OnRegisterTransferBuffer( base::SharedMemoryHandle transfer_buffer, size_t size, int32 id_request, IPC::Message* reply_message) { #if defined(OS_WIN) base::SharedMemory shared_memory(transfer_buffer, false, channel_->renderer_process()); #else #endif if (command_buffer_.get()) { int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory, size, id_request); GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message, id); } else { reply_message->set_reply_error(); } Send(reply_message); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuCommandBufferStub::OnRegisterTransferBuffer( base::SharedMemoryHandle transfer_buffer, size_t size, int32 id_request, IPC::Message* reply_message) { if (command_buffer_.get()) { int32 id = command_buffer_->RegisterTransferBuffer(&shared_memory, size, id_request); GpuCommandBufferMsg_RegisterTransferBuffer::WriteReplyParams(reply_message, id); } else { reply_message->set_reply_error(); } Send(reply_message); }
17,356
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int cipso_v4_delopt(struct ip_options **opt_ptr) { int hdr_delta = 0; struct ip_options *opt = *opt_ptr; if (opt->srr || opt->rr || opt->ts || opt->router_alert) { u8 cipso_len; u8 cipso_off; unsigned char *cipso_ptr; int iter; int optlen_new; cipso_off = opt->cipso - sizeof(struct iphdr); cipso_ptr = &opt->__data[cipso_off]; cipso_len = cipso_ptr[1]; if (opt->srr > opt->cipso) opt->srr -= cipso_len; if (opt->rr > opt->cipso) opt->rr -= cipso_len; if (opt->ts > opt->cipso) opt->ts -= cipso_len; if (opt->router_alert > opt->cipso) opt->router_alert -= cipso_len; opt->cipso = 0; memmove(cipso_ptr, cipso_ptr + cipso_len, opt->optlen - cipso_off - cipso_len); /* determining the new total option length is tricky because of * the padding necessary, the only thing i can think to do at * this point is walk the options one-by-one, skipping the * padding at the end to determine the actual option size and * from there we can determine the new total option length */ iter = 0; optlen_new = 0; while (iter < opt->optlen) if (opt->__data[iter] != IPOPT_NOP) { iter += opt->__data[iter + 1]; optlen_new = iter; } else iter++; hdr_delta = opt->optlen; opt->optlen = (optlen_new + 3) & ~3; hdr_delta -= opt->optlen; } else { /* only the cipso option was present on the socket so we can * remove the entire option struct */ *opt_ptr = NULL; hdr_delta = opt->optlen; kfree(opt); } return hdr_delta; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-362
static int cipso_v4_delopt(struct ip_options **opt_ptr) static int cipso_v4_delopt(struct ip_options_rcu **opt_ptr) { int hdr_delta = 0; struct ip_options_rcu *opt = *opt_ptr; if (opt->opt.srr || opt->opt.rr || opt->opt.ts || opt->opt.router_alert) { u8 cipso_len; u8 cipso_off; unsigned char *cipso_ptr; int iter; int optlen_new; cipso_off = opt->opt.cipso - sizeof(struct iphdr); cipso_ptr = &opt->opt.__data[cipso_off]; cipso_len = cipso_ptr[1]; if (opt->opt.srr > opt->opt.cipso) opt->opt.srr -= cipso_len; if (opt->opt.rr > opt->opt.cipso) opt->opt.rr -= cipso_len; if (opt->opt.ts > opt->opt.cipso) opt->opt.ts -= cipso_len; if (opt->opt.router_alert > opt->opt.cipso) opt->opt.router_alert -= cipso_len; opt->opt.cipso = 0; memmove(cipso_ptr, cipso_ptr + cipso_len, opt->opt.optlen - cipso_off - cipso_len); /* determining the new total option length is tricky because of * the padding necessary, the only thing i can think to do at * this point is walk the options one-by-one, skipping the * padding at the end to determine the actual option size and * from there we can determine the new total option length */ iter = 0; optlen_new = 0; while (iter < opt->opt.optlen) if (opt->opt.__data[iter] != IPOPT_NOP) { iter += opt->opt.__data[iter + 1]; optlen_new = iter; } else iter++; hdr_delta = opt->opt.optlen; opt->opt.optlen = (optlen_new + 3) & ~3; hdr_delta -= opt->opt.optlen; } else { /* only the cipso option was present on the socket so we can * remove the entire option struct */ *opt_ptr = NULL; hdr_delta = opt->opt.optlen; call_rcu(&opt->rcu, opt_kfree_rcu); } return hdr_delta; }
29,097
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: pimv2_print(netdissect_options *ndo, register const u_char *bp, register u_int len, const u_char *bp2) { register const u_char *ep; register const struct pim *pim = (const struct pim *)bp; int advance; enum checksum_status cksum_status; ep = (const u_char *)ndo->ndo_snapend; if (bp >= ep) return; if (ep > bp + len) ep = bp + len; ND_TCHECK(pim->pim_rsv); pimv2_addr_len = pim->pim_rsv; if (pimv2_addr_len != 0) ND_PRINT((ndo, ", RFC2117-encoding")); ND_PRINT((ndo, ", cksum 0x%04x ", EXTRACT_16BITS(&pim->pim_cksum))); if (EXTRACT_16BITS(&pim->pim_cksum) == 0) { ND_PRINT((ndo, "(unverified)")); } else { if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) { /* * The checksum only covers the packet header, * not the encapsulated packet. */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8); if (cksum_status == INCORRECT) { /* * To quote RFC 4601, "For interoperability * reasons, a message carrying a checksum * calculated over the entire PIM Register * message should also be accepted." */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, len); } } else { /* * The checksum covers the entire packet. */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, len); } switch (cksum_status) { case CORRECT: ND_PRINT((ndo, "(correct)")); break; case INCORRECT: ND_PRINT((ndo, "(incorrect)")); break; case UNVERIFIED: ND_PRINT((ndo, "(unverified)")); break; } } switch (PIM_TYPE(pim->pim_typever)) { case PIMV2_TYPE_HELLO: { uint16_t otype, olen; bp += 4; while (bp < ep) { ND_TCHECK2(bp[0], 4); otype = EXTRACT_16BITS(&bp[0]); olen = EXTRACT_16BITS(&bp[2]); ND_TCHECK2(bp[0], 4 + olen); ND_PRINT((ndo, "\n\t %s Option (%u), length %u, Value: ", tok2str(pimv2_hello_option_values, "Unknown", otype), otype, olen)); bp += 4; switch (otype) { case PIMV2_HELLO_OPTION_HOLDTIME: unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); break; case PIMV2_HELLO_OPTION_LANPRUNEDELAY: if (olen != 4) { ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen)); } else { char t_bit; uint16_t lan_delay, override_interval; lan_delay = EXTRACT_16BITS(bp); override_interval = EXTRACT_16BITS(bp+2); t_bit = (lan_delay & 0x8000)? 1 : 0; lan_delay &= ~0x8000; ND_PRINT((ndo, "\n\t T-bit=%d, LAN delay %dms, Override interval %dms", t_bit, lan_delay, override_interval)); } break; case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD: case PIMV2_HELLO_OPTION_DR_PRIORITY: switch (olen) { case 0: ND_PRINT((ndo, "Bi-Directional Capability (Old)")); break; case 4: ND_PRINT((ndo, "%u", EXTRACT_32BITS(bp))); break; default: ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen)); break; } break; case PIMV2_HELLO_OPTION_GENID: ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(bp))); break; case PIMV2_HELLO_OPTION_REFRESH_CAP: ND_PRINT((ndo, "v%d", *bp)); if (*(bp+1) != 0) { ND_PRINT((ndo, ", interval ")); unsigned_relts_print(ndo, *(bp+1)); } if (EXTRACT_16BITS(bp+2) != 0) { ND_PRINT((ndo, " ?0x%04x?", EXTRACT_16BITS(bp+2))); } break; case PIMV2_HELLO_OPTION_BIDIR_CAP: break; case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD: case PIMV2_HELLO_OPTION_ADDRESS_LIST: if (ndo->ndo_vflag > 1) { const u_char *ptr = bp; while (ptr < (bp+olen)) { ND_PRINT((ndo, "\n\t ")); advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0); if (advance < 0) { ND_PRINT((ndo, "...")); break; } ptr += advance; } } break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, bp, "\n\t ", olen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag> 1) print_unknown_data(ndo, bp, "\n\t ", olen); bp += olen; } break; } case PIMV2_TYPE_REGISTER: { const struct ip *ip; ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN); ND_PRINT((ndo, ", Flags [ %s ]\n\t", tok2str(pimv2_register_flag_values, "none", EXTRACT_32BITS(bp+4)))); bp += 8; len -= 8; /* encapsulated multicast packet */ ip = (const struct ip *)bp; switch (IP_V(ip)) { case 0: /* Null header */ ND_PRINT((ndo, "IP-Null-header %s > %s", ipaddr_string(ndo, &ip->ip_src), ipaddr_string(ndo, &ip->ip_dst))); break; case 4: /* IPv4 */ ip_print(ndo, bp, len); break; case 6: /* IPv6 */ ip6_print(ndo, bp, len); break; default: ND_PRINT((ndo, "IP ver %d", IP_V(ip))); break; } break; } case PIMV2_TYPE_REGISTER_STOP: bp += 4; len -= 4; if (bp >= ep) break; ND_PRINT((ndo, " group=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; len -= advance; if (bp >= ep) break; ND_PRINT((ndo, " source=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; len -= advance; break; case PIMV2_TYPE_JOIN_PRUNE: case PIMV2_TYPE_GRAFT: case PIMV2_TYPE_GRAFT_ACK: /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |PIM Ver| Type | Addr length | Checksum | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Unicast-Upstream Neighbor Address | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Reserved | Num groups | Holdtime | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Multicast Group Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Number of Joined Sources | Number of Pruned Sources | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Joined Source Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Joined Source Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Pruned Source Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Pruned Source Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Multicast Group Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ { uint8_t ngroup; uint16_t holdtime; uint16_t njoin; uint16_t nprune; int i, j; bp += 4; len -= 4; if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/ if (bp >= ep) break; ND_PRINT((ndo, ", upstream-neighbor: ")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; len -= advance; } if (bp + 4 > ep) break; ngroup = bp[1]; holdtime = EXTRACT_16BITS(&bp[2]); ND_PRINT((ndo, "\n\t %u group(s)", ngroup)); if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/ ND_PRINT((ndo, ", holdtime: ")); if (holdtime == 0xffff) ND_PRINT((ndo, "infinite")); else unsigned_relts_print(ndo, holdtime); } bp += 4; len -= 4; for (i = 0; i < ngroup; i++) { if (bp >= ep) goto jp_done; ND_PRINT((ndo, "\n\t group #%u: ", i+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...)")); goto jp_done; } bp += advance; len -= advance; if (bp + 4 > ep) { ND_PRINT((ndo, "...)")); goto jp_done; } njoin = EXTRACT_16BITS(&bp[0]); nprune = EXTRACT_16BITS(&bp[2]); ND_PRINT((ndo, ", joined sources: %u, pruned sources: %u", njoin, nprune)); bp += 4; len -= 4; for (j = 0; j < njoin; j++) { ND_PRINT((ndo, "\n\t joined source #%u: ", j+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { ND_PRINT((ndo, "...)")); goto jp_done; } bp += advance; len -= advance; } for (j = 0; j < nprune; j++) { ND_PRINT((ndo, "\n\t pruned source #%u: ", j+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { ND_PRINT((ndo, "...)")); goto jp_done; } bp += advance; len -= advance; } } jp_done: break; } case PIMV2_TYPE_BOOTSTRAP: { int i, j, frpcnt; bp += 4; /* Fragment Tag, Hash Mask len, and BSR-priority */ if (bp + sizeof(uint16_t) >= ep) break; ND_PRINT((ndo, " tag=%x", EXTRACT_16BITS(bp))); bp += sizeof(uint16_t); if (bp >= ep) break; ND_PRINT((ndo, " hashmlen=%d", bp[0])); if (bp + 1 >= ep) break; ND_PRINT((ndo, " BSRprio=%d", bp[1])); bp += 2; /* Encoded-Unicast-BSR-Address */ if (bp >= ep) break; ND_PRINT((ndo, " BSR=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; for (i = 0; bp < ep; i++) { /* Encoded-Group Address */ ND_PRINT((ndo, " (group%d: ", i)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...)")); goto bs_done; } bp += advance; /* RP-Count, Frag RP-Cnt, and rsvd */ if (bp >= ep) { ND_PRINT((ndo, "...)")); goto bs_done; } ND_PRINT((ndo, " RPcnt=%d", bp[0])); if (bp + 1 >= ep) { ND_PRINT((ndo, "...)")); goto bs_done; } ND_PRINT((ndo, " FRPcnt=%d", frpcnt = bp[1])); bp += 4; for (j = 0; j < frpcnt && bp < ep; j++) { /* each RP info */ ND_PRINT((ndo, " RP%d=", j)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...)")); goto bs_done; } bp += advance; if (bp + 1 >= ep) { ND_PRINT((ndo, "...)")); goto bs_done; } ND_PRINT((ndo, ",holdtime=")); unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); if (bp + 2 >= ep) { ND_PRINT((ndo, "...)")); goto bs_done; } ND_PRINT((ndo, ",prio=%d", bp[2])); bp += 4; } ND_PRINT((ndo, ")")); } bs_done: break; } case PIMV2_TYPE_ASSERT: bp += 4; len -= 4; if (bp >= ep) break; ND_PRINT((ndo, " group=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; len -= advance; if (bp >= ep) break; ND_PRINT((ndo, " src=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; len -= advance; if (bp + 8 > ep) break; if (bp[0] & 0x80) ND_PRINT((ndo, " RPT")); ND_PRINT((ndo, " pref=%u", EXTRACT_32BITS(&bp[0]) & 0x7fffffff)); ND_PRINT((ndo, " metric=%u", EXTRACT_32BITS(&bp[4]))); break; case PIMV2_TYPE_CANDIDATE_RP: { int i, pfxcnt; bp += 4; /* Prefix-Cnt, Priority, and Holdtime */ if (bp >= ep) break; ND_PRINT((ndo, " prefix-cnt=%d", bp[0])); pfxcnt = bp[0]; if (bp + 1 >= ep) break; ND_PRINT((ndo, " prio=%d", bp[1])); if (bp + 3 >= ep) break; ND_PRINT((ndo, " holdtime=")); unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); bp += 4; /* Encoded-Unicast-RP-Address */ if (bp >= ep) break; ND_PRINT((ndo, " RP=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; /* Encoded-Group Addresses */ for (i = 0; i < pfxcnt && bp < ep; i++) { ND_PRINT((ndo, " Group%d=", i)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; } break; } case PIMV2_TYPE_PRUNE_REFRESH: ND_PRINT((ndo, " src=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; ND_PRINT((ndo, " grp=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; ND_PRINT((ndo, " forwarder=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; ND_TCHECK2(bp[0], 2); ND_PRINT((ndo, " TUNR ")); unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); break; default: ND_PRINT((ndo, " [type %d]", PIM_TYPE(pim->pim_typever))); break; } return; trunc: ND_PRINT((ndo, "[|pim]")); } Commit Message: CVE-2017-12996/PIMv2: Make sure PIM TLVs have the right length. We do bounds checks based on the TLV length, so if the TLV's length is too short, and we don't check for that, we could end up fetching data past the end of the TLV - including past the length of the captured data in the packet. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
pimv2_print(netdissect_options *ndo, register const u_char *bp, register u_int len, const u_char *bp2) { register const u_char *ep; register const struct pim *pim = (const struct pim *)bp; int advance; enum checksum_status cksum_status; ep = (const u_char *)ndo->ndo_snapend; if (bp >= ep) return; if (ep > bp + len) ep = bp + len; ND_TCHECK(pim->pim_rsv); pimv2_addr_len = pim->pim_rsv; if (pimv2_addr_len != 0) ND_PRINT((ndo, ", RFC2117-encoding")); ND_PRINT((ndo, ", cksum 0x%04x ", EXTRACT_16BITS(&pim->pim_cksum))); if (EXTRACT_16BITS(&pim->pim_cksum) == 0) { ND_PRINT((ndo, "(unverified)")); } else { if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) { /* * The checksum only covers the packet header, * not the encapsulated packet. */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8); if (cksum_status == INCORRECT) { /* * To quote RFC 4601, "For interoperability * reasons, a message carrying a checksum * calculated over the entire PIM Register * message should also be accepted." */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, len); } } else { /* * The checksum covers the entire packet. */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, len); } switch (cksum_status) { case CORRECT: ND_PRINT((ndo, "(correct)")); break; case INCORRECT: ND_PRINT((ndo, "(incorrect)")); break; case UNVERIFIED: ND_PRINT((ndo, "(unverified)")); break; } } switch (PIM_TYPE(pim->pim_typever)) { case PIMV2_TYPE_HELLO: { uint16_t otype, olen; bp += 4; while (bp < ep) { ND_TCHECK2(bp[0], 4); otype = EXTRACT_16BITS(&bp[0]); olen = EXTRACT_16BITS(&bp[2]); ND_TCHECK2(bp[0], 4 + olen); ND_PRINT((ndo, "\n\t %s Option (%u), length %u, Value: ", tok2str(pimv2_hello_option_values, "Unknown", otype), otype, olen)); bp += 4; switch (otype) { case PIMV2_HELLO_OPTION_HOLDTIME: if (olen != 2) { ND_PRINT((ndo, "ERROR: Option Length != 2 Bytes (%u)", olen)); } else { unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); } break; case PIMV2_HELLO_OPTION_LANPRUNEDELAY: if (olen != 4) { ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen)); } else { char t_bit; uint16_t lan_delay, override_interval; lan_delay = EXTRACT_16BITS(bp); override_interval = EXTRACT_16BITS(bp+2); t_bit = (lan_delay & 0x8000)? 1 : 0; lan_delay &= ~0x8000; ND_PRINT((ndo, "\n\t T-bit=%d, LAN delay %dms, Override interval %dms", t_bit, lan_delay, override_interval)); } break; case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD: case PIMV2_HELLO_OPTION_DR_PRIORITY: switch (olen) { case 0: ND_PRINT((ndo, "Bi-Directional Capability (Old)")); break; case 4: ND_PRINT((ndo, "%u", EXTRACT_32BITS(bp))); break; default: ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen)); break; } break; case PIMV2_HELLO_OPTION_GENID: if (olen != 4) { ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen)); } else { ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(bp))); } break; case PIMV2_HELLO_OPTION_REFRESH_CAP: if (olen != 4) { ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen)); } else { ND_PRINT((ndo, "v%d", *bp)); if (*(bp+1) != 0) { ND_PRINT((ndo, ", interval ")); unsigned_relts_print(ndo, *(bp+1)); } if (EXTRACT_16BITS(bp+2) != 0) { ND_PRINT((ndo, " ?0x%04x?", EXTRACT_16BITS(bp+2))); } } break; case PIMV2_HELLO_OPTION_BIDIR_CAP: break; case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD: case PIMV2_HELLO_OPTION_ADDRESS_LIST: if (ndo->ndo_vflag > 1) { const u_char *ptr = bp; while (ptr < (bp+olen)) { ND_PRINT((ndo, "\n\t ")); advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0); if (advance < 0) { ND_PRINT((ndo, "...")); break; } ptr += advance; } } break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, bp, "\n\t ", olen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag> 1) print_unknown_data(ndo, bp, "\n\t ", olen); bp += olen; } break; } case PIMV2_TYPE_REGISTER: { const struct ip *ip; ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN); ND_PRINT((ndo, ", Flags [ %s ]\n\t", tok2str(pimv2_register_flag_values, "none", EXTRACT_32BITS(bp+4)))); bp += 8; len -= 8; /* encapsulated multicast packet */ ip = (const struct ip *)bp; switch (IP_V(ip)) { case 0: /* Null header */ ND_PRINT((ndo, "IP-Null-header %s > %s", ipaddr_string(ndo, &ip->ip_src), ipaddr_string(ndo, &ip->ip_dst))); break; case 4: /* IPv4 */ ip_print(ndo, bp, len); break; case 6: /* IPv6 */ ip6_print(ndo, bp, len); break; default: ND_PRINT((ndo, "IP ver %d", IP_V(ip))); break; } break; } case PIMV2_TYPE_REGISTER_STOP: bp += 4; len -= 4; if (bp >= ep) break; ND_PRINT((ndo, " group=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; len -= advance; if (bp >= ep) break; ND_PRINT((ndo, " source=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; len -= advance; break; case PIMV2_TYPE_JOIN_PRUNE: case PIMV2_TYPE_GRAFT: case PIMV2_TYPE_GRAFT_ACK: /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |PIM Ver| Type | Addr length | Checksum | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Unicast-Upstream Neighbor Address | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Reserved | Num groups | Holdtime | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Multicast Group Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Number of Joined Sources | Number of Pruned Sources | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Joined Source Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Joined Source Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Pruned Source Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Pruned Source Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Multicast Group Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ { uint8_t ngroup; uint16_t holdtime; uint16_t njoin; uint16_t nprune; int i, j; bp += 4; len -= 4; if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/ if (bp >= ep) break; ND_PRINT((ndo, ", upstream-neighbor: ")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; len -= advance; } if (bp + 4 > ep) break; ngroup = bp[1]; holdtime = EXTRACT_16BITS(&bp[2]); ND_PRINT((ndo, "\n\t %u group(s)", ngroup)); if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/ ND_PRINT((ndo, ", holdtime: ")); if (holdtime == 0xffff) ND_PRINT((ndo, "infinite")); else unsigned_relts_print(ndo, holdtime); } bp += 4; len -= 4; for (i = 0; i < ngroup; i++) { if (bp >= ep) goto jp_done; ND_PRINT((ndo, "\n\t group #%u: ", i+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...)")); goto jp_done; } bp += advance; len -= advance; if (bp + 4 > ep) { ND_PRINT((ndo, "...)")); goto jp_done; } njoin = EXTRACT_16BITS(&bp[0]); nprune = EXTRACT_16BITS(&bp[2]); ND_PRINT((ndo, ", joined sources: %u, pruned sources: %u", njoin, nprune)); bp += 4; len -= 4; for (j = 0; j < njoin; j++) { ND_PRINT((ndo, "\n\t joined source #%u: ", j+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { ND_PRINT((ndo, "...)")); goto jp_done; } bp += advance; len -= advance; } for (j = 0; j < nprune; j++) { ND_PRINT((ndo, "\n\t pruned source #%u: ", j+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { ND_PRINT((ndo, "...)")); goto jp_done; } bp += advance; len -= advance; } } jp_done: break; } case PIMV2_TYPE_BOOTSTRAP: { int i, j, frpcnt; bp += 4; /* Fragment Tag, Hash Mask len, and BSR-priority */ if (bp + sizeof(uint16_t) >= ep) break; ND_PRINT((ndo, " tag=%x", EXTRACT_16BITS(bp))); bp += sizeof(uint16_t); if (bp >= ep) break; ND_PRINT((ndo, " hashmlen=%d", bp[0])); if (bp + 1 >= ep) break; ND_PRINT((ndo, " BSRprio=%d", bp[1])); bp += 2; /* Encoded-Unicast-BSR-Address */ if (bp >= ep) break; ND_PRINT((ndo, " BSR=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; for (i = 0; bp < ep; i++) { /* Encoded-Group Address */ ND_PRINT((ndo, " (group%d: ", i)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...)")); goto bs_done; } bp += advance; /* RP-Count, Frag RP-Cnt, and rsvd */ if (bp >= ep) { ND_PRINT((ndo, "...)")); goto bs_done; } ND_PRINT((ndo, " RPcnt=%d", bp[0])); if (bp + 1 >= ep) { ND_PRINT((ndo, "...)")); goto bs_done; } ND_PRINT((ndo, " FRPcnt=%d", frpcnt = bp[1])); bp += 4; for (j = 0; j < frpcnt && bp < ep; j++) { /* each RP info */ ND_PRINT((ndo, " RP%d=", j)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...)")); goto bs_done; } bp += advance; if (bp + 1 >= ep) { ND_PRINT((ndo, "...)")); goto bs_done; } ND_PRINT((ndo, ",holdtime=")); unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); if (bp + 2 >= ep) { ND_PRINT((ndo, "...)")); goto bs_done; } ND_PRINT((ndo, ",prio=%d", bp[2])); bp += 4; } ND_PRINT((ndo, ")")); } bs_done: break; } case PIMV2_TYPE_ASSERT: bp += 4; len -= 4; if (bp >= ep) break; ND_PRINT((ndo, " group=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; len -= advance; if (bp >= ep) break; ND_PRINT((ndo, " src=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; len -= advance; if (bp + 8 > ep) break; if (bp[0] & 0x80) ND_PRINT((ndo, " RPT")); ND_PRINT((ndo, " pref=%u", EXTRACT_32BITS(&bp[0]) & 0x7fffffff)); ND_PRINT((ndo, " metric=%u", EXTRACT_32BITS(&bp[4]))); break; case PIMV2_TYPE_CANDIDATE_RP: { int i, pfxcnt; bp += 4; /* Prefix-Cnt, Priority, and Holdtime */ if (bp >= ep) break; ND_PRINT((ndo, " prefix-cnt=%d", bp[0])); pfxcnt = bp[0]; if (bp + 1 >= ep) break; ND_PRINT((ndo, " prio=%d", bp[1])); if (bp + 3 >= ep) break; ND_PRINT((ndo, " holdtime=")); unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); bp += 4; /* Encoded-Unicast-RP-Address */ if (bp >= ep) break; ND_PRINT((ndo, " RP=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; /* Encoded-Group Addresses */ for (i = 0; i < pfxcnt && bp < ep; i++) { ND_PRINT((ndo, " Group%d=", i)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; } break; } case PIMV2_TYPE_PRUNE_REFRESH: ND_PRINT((ndo, " src=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; ND_PRINT((ndo, " grp=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; ND_PRINT((ndo, " forwarder=")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, "...")); break; } bp += advance; ND_TCHECK2(bp[0], 2); ND_PRINT((ndo, " TUNR ")); unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); break; default: ND_PRINT((ndo, " [type %d]", PIM_TYPE(pim->pim_typever))); break; } return; trunc: ND_PRINT((ndo, "[|pim]")); }
5,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void MessageService::OpenChannelToNativeApp( int source_process_id, int source_routing_id, int receiver_port_id, const std::string& source_extension_id, const std::string& native_app_name, const std::string& channel_name, const std::string& connect_message) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<MessageChannel> channel(new MessageChannel()); channel->opener.reset(new ExtensionMessagePort(source, MSG_ROUTING_CONTROL, source_extension_id)); NativeMessageProcessHost::MessageType type = channel_name == "chrome.runtime.sendNativeMessage" ? NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST : NativeMessageProcessHost::TYPE_CONNECT; content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&NativeMessageProcessHost::Create, base::WeakPtr<NativeMessageProcessHost::Client>( weak_factory_.GetWeakPtr()), native_app_name, connect_message, receiver_port_id, type, base::Bind(&MessageService::FinalizeOpenChannelToNativeApp, weak_factory_.GetWeakPtr(), receiver_port_id, channel_name, base::Passed(&channel), tab_json))); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void MessageService::OpenChannelToNativeApp( int source_process_id, int source_routing_id, int receiver_port_id, const std::string& source_extension_id, const std::string& native_app_name, const std::string& channel_name, const std::string& connect_message) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<MessageChannel> channel(new MessageChannel()); channel->opener.reset(new ExtensionMessagePort(source, MSG_ROUTING_CONTROL, source_extension_id)); NativeMessageProcessHost::MessageType type = channel_name == "chrome.runtime.sendNativeMessage" ? NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST : NativeMessageProcessHost::TYPE_CONNECT; content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&NativeMessageProcessHost::Create, base::WeakPtr<NativeMessageProcessHost::Client>( weak_factory_.GetWeakPtr()), native_app_name, connect_message, receiver_port_id, type, base::Bind(&MessageService::FinalizeOpenChannelToNativeApp, weak_factory_.GetWeakPtr(), receiver_port_id, channel_name, base::Passed(&channel), tab_json))); }
26,396
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int cp2112_gpio_direction_output(struct gpio_chip *chip, unsigned offset, int value) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; unsigned long flags; int ret; spin_lock_irqsave(&dev->lock, flags); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto fail; } buf[1] |= 1 << offset; buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto fail; } spin_unlock_irqrestore(&dev->lock, flags); /* * Set gpio value when output direction is already set, * as specified in AN495, Rev. 0.2, cpt. 4.4 */ cp2112_gpio_set(chip, offset, value); return 0; fail: spin_unlock_irqrestore(&dev->lock, flags); return ret < 0 ? ret : -EIO; } Commit Message: HID: cp2112: fix sleep-while-atomic A recent commit fixing DMA-buffers on stack added a shared transfer buffer protected by a spinlock. This is broken as the USB HID request callbacks can sleep. Fix this up by replacing the spinlock with a mutex. Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable") Cc: stable <stable@vger.kernel.org> # 4.9 Signed-off-by: Johan Hovold <johan@kernel.org> Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz> CWE ID: CWE-404
static int cp2112_gpio_direction_output(struct gpio_chip *chip, unsigned offset, int value) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; int ret; mutex_lock(&dev->lock); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto fail; } buf[1] |= 1 << offset; buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto fail; } mutex_unlock(&dev->lock); /* * Set gpio value when output direction is already set, * as specified in AN495, Rev. 0.2, cpt. 4.4 */ cp2112_gpio_set(chip, offset, value); return 0; fail: mutex_unlock(&dev->lock); return ret < 0 ? ret : -EIO; }
8,316
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool Cues::DoneParsing() const { const long long stop = m_start + m_size; return (m_pos >= stop); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool Cues::DoneParsing() const
15,536
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: long Chapters::Edition::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) { // Atom ID status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Chapters::Edition::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) { // Atom ID status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; return 0; }
20,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function 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; } 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} CWE ID: CWE-20
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); const net::ProxyBypassRules::ParseFormat kFormats[] = { net::ProxyBypassRules::ParseFormat::kDefault, net::ProxyBypassRules::ParseFormat::kHostnameSuffixMatching, }; for (auto format : kFormats) rules.ParseFromString(input, format); return 0; }
19,018
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int _make_decode_table(codebook *s,char *lengthlist,long quantvals, oggpack_buffer *opb,int maptype){ int i; ogg_uint32_t *work; if (!lengthlist) return 1; if(s->dec_nodeb==4){ /* Over-allocate by using s->entries instead of used_entries. * This means that we can use s->entries to enforce size in * _make_words without messing up length list looping. * This probably wastes a bit of space, but it shouldn't * impact behavior or size too much. */ s->dec_table=_ogg_malloc((s->entries*2+1)*sizeof(*work)); if (!s->dec_table) return 1; /* +1 (rather than -2) is to accommodate 0 and 1 sized books, which are specialcased to nodeb==4 */ if(_make_words(lengthlist,s->entries, s->dec_table,quantvals,s,opb,maptype))return 1; return 0; } if (s->used_entries > INT_MAX/2 || s->used_entries*2 > INT_MAX/((long) sizeof(*work)) - 1) return 1; /* Overallocate as above */ work=calloc((s->entries*2+1),sizeof(*work)); if (!work) return 1; if(_make_words(lengthlist,s->entries,work,quantvals,s,opb,maptype)) goto error_out; if (s->used_entries > INT_MAX/(s->dec_leafw+1)) goto error_out; if (s->dec_nodeb && s->used_entries * (s->dec_leafw+1) > INT_MAX/s->dec_nodeb) goto error_out; s->dec_table=_ogg_malloc((s->used_entries*(s->dec_leafw+1)-2)* s->dec_nodeb); if (!s->dec_table) goto error_out; if(s->dec_leafw==1){ switch(s->dec_nodeb){ case 1: for(i=0;i<s->used_entries*2-2;i++) ((unsigned char *)s->dec_table)[i]=(unsigned char) (((work[i] & 0x80000000UL) >> 24) | work[i]); break; case 2: for(i=0;i<s->used_entries*2-2;i++) ((ogg_uint16_t *)s->dec_table)[i]=(ogg_uint16_t) (((work[i] & 0x80000000UL) >> 16) | work[i]); break; } }else{ /* more complex; we have to do a two-pass repack that updates the node indexing. */ long top=s->used_entries*3-2; if(s->dec_nodeb==1){ unsigned char *out=(unsigned char *)s->dec_table; for(i=s->used_entries*2-4;i>=0;i-=2){ if(work[i]&0x80000000UL){ if(work[i+1]&0x80000000UL){ top-=4; out[top]=(work[i]>>8 & 0x7f)|0x80; out[top+1]=(work[i+1]>>8 & 0x7f)|0x80; out[top+2]=work[i] & 0xff; out[top+3]=work[i+1] & 0xff; }else{ top-=3; out[top]=(work[i]>>8 & 0x7f)|0x80; out[top+1]=work[work[i+1]*2]; out[top+2]=work[i] & 0xff; } }else{ if(work[i+1]&0x80000000UL){ top-=3; out[top]=work[work[i]*2]; out[top+1]=(work[i+1]>>8 & 0x7f)|0x80; out[top+2]=work[i+1] & 0xff; }else{ top-=2; out[top]=work[work[i]*2]; out[top+1]=work[work[i+1]*2]; } } work[i]=top; } }else{ ogg_uint16_t *out=(ogg_uint16_t *)s->dec_table; for(i=s->used_entries*2-4;i>=0;i-=2){ if(work[i]&0x80000000UL){ if(work[i+1]&0x80000000UL){ top-=4; out[top]=(work[i]>>16 & 0x7fff)|0x8000; out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000; out[top+2]=work[i] & 0xffff; out[top+3]=work[i+1] & 0xffff; }else{ top-=3; out[top]=(work[i]>>16 & 0x7fff)|0x8000; out[top+1]=work[work[i+1]*2]; out[top+2]=work[i] & 0xffff; } }else{ if(work[i+1]&0x80000000UL){ top-=3; out[top]=work[work[i]*2]; out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000; out[top+2]=work[i+1] & 0xffff; }else{ top-=2; out[top]=work[work[i]*2]; out[top+1]=work[work[i+1]*2]; } } work[i]=top; } } } free(work); return 0; error_out: free(work); return 1; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
static int _make_decode_table(codebook *s,char *lengthlist,long quantvals, oggpack_buffer *opb,int maptype){ int i; ogg_uint32_t *work; if (!lengthlist) return 1; if(s->dec_nodeb==4){ /* Over-allocate by using s->entries instead of used_entries. * This means that we can use s->entries to enforce size in * _make_words without messing up length list looping. * This probably wastes a bit of space, but it shouldn't * impact behavior or size too much. */ s->dec_table=_ogg_malloc((s->entries*2+1)*sizeof(*work)); if (!s->dec_table) return 1; /* +1 (rather than -2) is to accommodate 0 and 1 sized books, which are specialcased to nodeb==4 */ if(_make_words(lengthlist,s->entries, s->dec_table,quantvals,s,opb,maptype))return 1; return 0; } if (s->used_entries > INT_MAX/2 || s->used_entries*2 > INT_MAX/((long) sizeof(*work)) - 1) return 1; /* Overallocate as above */ work=calloc((s->entries*2+1),sizeof(*work)); if (!work) return 1; if(_make_words(lengthlist,s->entries,work,quantvals,s,opb,maptype)) goto error_out; if (s->used_entries > INT_MAX/(s->dec_leafw+1)) goto error_out; if (s->dec_nodeb && s->used_entries * (s->dec_leafw+1) > INT_MAX/s->dec_nodeb) goto error_out; s->dec_table=_ogg_malloc((s->used_entries*(s->dec_leafw+1)-2)* s->dec_nodeb); if (!s->dec_table) goto error_out; if(s->dec_leafw==1){ switch(s->dec_nodeb){ case 1: for(i=0;i<s->used_entries*2-2;i++) ((unsigned char *)s->dec_table)[i]=(unsigned char) (((work[i] & 0x80000000UL) >> 24) | work[i]); break; case 2: for(i=0;i<s->used_entries*2-2;i++) ((ogg_uint16_t *)s->dec_table)[i]=(ogg_uint16_t) (((work[i] & 0x80000000UL) >> 16) | work[i]); break; } }else{ /* more complex; we have to do a two-pass repack that updates the node indexing. */ long top=s->used_entries*3-2; if(s->dec_nodeb==1){ unsigned char *out=(unsigned char *)s->dec_table; for(i=s->used_entries*2-4;i>=0;i-=2){ if(work[i]&0x80000000UL){ if(work[i+1]&0x80000000UL){ top-=4; out[top]=(work[i]>>8 & 0x7f)|0x80; out[top+1]=(work[i+1]>>8 & 0x7f)|0x80; out[top+2]=work[i] & 0xff; out[top+3]=work[i+1] & 0xff; }else{ top-=3; out[top]=(work[i]>>8 & 0x7f)|0x80; out[top+1]=work[work[i+1]*2]; out[top+2]=work[i] & 0xff; } }else{ if(work[i+1]&0x80000000UL){ top-=3; out[top]=work[work[i]*2]; out[top+1]=(work[i+1]>>8 & 0x7f)|0x80; out[top+2]=work[i+1] & 0xff; }else{ top-=2; out[top]=work[work[i]*2]; out[top+1]=work[work[i+1]*2]; } } work[i]=top; } }else{ ogg_uint16_t *out=(ogg_uint16_t *)s->dec_table; for(i=s->used_entries*2-4;i>=0;i-=2){ if(work[i]&0x80000000UL){ if(work[i+1]&0x80000000UL){ top-=4; out[top]=(work[i]>>16 & 0x7fff)|0x8000; out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000; out[top+2]=work[i] & 0xffff; out[top+3]=work[i+1] & 0xffff; }else{ top-=3; out[top]=(work[i]>>16 & 0x7fff)|0x8000; out[top+1]=work[work[i+1]*2]; out[top+2]=work[i] & 0xffff; } }else{ if(work[i+1]&0x80000000UL){ top-=3; out[top]=work[work[i]*2]; out[top+1]=(work[i+1]>>16 & 0x7fff)|0x8000; out[top+2]=work[i+1] & 0xffff; }else{ top-=2; out[top]=work[work[i]*2]; out[top+1]=work[work[i+1]*2]; } } work[i]=top; } } } free(work); return 0; error_out: free(work); return 1; }
21,350
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); if (end < start) { return false; } addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; } Commit Message: Add error logging on invalid cmap - DO NOT MERGE This patch logs instances of fonts with invalid cmap tables. Bug: 25645298 Bug: 26413177 Change-Id: I183985e9784a97a2b4307a22e036382b1fc90e5e CWE ID: CWE-20
static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kNGroupsOffset = 12; const size_t kFirstGroupOffset = 16; const size_t kGroupSize = 12; const size_t kStartCharCodeOffset = 0; const size_t kEndCharCodeOffset = 4; const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow if (kFirstGroupOffset > size) { return false; } uint32_t nGroups = readU32(data, kNGroupsOffset); if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) { android_errorWriteLog(0x534e4554, "25645298"); return false; } for (uint32_t i = 0; i < nGroups; i++) { uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize; uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset); uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset); if (end < start) { android_errorWriteLog(0x534e4554, "26413177"); return false; } addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive } return true; }
64
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: const std::string& AppControllerImpl::MaybeGetAndroidPackageName( const std::string& app_id) { const auto& package_name_it = android_package_map_.find(app_id); if (package_name_it != android_package_map_.end()) { return package_name_it->second; } ArcAppListPrefs* arc_prefs_ = ArcAppListPrefs::Get(profile_); if (!arc_prefs_) { return base::EmptyString(); } std::unique_ptr<ArcAppListPrefs::AppInfo> arc_info = arc_prefs_->GetApp(app_id); if (!arc_info) { return base::EmptyString(); } android_package_map_[app_id] = arc_info->package_name; return android_package_map_[app_id]; } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <michaelpg@chromium.org> Commit-Queue: Lucas Tenório <ltenorio@chromium.org> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
const std::string& AppControllerImpl::MaybeGetAndroidPackageName( const std::string& AppControllerService::MaybeGetAndroidPackageName( const std::string& app_id) { const auto& package_name_it = android_package_map_.find(app_id); if (package_name_it != android_package_map_.end()) { return package_name_it->second; } ArcAppListPrefs* arc_prefs_ = ArcAppListPrefs::Get(profile_); if (!arc_prefs_) { return base::EmptyString(); } std::unique_ptr<ArcAppListPrefs::AppInfo> arc_info = arc_prefs_->GetApp(app_id); if (!arc_info) { return base::EmptyString(); } android_package_map_[app_id] = arc_info->package_name; return android_package_map_[app_id]; }
9,018
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire) { unsigned int section, name_len, x, errors, num_chunks; unsigned char buf[0x54], *chunk = NULL, *name, *p, *end; struct mschmd_file *fi, *link = NULL; off_t offset, length; int num_entries; /* initialise pointers */ chm->files = NULL; chm->sysfiles = NULL; chm->chunk_cache = NULL; chm->sec0.base.chm = chm; chm->sec0.base.id = 0; chm->sec1.base.chm = chm; chm->sec1.base.id = 1; chm->sec1.content = NULL; chm->sec1.control = NULL; chm->sec1.spaninfo = NULL; chm->sec1.rtable = NULL; /* read the first header */ if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) { return MSPACK_ERR_READ; } /* check ITSF signature */ if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) { return MSPACK_ERR_SIGNATURE; } /* check both header GUIDs */ if (memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) { D(("incorrect GUIDs")) return MSPACK_ERR_SIGNATURE; } chm->version = EndGetI32(&buf[chmhead_Version]); chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]); chm->language = EndGetI32(&buf[chmhead_LanguageID]); if (chm->version > 3) { sys->message(fh, "WARNING; CHM version > 3"); } /* read the header section table */ if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) { return MSPACK_ERR_READ; } /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files. * The offset will be corrected later, once HS1 is read. */ if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) || read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) || read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 0 */ if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 0 */ if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) { return MSPACK_ERR_READ; } if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 1 */ if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 1 */ if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) { return MSPACK_ERR_READ; } chm->dir_offset = sys->tell(fh); chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]); chm->density = EndGetI32(&buf[chmhs1_Density]); chm->depth = EndGetI32(&buf[chmhs1_Depth]); chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]); chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]); chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]); chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]); if (chm->version < 3) { /* versions before 3 don't have chmhst3_OffsetCS0 */ chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks); } /* check if content offset or file size is wrong */ if (chm->sec0.offset > chm->length) { D(("content section begins after file has ended")) return MSPACK_ERR_DATAFORMAT; } /* ensure there are chunks and that chunk size is * large enough for signature and num_entries */ if (chm->chunk_size < (pmgl_Entries + 2)) { D(("chunk size not large enough")) return MSPACK_ERR_DATAFORMAT; } if (chm->num_chunks == 0) { D(("no chunks")) return MSPACK_ERR_DATAFORMAT; } /* The chunk_cache data structure is not great; large values for num_chunks * or num_chunks*chunk_size can exhaust all memory. Until a better chunk * cache is implemented, put arbitrary limits on num_chunks and chunk size. */ if (chm->num_chunks > 100000) { D(("more than 100,000 chunks")) return MSPACK_ERR_DATAFORMAT; } if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) { D(("chunks larger than entire file")) return MSPACK_ERR_DATAFORMAT; } /* common sense checks on header section 1 fields */ if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) { sys->message(fh, "WARNING; chunk size is not a power of two"); } if (chm->first_pmgl != 0) { sys->message(fh, "WARNING; first PMGL chunk is not zero"); } if (chm->first_pmgl > chm->last_pmgl) { D(("first pmgl chunk is after last pmgl chunk")) return MSPACK_ERR_DATAFORMAT; } if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) { D(("index_root outside valid range")) return MSPACK_ERR_DATAFORMAT; } /* if we are doing a quick read, stop here! */ if (!entire) { return MSPACK_ERR_OK; } /* seek to the first PMGL chunk, and reduce the number of chunks to read */ if ((x = chm->first_pmgl) != 0) { if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) { return MSPACK_ERR_SEEK; } } num_chunks = chm->last_pmgl - x + 1; if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) { return MSPACK_ERR_NOMEMORY; } /* read and process all chunks from FirstPMGL to LastPMGL */ errors = 0; while (num_chunks--) { /* read next chunk */ if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) { sys->free(chunk); return MSPACK_ERR_READ; } /* process only directory (PMGL) chunks */ if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue; if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) { sys->message(fh, "WARNING; PMGL quickref area is too small"); } if (EndGetI32(&chunk[pmgl_QuickRefSize]) > ((int)chm->chunk_size - pmgl_Entries)) { sys->message(fh, "WARNING; PMGL quickref area is too large"); } p = &chunk[pmgl_Entries]; end = &chunk[chm->chunk_size - 2]; num_entries = EndGetI16(end); while (num_entries--) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; name = p; p += name_len; READ_ENCINT(section); READ_ENCINT(offset); READ_ENCINT(length); /* ignore blank or one-char (e.g. "/") filenames we'd return as blank */ if (name_len < 2 || !name[0] || !name[1]) continue; /* empty files and directory names are stored as a file entry at * offset 0 with length 0. We want to keep empty files, but not * directory names, which end with a "/" */ if ((offset == 0) && (length == 0)) { if ((name_len > 0) && (name[name_len-1] == '/')) continue; } if (section > 1) { sys->message(fh, "invalid section number '%u'.", section); continue; } if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) { sys->free(chunk); return MSPACK_ERR_NOMEMORY; } fi->next = NULL; fi->filename = (char *) &fi[1]; fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0) : (struct mschmd_section *) (&chm->sec1)); fi->offset = offset; fi->length = length; sys->copy(name, fi->filename, (size_t) name_len); fi->filename[name_len] = '\0'; if (name[0] == ':' && name[1] == ':') { /* system file */ if (memcmp(&name[2], &content_name[2], 31L) == 0) { if (memcmp(&name[33], &content_name[33], 8L) == 0) { chm->sec1.content = fi; } else if (memcmp(&name[33], &control_name[33], 11L) == 0) { chm->sec1.control = fi; } else if (memcmp(&name[33], &spaninfo_name[33], 8L) == 0) { chm->sec1.spaninfo = fi; } else if (memcmp(&name[33], &rtable_name[33], 72L) == 0) { chm->sec1.rtable = fi; } } fi->next = chm->sysfiles; chm->sysfiles = fi; } else { /* normal file */ if (link) link->next = fi; else chm->files = fi; link = fi; } } /* this is reached either when num_entries runs out, or if * reading data from the chunk reached a premature end of chunk */ chunk_end: if (num_entries >= 0) { D(("chunk ended before all entries could be read")) errors++; } } sys->free(chunk); return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK; } Commit Message: length checks when looking for control files CWE ID: CWE-119
static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire) { unsigned int section, name_len, x, errors, num_chunks; unsigned char buf[0x54], *chunk = NULL, *name, *p, *end; struct mschmd_file *fi, *link = NULL; off_t offset, length; int num_entries; /* initialise pointers */ chm->files = NULL; chm->sysfiles = NULL; chm->chunk_cache = NULL; chm->sec0.base.chm = chm; chm->sec0.base.id = 0; chm->sec1.base.chm = chm; chm->sec1.base.id = 1; chm->sec1.content = NULL; chm->sec1.control = NULL; chm->sec1.spaninfo = NULL; chm->sec1.rtable = NULL; /* read the first header */ if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) { return MSPACK_ERR_READ; } /* check ITSF signature */ if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) { return MSPACK_ERR_SIGNATURE; } /* check both header GUIDs */ if (memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) { D(("incorrect GUIDs")) return MSPACK_ERR_SIGNATURE; } chm->version = EndGetI32(&buf[chmhead_Version]); chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]); chm->language = EndGetI32(&buf[chmhead_LanguageID]); if (chm->version > 3) { sys->message(fh, "WARNING; CHM version > 3"); } /* read the header section table */ if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) { return MSPACK_ERR_READ; } /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files. * The offset will be corrected later, once HS1 is read. */ if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) || read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) || read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 0 */ if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 0 */ if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) { return MSPACK_ERR_READ; } if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 1 */ if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 1 */ if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) { return MSPACK_ERR_READ; } chm->dir_offset = sys->tell(fh); chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]); chm->density = EndGetI32(&buf[chmhs1_Density]); chm->depth = EndGetI32(&buf[chmhs1_Depth]); chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]); chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]); chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]); chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]); if (chm->version < 3) { /* versions before 3 don't have chmhst3_OffsetCS0 */ chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks); } /* check if content offset or file size is wrong */ if (chm->sec0.offset > chm->length) { D(("content section begins after file has ended")) return MSPACK_ERR_DATAFORMAT; } /* ensure there are chunks and that chunk size is * large enough for signature and num_entries */ if (chm->chunk_size < (pmgl_Entries + 2)) { D(("chunk size not large enough")) return MSPACK_ERR_DATAFORMAT; } if (chm->num_chunks == 0) { D(("no chunks")) return MSPACK_ERR_DATAFORMAT; } /* The chunk_cache data structure is not great; large values for num_chunks * or num_chunks*chunk_size can exhaust all memory. Until a better chunk * cache is implemented, put arbitrary limits on num_chunks and chunk size. */ if (chm->num_chunks > 100000) { D(("more than 100,000 chunks")) return MSPACK_ERR_DATAFORMAT; } if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) { D(("chunks larger than entire file")) return MSPACK_ERR_DATAFORMAT; } /* common sense checks on header section 1 fields */ if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) { sys->message(fh, "WARNING; chunk size is not a power of two"); } if (chm->first_pmgl != 0) { sys->message(fh, "WARNING; first PMGL chunk is not zero"); } if (chm->first_pmgl > chm->last_pmgl) { D(("first pmgl chunk is after last pmgl chunk")) return MSPACK_ERR_DATAFORMAT; } if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) { D(("index_root outside valid range")) return MSPACK_ERR_DATAFORMAT; } /* if we are doing a quick read, stop here! */ if (!entire) { return MSPACK_ERR_OK; } /* seek to the first PMGL chunk, and reduce the number of chunks to read */ if ((x = chm->first_pmgl) != 0) { if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) { return MSPACK_ERR_SEEK; } } num_chunks = chm->last_pmgl - x + 1; if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) { return MSPACK_ERR_NOMEMORY; } /* read and process all chunks from FirstPMGL to LastPMGL */ errors = 0; while (num_chunks--) { /* read next chunk */ if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) { sys->free(chunk); return MSPACK_ERR_READ; } /* process only directory (PMGL) chunks */ if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue; if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) { sys->message(fh, "WARNING; PMGL quickref area is too small"); } if (EndGetI32(&chunk[pmgl_QuickRefSize]) > ((int)chm->chunk_size - pmgl_Entries)) { sys->message(fh, "WARNING; PMGL quickref area is too large"); } p = &chunk[pmgl_Entries]; end = &chunk[chm->chunk_size - 2]; num_entries = EndGetI16(end); while (num_entries--) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; name = p; p += name_len; READ_ENCINT(section); READ_ENCINT(offset); READ_ENCINT(length); /* ignore blank or one-char (e.g. "/") filenames we'd return as blank */ if (name_len < 2 || !name[0] || !name[1]) continue; /* empty files and directory names are stored as a file entry at * offset 0 with length 0. We want to keep empty files, but not * directory names, which end with a "/" */ if ((offset == 0) && (length == 0)) { if ((name_len > 0) && (name[name_len-1] == '/')) continue; } if (section > 1) { sys->message(fh, "invalid section number '%u'.", section); continue; } if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) { sys->free(chunk); return MSPACK_ERR_NOMEMORY; } fi->next = NULL; fi->filename = (char *) &fi[1]; fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0) : (struct mschmd_section *) (&chm->sec1)); fi->offset = offset; fi->length = length; sys->copy(name, fi->filename, (size_t) name_len); fi->filename[name_len] = '\0'; if (name[0] == ':' && name[1] == ':') { /* system file */ if (name_len == 40 && memcmp(name, content_name, 40) == 0) { chm->sec1.content = fi; } else if (name_len == 44 && memcmp(name, control_name, 44) == 0) { chm->sec1.control = fi; } else if (name_len == 41 && memcmp(name, spaninfo_name, 41) == 0) { chm->sec1.spaninfo = fi; } else if (name_len == 105 && memcmp(name, rtable_name, 105) == 0) { chm->sec1.rtable = fi; } fi->next = chm->sysfiles; chm->sysfiles = fi; } else { /* normal file */ if (link) link->next = fi; else chm->files = fi; link = fi; } } /* this is reached either when num_entries runs out, or if * reading data from the chunk reached a premature end of chunk */ chunk_end: if (num_entries >= 0) { D(("chunk ended before all entries could be read")) errors++; } } sys->free(chunk); return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK; }
17,012
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len) { int rc = X86EMUL_CONTINUE; int mode = ctxt->mode; int def_op_bytes, def_ad_bytes, goffset, simd_prefix; bool op_prefix = false; bool has_seg_override = false; struct opcode opcode; ctxt->memop.type = OP_NONE; ctxt->memopp = NULL; ctxt->_eip = ctxt->eip; ctxt->fetch.ptr = ctxt->fetch.data; ctxt->fetch.end = ctxt->fetch.data + insn_len; ctxt->opcode_len = 1; if (insn_len > 0) memcpy(ctxt->fetch.data, insn, insn_len); else { rc = __do_insn_fetch_bytes(ctxt, 1); if (rc != X86EMUL_CONTINUE) return rc; } switch (mode) { case X86EMUL_MODE_REAL: case X86EMUL_MODE_VM86: case X86EMUL_MODE_PROT16: def_op_bytes = def_ad_bytes = 2; break; case X86EMUL_MODE_PROT32: def_op_bytes = def_ad_bytes = 4; break; #ifdef CONFIG_X86_64 case X86EMUL_MODE_PROT64: def_op_bytes = 4; def_ad_bytes = 8; break; #endif default: return EMULATION_FAILED; } ctxt->op_bytes = def_op_bytes; ctxt->ad_bytes = def_ad_bytes; /* Legacy prefixes. */ for (;;) { switch (ctxt->b = insn_fetch(u8, ctxt)) { case 0x66: /* operand-size override */ op_prefix = true; /* switch between 2/4 bytes */ ctxt->op_bytes = def_op_bytes ^ 6; break; case 0x67: /* address-size override */ if (mode == X86EMUL_MODE_PROT64) /* switch between 4/8 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 12; else /* switch between 2/4 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 6; break; case 0x26: /* ES override */ case 0x2e: /* CS override */ case 0x36: /* SS override */ case 0x3e: /* DS override */ has_seg_override = true; ctxt->seg_override = (ctxt->b >> 3) & 3; break; case 0x64: /* FS override */ case 0x65: /* GS override */ has_seg_override = true; ctxt->seg_override = ctxt->b & 7; break; case 0x40 ... 0x4f: /* REX */ if (mode != X86EMUL_MODE_PROT64) goto done_prefixes; ctxt->rex_prefix = ctxt->b; continue; case 0xf0: /* LOCK */ ctxt->lock_prefix = 1; break; case 0xf2: /* REPNE/REPNZ */ case 0xf3: /* REP/REPE/REPZ */ ctxt->rep_prefix = ctxt->b; break; default: goto done_prefixes; } /* Any legacy prefix after a REX prefix nullifies its effect. */ ctxt->rex_prefix = 0; } done_prefixes: /* REX prefix. */ if (ctxt->rex_prefix & 8) ctxt->op_bytes = 8; /* REX.W */ /* Opcode byte(s). */ opcode = opcode_table[ctxt->b]; /* Two-byte opcode? */ if (ctxt->b == 0x0f) { ctxt->opcode_len = 2; ctxt->b = insn_fetch(u8, ctxt); opcode = twobyte_table[ctxt->b]; /* 0F_38 opcode map */ if (ctxt->b == 0x38) { ctxt->opcode_len = 3; ctxt->b = insn_fetch(u8, ctxt); opcode = opcode_map_0f_38[ctxt->b]; } } ctxt->d = opcode.flags; if (ctxt->d & ModRM) ctxt->modrm = insn_fetch(u8, ctxt); /* vex-prefix instructions are not implemented */ if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) && (mode == X86EMUL_MODE_PROT64 || (mode >= X86EMUL_MODE_PROT16 && (ctxt->modrm & 0x80)))) { ctxt->d = NotImpl; } while (ctxt->d & GroupMask) { switch (ctxt->d & GroupMask) { case Group: goffset = (ctxt->modrm >> 3) & 7; opcode = opcode.u.group[goffset]; break; case GroupDual: goffset = (ctxt->modrm >> 3) & 7; if ((ctxt->modrm >> 6) == 3) opcode = opcode.u.gdual->mod3[goffset]; else opcode = opcode.u.gdual->mod012[goffset]; break; case RMExt: goffset = ctxt->modrm & 7; opcode = opcode.u.group[goffset]; break; case Prefix: if (ctxt->rep_prefix && op_prefix) return EMULATION_FAILED; simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix; switch (simd_prefix) { case 0x00: opcode = opcode.u.gprefix->pfx_no; break; case 0x66: opcode = opcode.u.gprefix->pfx_66; break; case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break; case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break; } break; case Escape: if (ctxt->modrm > 0xbf) opcode = opcode.u.esc->high[ctxt->modrm - 0xc0]; else opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7]; break; default: return EMULATION_FAILED; } ctxt->d &= ~(u64)GroupMask; ctxt->d |= opcode.flags; } /* Unrecognised? */ if (ctxt->d == 0) return EMULATION_FAILED; ctxt->execute = opcode.u.execute; if (unlikely(ctxt->ud) && likely(!(ctxt->d & EmulateOnUD))) return EMULATION_FAILED; if (unlikely(ctxt->d & (NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm))) { /* * These are copied unconditionally here, and checked unconditionally * in x86_emulate_insn. */ ctxt->check_perm = opcode.check_perm; ctxt->intercept = opcode.intercept; if (ctxt->d & NotImpl) return EMULATION_FAILED; if (mode == X86EMUL_MODE_PROT64 && (ctxt->d & Stack)) ctxt->op_bytes = 8; if (ctxt->d & Op3264) { if (mode == X86EMUL_MODE_PROT64) ctxt->op_bytes = 8; else ctxt->op_bytes = 4; } if (ctxt->d & Sse) ctxt->op_bytes = 16; else if (ctxt->d & Mmx) ctxt->op_bytes = 8; } /* ModRM and SIB bytes. */ if (ctxt->d & ModRM) { rc = decode_modrm(ctxt, &ctxt->memop); if (!has_seg_override) { has_seg_override = true; ctxt->seg_override = ctxt->modrm_seg; } } else if (ctxt->d & MemAbs) rc = decode_abs(ctxt, &ctxt->memop); if (rc != X86EMUL_CONTINUE) goto done; if (!has_seg_override) ctxt->seg_override = VCPU_SREG_DS; ctxt->memop.addr.mem.seg = ctxt->seg_override; /* * Decode and fetch the source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* * Decode and fetch the second source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* Decode and fetch the destination operand: register or memory. */ rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask); done: if (ctxt->rip_relative) ctxt->memopp->addr.mem.ea += ctxt->_eip; return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK; } Commit Message: KVM: emulate: avoid accessing NULL ctxt->memopp A failure to decode the instruction can cause a NULL pointer access. This is fixed simply by moving the "done" label as close as possible to the return. This fixes CVE-2014-8481. Reported-by: Andy Lutomirski <luto@amacapital.net> Cc: stable@vger.kernel.org Fixes: 41061cdb98a0bec464278b4db8e894a3121671f5 Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-399
int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len) { int rc = X86EMUL_CONTINUE; int mode = ctxt->mode; int def_op_bytes, def_ad_bytes, goffset, simd_prefix; bool op_prefix = false; bool has_seg_override = false; struct opcode opcode; ctxt->memop.type = OP_NONE; ctxt->memopp = NULL; ctxt->_eip = ctxt->eip; ctxt->fetch.ptr = ctxt->fetch.data; ctxt->fetch.end = ctxt->fetch.data + insn_len; ctxt->opcode_len = 1; if (insn_len > 0) memcpy(ctxt->fetch.data, insn, insn_len); else { rc = __do_insn_fetch_bytes(ctxt, 1); if (rc != X86EMUL_CONTINUE) return rc; } switch (mode) { case X86EMUL_MODE_REAL: case X86EMUL_MODE_VM86: case X86EMUL_MODE_PROT16: def_op_bytes = def_ad_bytes = 2; break; case X86EMUL_MODE_PROT32: def_op_bytes = def_ad_bytes = 4; break; #ifdef CONFIG_X86_64 case X86EMUL_MODE_PROT64: def_op_bytes = 4; def_ad_bytes = 8; break; #endif default: return EMULATION_FAILED; } ctxt->op_bytes = def_op_bytes; ctxt->ad_bytes = def_ad_bytes; /* Legacy prefixes. */ for (;;) { switch (ctxt->b = insn_fetch(u8, ctxt)) { case 0x66: /* operand-size override */ op_prefix = true; /* switch between 2/4 bytes */ ctxt->op_bytes = def_op_bytes ^ 6; break; case 0x67: /* address-size override */ if (mode == X86EMUL_MODE_PROT64) /* switch between 4/8 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 12; else /* switch between 2/4 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 6; break; case 0x26: /* ES override */ case 0x2e: /* CS override */ case 0x36: /* SS override */ case 0x3e: /* DS override */ has_seg_override = true; ctxt->seg_override = (ctxt->b >> 3) & 3; break; case 0x64: /* FS override */ case 0x65: /* GS override */ has_seg_override = true; ctxt->seg_override = ctxt->b & 7; break; case 0x40 ... 0x4f: /* REX */ if (mode != X86EMUL_MODE_PROT64) goto done_prefixes; ctxt->rex_prefix = ctxt->b; continue; case 0xf0: /* LOCK */ ctxt->lock_prefix = 1; break; case 0xf2: /* REPNE/REPNZ */ case 0xf3: /* REP/REPE/REPZ */ ctxt->rep_prefix = ctxt->b; break; default: goto done_prefixes; } /* Any legacy prefix after a REX prefix nullifies its effect. */ ctxt->rex_prefix = 0; } done_prefixes: /* REX prefix. */ if (ctxt->rex_prefix & 8) ctxt->op_bytes = 8; /* REX.W */ /* Opcode byte(s). */ opcode = opcode_table[ctxt->b]; /* Two-byte opcode? */ if (ctxt->b == 0x0f) { ctxt->opcode_len = 2; ctxt->b = insn_fetch(u8, ctxt); opcode = twobyte_table[ctxt->b]; /* 0F_38 opcode map */ if (ctxt->b == 0x38) { ctxt->opcode_len = 3; ctxt->b = insn_fetch(u8, ctxt); opcode = opcode_map_0f_38[ctxt->b]; } } ctxt->d = opcode.flags; if (ctxt->d & ModRM) ctxt->modrm = insn_fetch(u8, ctxt); /* vex-prefix instructions are not implemented */ if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) && (mode == X86EMUL_MODE_PROT64 || (mode >= X86EMUL_MODE_PROT16 && (ctxt->modrm & 0x80)))) { ctxt->d = NotImpl; } while (ctxt->d & GroupMask) { switch (ctxt->d & GroupMask) { case Group: goffset = (ctxt->modrm >> 3) & 7; opcode = opcode.u.group[goffset]; break; case GroupDual: goffset = (ctxt->modrm >> 3) & 7; if ((ctxt->modrm >> 6) == 3) opcode = opcode.u.gdual->mod3[goffset]; else opcode = opcode.u.gdual->mod012[goffset]; break; case RMExt: goffset = ctxt->modrm & 7; opcode = opcode.u.group[goffset]; break; case Prefix: if (ctxt->rep_prefix && op_prefix) return EMULATION_FAILED; simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix; switch (simd_prefix) { case 0x00: opcode = opcode.u.gprefix->pfx_no; break; case 0x66: opcode = opcode.u.gprefix->pfx_66; break; case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break; case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break; } break; case Escape: if (ctxt->modrm > 0xbf) opcode = opcode.u.esc->high[ctxt->modrm - 0xc0]; else opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7]; break; default: return EMULATION_FAILED; } ctxt->d &= ~(u64)GroupMask; ctxt->d |= opcode.flags; } /* Unrecognised? */ if (ctxt->d == 0) return EMULATION_FAILED; ctxt->execute = opcode.u.execute; if (unlikely(ctxt->ud) && likely(!(ctxt->d & EmulateOnUD))) return EMULATION_FAILED; if (unlikely(ctxt->d & (NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm))) { /* * These are copied unconditionally here, and checked unconditionally * in x86_emulate_insn. */ ctxt->check_perm = opcode.check_perm; ctxt->intercept = opcode.intercept; if (ctxt->d & NotImpl) return EMULATION_FAILED; if (mode == X86EMUL_MODE_PROT64 && (ctxt->d & Stack)) ctxt->op_bytes = 8; if (ctxt->d & Op3264) { if (mode == X86EMUL_MODE_PROT64) ctxt->op_bytes = 8; else ctxt->op_bytes = 4; } if (ctxt->d & Sse) ctxt->op_bytes = 16; else if (ctxt->d & Mmx) ctxt->op_bytes = 8; } /* ModRM and SIB bytes. */ if (ctxt->d & ModRM) { rc = decode_modrm(ctxt, &ctxt->memop); if (!has_seg_override) { has_seg_override = true; ctxt->seg_override = ctxt->modrm_seg; } } else if (ctxt->d & MemAbs) rc = decode_abs(ctxt, &ctxt->memop); if (rc != X86EMUL_CONTINUE) goto done; if (!has_seg_override) ctxt->seg_override = VCPU_SREG_DS; ctxt->memop.addr.mem.seg = ctxt->seg_override; /* * Decode and fetch the source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* * Decode and fetch the second source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* Decode and fetch the destination operand: register or memory. */ rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask); if (ctxt->rip_relative) ctxt->memopp->addr.mem.ea += ctxt->_eip; done: return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK; }
16,533
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void GpuDataManager::UpdateGpuFeatureFlags() { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &GpuDataManager::UpdateGpuFeatureFlags)); return; } GpuBlacklist* gpu_blacklist = GetGpuBlacklist(); if (gpu_blacklist == NULL) return; if (!gpu_blacklist) { gpu_feature_flags_.set_flags(0); return; } { base::AutoLock auto_lock(gpu_info_lock_); gpu_feature_flags_ = gpu_blacklist->DetermineGpuFeatureFlags( GpuBlacklist::kOsAny, NULL, gpu_info_); } uint32 max_entry_id = gpu_blacklist->max_entry_id(); if (!gpu_feature_flags_.flags()) { UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry", 0, max_entry_id + 1); return; } RunGpuInfoUpdateCallbacks(); std::vector<uint32> flag_entries; gpu_blacklist->GetGpuFeatureFlagEntries( GpuFeatureFlags::kGpuFeatureAll, flag_entries); DCHECK_GT(flag_entries.size(), 0u); for (size_t i = 0; i < flag_entries.size(); ++i) { UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry", flag_entries[i], max_entry_id + 1); } } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void GpuDataManager::UpdateGpuFeatureFlags() { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &GpuDataManager::UpdateGpuFeatureFlags)); return; } GpuBlacklist* gpu_blacklist = GetGpuBlacklist(); if (!gpu_blacklist) { gpu_feature_flags_.set_flags(0); return; } { base::AutoLock auto_lock(gpu_info_lock_); gpu_feature_flags_ = gpu_blacklist->DetermineGpuFeatureFlags( GpuBlacklist::kOsAny, NULL, gpu_info_); } uint32 max_entry_id = gpu_blacklist->max_entry_id(); if (!gpu_feature_flags_.flags()) { UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry", 0, max_entry_id + 1); return; } RunGpuInfoUpdateCallbacks(); std::vector<uint32> flag_entries; gpu_blacklist->GetGpuFeatureFlagEntries( GpuFeatureFlags::kGpuFeatureAll, flag_entries); DCHECK_GT(flag_entries.size(), 0u); for (size_t i = 0; i < flag_entries.size(); ++i) { UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry", flag_entries[i], max_entry_id + 1); } }
10,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void xacct_add_tsk(struct taskstats *stats, struct task_struct *p) { /* convert pages-jiffies to Mbyte-usec */ stats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB; stats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB; if (p->mm) { /* adjust to KB unit */ stats->hiwater_rss = p->mm->hiwater_rss * PAGE_SIZE / KB; stats->hiwater_vm = p->mm->hiwater_vm * PAGE_SIZE / KB; } stats->read_char = p->rchar; stats->write_char = p->wchar; stats->read_syscalls = p->syscr; stats->write_syscalls = p->syscw; } Commit Message: [PATCH] xacct_add_tsk: fix pure theoretical ->mm use-after-free Paranoid fix. The task can free its ->mm after the 'if (p->mm)' check. Signed-off-by: Oleg Nesterov <oleg@tv-sign.ru> Cc: Shailabh Nagar <nagar@watson.ibm.com> Cc: Balbir Singh <balbir@in.ibm.com> Cc: Jay Lan <jlan@sgi.com> Signed-off-by: Andrew Morton <akpm@osdl.org> Signed-off-by: Linus Torvalds <torvalds@osdl.org> CWE ID: CWE-399
void xacct_add_tsk(struct taskstats *stats, struct task_struct *p) { struct mm_struct *mm; /* convert pages-jiffies to Mbyte-usec */ stats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB; stats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB; mm = get_task_mm(p); if (mm) { /* adjust to KB unit */ stats->hiwater_rss = mm->hiwater_rss * PAGE_SIZE / KB; stats->hiwater_vm = mm->hiwater_vm * PAGE_SIZE / KB; mmput(mm); } stats->read_char = p->rchar; stats->write_char = p->wchar; stats->read_syscalls = p->syscr; stats->write_syscalls = p->syscw; }
29,655
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void PrintWebViewHelper::PrintNode(const WebKit::WebNode& node) { if (node.isNull() || !node.document().frame()) { return; } if (is_preview_enabled_) { print_preview_context_.InitWithNode(node); RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE); } else { WebKit::WebNode duplicate_node(node); Print(duplicate_node.document().frame(), duplicate_node); } } Commit Message: Guard against the same PrintWebViewHelper being re-entered. BUG=159165 Review URL: https://chromiumcodereview.appspot.com/11367076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PrintWebViewHelper::PrintNode(const WebKit::WebNode& node) { if (node.isNull() || !node.document().frame()) { return; } if (print_node_in_progress_) { // This can happen as a result of processing sync messages when printing // from ppapi plugins. It's a rare case, so its OK to just fail here. // See http://crbug.com/159165. return; } print_node_in_progress_ = true; if (is_preview_enabled_) { print_preview_context_.InitWithNode(node); RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE); } else { WebKit::WebNode duplicate_node(node); Print(duplicate_node.document().frame(), duplicate_node); } print_node_in_progress_ = false; }
20,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: AppControllerImpl::~AppControllerImpl() { if (apps::AppServiceProxy::Get(profile_)) app_service_proxy_->AppRegistryCache().RemoveObserver(this); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <michaelpg@chromium.org> Commit-Queue: Lucas Tenório <ltenorio@chromium.org> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
AppControllerImpl::~AppControllerImpl() { AppControllerService::~AppControllerService() { app_service_proxy_->AppRegistryCache().RemoveObserver(this); }
23,278
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool ChildProcessSecurityPolicyImpl::CanCommitURL(int child_id, const GURL& url) { if (!url.is_valid()) return false; // Can't commit invalid URLs. const std::string& scheme = url.scheme(); if (IsPseudoScheme(scheme)) return url == url::kAboutBlankURL || url == kAboutSrcDocURL; if (url.SchemeIsBlob() || url.SchemeIsFileSystem()) { if (IsMalformedBlobUrl(url)) return false; url::Origin origin = url::Origin::Create(url); return origin.unique() || CanCommitURL(child_id, GURL(origin.Serialize())); } { base::AutoLock lock(lock_); if (base::ContainsKey(schemes_okay_to_commit_in_any_process_, scheme)) return true; SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; return state->second->CanCommitURL(url); } } Commit Message: Lock down blob/filesystem URL creation with a stronger CPSP::CanCommitURL() ChildProcessSecurityPolicy::CanCommitURL() is a security check that's supposed to tell whether a given renderer process is allowed to commit a given URL. It is currently used to validate (1) blob and filesystem URL creation, and (2) Origin headers. Currently, it has scheme-based checks that disallow things like web renderers creating blob/filesystem URLs in chrome-extension: origins, but it cannot stop one web origin from creating those URLs for another origin. This CL locks down its use for (1) to also consult CanAccessDataForOrigin(). With site isolation, this will check origin locks and ensure that foo.com cannot create blob/filesystem URLs for other origins. For now, this CL does not provide the same enforcements for (2), Origin header validation, which has additional constraints that need to be solved first (see https://crbug.com/515309). Bug: 886976, 888001 Change-Id: I743ef05469e4000b2c0bee840022162600cc237f Reviewed-on: https://chromium-review.googlesource.com/1235343 Commit-Queue: Alex Moshchuk <alexmos@chromium.org> Reviewed-by: Charlie Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#594914} CWE ID:
bool ChildProcessSecurityPolicyImpl::CanCommitURL(int child_id, const GURL& url, bool check_origin_locks) { if (!url.is_valid()) return false; // Can't commit invalid URLs. const std::string& scheme = url.scheme(); if (IsPseudoScheme(scheme)) return url == url::kAboutBlankURL || url == kAboutSrcDocURL; if (url.SchemeIsBlob() || url.SchemeIsFileSystem()) { if (IsMalformedBlobUrl(url)) return false; url::Origin origin = url::Origin::Create(url); return origin.unique() || CanCommitURL(child_id, GURL(origin.Serialize()), check_origin_locks); } // With site isolation, a URL from a site may only be committed in a process // dedicated to that site. This check will ensure that |url| can't commit if // the process is locked to a different site. Note that this check is only // effective for processes that are locked to a site, but even with strict // site isolation, currently not all processes are locked (e.g., extensions // or <webview> tags - see ShouldLockToOrigin()). if (check_origin_locks && !CanAccessDataForOrigin(child_id, url)) return false; { base::AutoLock lock(lock_); // TODO(creis, nick): https://crbug.com/515309: The line below does not if (base::ContainsKey(schemes_okay_to_commit_in_any_process_, scheme)) return true; SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; return state->second->CanCommitURL(url); } }
6,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int do_ipv6_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { struct ipv6_pinfo *np = inet6_sk(sk); struct net *net = sock_net(sk); int val, valbool; int retv = -ENOPROTOOPT; bool needs_rtnl = setsockopt_needs_rtnl(optname); if (!optval) val = 0; else { if (optlen >= sizeof(int)) { if (get_user(val, (int __user *) optval)) return -EFAULT; } else val = 0; } valbool = (val != 0); if (ip6_mroute_opt(optname)) return ip6_mroute_setsockopt(sk, optname, optval, optlen); if (needs_rtnl) rtnl_lock(); lock_sock(sk); switch (optname) { case IPV6_ADDRFORM: if (optlen < sizeof(int)) goto e_inval; if (val == PF_INET) { struct ipv6_txoptions *opt; struct sk_buff *pktopt; if (sk->sk_type == SOCK_RAW) break; if (sk->sk_protocol == IPPROTO_UDP || sk->sk_protocol == IPPROTO_UDPLITE) { struct udp_sock *up = udp_sk(sk); if (up->pending == AF_INET6) { retv = -EBUSY; break; } } else if (sk->sk_protocol != IPPROTO_TCP) break; if (sk->sk_state != TCP_ESTABLISHED) { retv = -ENOTCONN; break; } if (ipv6_only_sock(sk) || !ipv6_addr_v4mapped(&sk->sk_v6_daddr)) { retv = -EADDRNOTAVAIL; break; } fl6_free_socklist(sk); ipv6_sock_mc_close(sk); /* * Sock is moving from IPv6 to IPv4 (sk_prot), so * remove it from the refcnt debug socks count in the * original family... */ sk_refcnt_debug_dec(sk); if (sk->sk_protocol == IPPROTO_TCP) { struct inet_connection_sock *icsk = inet_csk(sk); local_bh_disable(); sock_prot_inuse_add(net, sk->sk_prot, -1); sock_prot_inuse_add(net, &tcp_prot, 1); local_bh_enable(); sk->sk_prot = &tcp_prot; icsk->icsk_af_ops = &ipv4_specific; sk->sk_socket->ops = &inet_stream_ops; sk->sk_family = PF_INET; tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); } else { struct proto *prot = &udp_prot; if (sk->sk_protocol == IPPROTO_UDPLITE) prot = &udplite_prot; local_bh_disable(); sock_prot_inuse_add(net, sk->sk_prot, -1); sock_prot_inuse_add(net, prot, 1); local_bh_enable(); sk->sk_prot = prot; sk->sk_socket->ops = &inet_dgram_ops; sk->sk_family = PF_INET; } opt = xchg(&np->opt, NULL); if (opt) sock_kfree_s(sk, opt, opt->tot_len); pktopt = xchg(&np->pktoptions, NULL); kfree_skb(pktopt); sk->sk_destruct = inet_sock_destruct; /* * ... and add it to the refcnt debug socks count * in the new family. -acme */ sk_refcnt_debug_inc(sk); module_put(THIS_MODULE); retv = 0; break; } goto e_inval; case IPV6_V6ONLY: if (optlen < sizeof(int) || inet_sk(sk)->inet_num) goto e_inval; sk->sk_ipv6only = valbool; retv = 0; break; case IPV6_RECVPKTINFO: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxinfo = valbool; retv = 0; break; case IPV6_2292PKTINFO: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxoinfo = valbool; retv = 0; break; case IPV6_RECVHOPLIMIT: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxhlim = valbool; retv = 0; break; case IPV6_2292HOPLIMIT: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxohlim = valbool; retv = 0; break; case IPV6_RECVRTHDR: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.srcrt = valbool; retv = 0; break; case IPV6_2292RTHDR: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.osrcrt = valbool; retv = 0; break; case IPV6_RECVHOPOPTS: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.hopopts = valbool; retv = 0; break; case IPV6_2292HOPOPTS: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.ohopopts = valbool; retv = 0; break; case IPV6_RECVDSTOPTS: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.dstopts = valbool; retv = 0; break; case IPV6_2292DSTOPTS: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.odstopts = valbool; retv = 0; break; case IPV6_TCLASS: if (optlen < sizeof(int)) goto e_inval; if (val < -1 || val > 0xff) goto e_inval; /* RFC 3542, 6.5: default traffic class of 0x0 */ if (val == -1) val = 0; np->tclass = val; retv = 0; break; case IPV6_RECVTCLASS: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxtclass = valbool; retv = 0; break; case IPV6_FLOWINFO: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxflow = valbool; retv = 0; break; case IPV6_RECVPATHMTU: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxpmtu = valbool; retv = 0; break; case IPV6_TRANSPARENT: if (valbool && !ns_capable(net->user_ns, CAP_NET_ADMIN) && !ns_capable(net->user_ns, CAP_NET_RAW)) { retv = -EPERM; break; } if (optlen < sizeof(int)) goto e_inval; /* we don't have a separate transparent bit for IPV6 we use the one in the IPv4 socket */ inet_sk(sk)->transparent = valbool; retv = 0; break; case IPV6_RECVORIGDSTADDR: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxorigdstaddr = valbool; retv = 0; break; case IPV6_HOPOPTS: case IPV6_RTHDRDSTOPTS: case IPV6_RTHDR: case IPV6_DSTOPTS: { struct ipv6_txoptions *opt; /* remove any sticky options header with a zero option * length, per RFC3542. */ if (optlen == 0) optval = NULL; else if (!optval) goto e_inval; else if (optlen < sizeof(struct ipv6_opt_hdr) || optlen & 0x7 || optlen > 8 * 255) goto e_inval; /* hop-by-hop / destination options are privileged option */ retv = -EPERM; if (optname != IPV6_RTHDR && !ns_capable(net->user_ns, CAP_NET_RAW)) break; opt = ipv6_renew_options(sk, np->opt, optname, (struct ipv6_opt_hdr __user *)optval, optlen); if (IS_ERR(opt)) { retv = PTR_ERR(opt); break; } /* routing header option needs extra check */ retv = -EINVAL; if (optname == IPV6_RTHDR && opt && opt->srcrt) { struct ipv6_rt_hdr *rthdr = opt->srcrt; switch (rthdr->type) { #if IS_ENABLED(CONFIG_IPV6_MIP6) case IPV6_SRCRT_TYPE_2: if (rthdr->hdrlen != 2 || rthdr->segments_left != 1) goto sticky_done; break; #endif default: goto sticky_done; } } retv = 0; opt = ipv6_update_options(sk, opt); sticky_done: if (opt) sock_kfree_s(sk, opt, opt->tot_len); break; } case IPV6_PKTINFO: { struct in6_pktinfo pkt; if (optlen == 0) goto e_inval; else if (optlen < sizeof(struct in6_pktinfo) || !optval) goto e_inval; if (copy_from_user(&pkt, optval, sizeof(struct in6_pktinfo))) { retv = -EFAULT; break; } if (sk->sk_bound_dev_if && pkt.ipi6_ifindex != sk->sk_bound_dev_if) goto e_inval; np->sticky_pktinfo.ipi6_ifindex = pkt.ipi6_ifindex; np->sticky_pktinfo.ipi6_addr = pkt.ipi6_addr; retv = 0; break; } case IPV6_2292PKTOPTIONS: { struct ipv6_txoptions *opt = NULL; struct msghdr msg; struct flowi6 fl6; int junk; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; if (optlen == 0) goto update; /* 1K is probably excessive * 1K is surely not enough, 2K per standard header is 16K. */ retv = -EINVAL; if (optlen > 64*1024) break; opt = sock_kmalloc(sk, sizeof(*opt) + optlen, GFP_KERNEL); retv = -ENOBUFS; if (!opt) break; memset(opt, 0, sizeof(*opt)); opt->tot_len = sizeof(*opt) + optlen; retv = -EFAULT; if (copy_from_user(opt+1, optval, optlen)) goto done; msg.msg_controllen = optlen; msg.msg_control = (void *)(opt+1); retv = ip6_datagram_send_ctl(net, sk, &msg, &fl6, opt, &junk, &junk, &junk); if (retv) goto done; update: retv = 0; opt = ipv6_update_options(sk, opt); done: if (opt) sock_kfree_s(sk, opt, opt->tot_len); break; } case IPV6_UNICAST_HOPS: if (optlen < sizeof(int)) goto e_inval; if (val > 255 || val < -1) goto e_inval; np->hop_limit = val; retv = 0; break; case IPV6_MULTICAST_HOPS: if (sk->sk_type == SOCK_STREAM) break; if (optlen < sizeof(int)) goto e_inval; if (val > 255 || val < -1) goto e_inval; np->mcast_hops = (val == -1 ? IPV6_DEFAULT_MCASTHOPS : val); retv = 0; break; case IPV6_MULTICAST_LOOP: if (optlen < sizeof(int)) goto e_inval; if (val != valbool) goto e_inval; np->mc_loop = valbool; retv = 0; break; case IPV6_UNICAST_IF: { struct net_device *dev = NULL; int ifindex; if (optlen != sizeof(int)) goto e_inval; ifindex = (__force int)ntohl((__force __be32)val); if (ifindex == 0) { np->ucast_oif = 0; retv = 0; break; } dev = dev_get_by_index(net, ifindex); retv = -EADDRNOTAVAIL; if (!dev) break; dev_put(dev); retv = -EINVAL; if (sk->sk_bound_dev_if) break; np->ucast_oif = ifindex; retv = 0; break; } case IPV6_MULTICAST_IF: if (sk->sk_type == SOCK_STREAM) break; if (optlen < sizeof(int)) goto e_inval; if (val) { struct net_device *dev; if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != val) goto e_inval; dev = dev_get_by_index(net, val); if (!dev) { retv = -ENODEV; break; } dev_put(dev); } np->mcast_oif = val; retv = 0; break; case IPV6_ADD_MEMBERSHIP: case IPV6_DROP_MEMBERSHIP: { struct ipv6_mreq mreq; if (optlen < sizeof(struct ipv6_mreq)) goto e_inval; retv = -EPROTO; if (inet_sk(sk)->is_icsk) break; retv = -EFAULT; if (copy_from_user(&mreq, optval, sizeof(struct ipv6_mreq))) break; if (optname == IPV6_ADD_MEMBERSHIP) retv = ipv6_sock_mc_join(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_multiaddr); else retv = ipv6_sock_mc_drop(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_multiaddr); break; } case IPV6_JOIN_ANYCAST: case IPV6_LEAVE_ANYCAST: { struct ipv6_mreq mreq; if (optlen < sizeof(struct ipv6_mreq)) goto e_inval; retv = -EFAULT; if (copy_from_user(&mreq, optval, sizeof(struct ipv6_mreq))) break; if (optname == IPV6_JOIN_ANYCAST) retv = ipv6_sock_ac_join(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_acaddr); else retv = ipv6_sock_ac_drop(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_acaddr); break; } case MCAST_JOIN_GROUP: case MCAST_LEAVE_GROUP: { struct group_req greq; struct sockaddr_in6 *psin6; if (optlen < sizeof(struct group_req)) goto e_inval; retv = -EFAULT; if (copy_from_user(&greq, optval, sizeof(struct group_req))) break; if (greq.gr_group.ss_family != AF_INET6) { retv = -EADDRNOTAVAIL; break; } psin6 = (struct sockaddr_in6 *)&greq.gr_group; if (optname == MCAST_JOIN_GROUP) retv = ipv6_sock_mc_join(sk, greq.gr_interface, &psin6->sin6_addr); else retv = ipv6_sock_mc_drop(sk, greq.gr_interface, &psin6->sin6_addr); break; } case MCAST_JOIN_SOURCE_GROUP: case MCAST_LEAVE_SOURCE_GROUP: case MCAST_BLOCK_SOURCE: case MCAST_UNBLOCK_SOURCE: { struct group_source_req greqs; int omode, add; if (optlen < sizeof(struct group_source_req)) goto e_inval; if (copy_from_user(&greqs, optval, sizeof(greqs))) { retv = -EFAULT; break; } if (greqs.gsr_group.ss_family != AF_INET6 || greqs.gsr_source.ss_family != AF_INET6) { retv = -EADDRNOTAVAIL; break; } if (optname == MCAST_BLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 1; } else if (optname == MCAST_UNBLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 0; } else if (optname == MCAST_JOIN_SOURCE_GROUP) { struct sockaddr_in6 *psin6; psin6 = (struct sockaddr_in6 *)&greqs.gsr_group; retv = ipv6_sock_mc_join(sk, greqs.gsr_interface, &psin6->sin6_addr); /* prior join w/ different source is ok */ if (retv && retv != -EADDRINUSE) break; omode = MCAST_INCLUDE; add = 1; } else /* MCAST_LEAVE_SOURCE_GROUP */ { omode = MCAST_INCLUDE; add = 0; } retv = ip6_mc_source(add, omode, sk, &greqs); break; } case MCAST_MSFILTER: { struct group_filter *gsf; if (optlen < GROUP_FILTER_SIZE(0)) goto e_inval; if (optlen > sysctl_optmem_max) { retv = -ENOBUFS; break; } gsf = kmalloc(optlen, GFP_KERNEL); if (!gsf) { retv = -ENOBUFS; break; } retv = -EFAULT; if (copy_from_user(gsf, optval, optlen)) { kfree(gsf); break; } /* numsrc >= (4G-140)/128 overflow in 32 bits */ if (gsf->gf_numsrc >= 0x1ffffffU || gsf->gf_numsrc > sysctl_mld_max_msf) { kfree(gsf); retv = -ENOBUFS; break; } if (GROUP_FILTER_SIZE(gsf->gf_numsrc) > optlen) { kfree(gsf); retv = -EINVAL; break; } retv = ip6_mc_msfilter(sk, gsf); kfree(gsf); break; } case IPV6_ROUTER_ALERT: if (optlen < sizeof(int)) goto e_inval; retv = ip6_ra_control(sk, val); break; case IPV6_MTU_DISCOVER: if (optlen < sizeof(int)) goto e_inval; if (val < IPV6_PMTUDISC_DONT || val > IPV6_PMTUDISC_OMIT) goto e_inval; np->pmtudisc = val; retv = 0; break; case IPV6_MTU: if (optlen < sizeof(int)) goto e_inval; if (val && val < IPV6_MIN_MTU) goto e_inval; np->frag_size = val; retv = 0; break; case IPV6_RECVERR: if (optlen < sizeof(int)) goto e_inval; np->recverr = valbool; if (!val) skb_queue_purge(&sk->sk_error_queue); retv = 0; break; case IPV6_FLOWINFO_SEND: if (optlen < sizeof(int)) goto e_inval; np->sndflow = valbool; retv = 0; break; case IPV6_FLOWLABEL_MGR: retv = ipv6_flowlabel_opt(sk, optval, optlen); break; case IPV6_IPSEC_POLICY: case IPV6_XFRM_POLICY: retv = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) break; retv = xfrm_user_policy(sk, optname, optval, optlen); break; case IPV6_ADDR_PREFERENCES: { unsigned int pref = 0; unsigned int prefmask = ~0; if (optlen < sizeof(int)) goto e_inval; retv = -EINVAL; /* check PUBLIC/TMP/PUBTMP_DEFAULT conflicts */ switch (val & (IPV6_PREFER_SRC_PUBLIC| IPV6_PREFER_SRC_TMP| IPV6_PREFER_SRC_PUBTMP_DEFAULT)) { case IPV6_PREFER_SRC_PUBLIC: pref |= IPV6_PREFER_SRC_PUBLIC; break; case IPV6_PREFER_SRC_TMP: pref |= IPV6_PREFER_SRC_TMP; break; case IPV6_PREFER_SRC_PUBTMP_DEFAULT: break; case 0: goto pref_skip_pubtmp; default: goto e_inval; } prefmask &= ~(IPV6_PREFER_SRC_PUBLIC| IPV6_PREFER_SRC_TMP); pref_skip_pubtmp: /* check HOME/COA conflicts */ switch (val & (IPV6_PREFER_SRC_HOME|IPV6_PREFER_SRC_COA)) { case IPV6_PREFER_SRC_HOME: break; case IPV6_PREFER_SRC_COA: pref |= IPV6_PREFER_SRC_COA; case 0: goto pref_skip_coa; default: goto e_inval; } prefmask &= ~IPV6_PREFER_SRC_COA; pref_skip_coa: /* check CGA/NONCGA conflicts */ switch (val & (IPV6_PREFER_SRC_CGA|IPV6_PREFER_SRC_NONCGA)) { case IPV6_PREFER_SRC_CGA: case IPV6_PREFER_SRC_NONCGA: case 0: break; default: goto e_inval; } np->srcprefs = (np->srcprefs & prefmask) | pref; retv = 0; break; } case IPV6_MINHOPCOUNT: if (optlen < sizeof(int)) goto e_inval; if (val < 0 || val > 255) goto e_inval; np->min_hopcount = val; retv = 0; break; case IPV6_DONTFRAG: np->dontfrag = valbool; retv = 0; break; case IPV6_AUTOFLOWLABEL: np->autoflowlabel = valbool; retv = 0; break; } release_sock(sk); if (needs_rtnl) rtnl_unlock(); return retv; e_inval: release_sock(sk); if (needs_rtnl) rtnl_unlock(); return -EINVAL; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
static int do_ipv6_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { struct ipv6_pinfo *np = inet6_sk(sk); struct net *net = sock_net(sk); int val, valbool; int retv = -ENOPROTOOPT; bool needs_rtnl = setsockopt_needs_rtnl(optname); if (!optval) val = 0; else { if (optlen >= sizeof(int)) { if (get_user(val, (int __user *) optval)) return -EFAULT; } else val = 0; } valbool = (val != 0); if (ip6_mroute_opt(optname)) return ip6_mroute_setsockopt(sk, optname, optval, optlen); if (needs_rtnl) rtnl_lock(); lock_sock(sk); switch (optname) { case IPV6_ADDRFORM: if (optlen < sizeof(int)) goto e_inval; if (val == PF_INET) { struct ipv6_txoptions *opt; struct sk_buff *pktopt; if (sk->sk_type == SOCK_RAW) break; if (sk->sk_protocol == IPPROTO_UDP || sk->sk_protocol == IPPROTO_UDPLITE) { struct udp_sock *up = udp_sk(sk); if (up->pending == AF_INET6) { retv = -EBUSY; break; } } else if (sk->sk_protocol != IPPROTO_TCP) break; if (sk->sk_state != TCP_ESTABLISHED) { retv = -ENOTCONN; break; } if (ipv6_only_sock(sk) || !ipv6_addr_v4mapped(&sk->sk_v6_daddr)) { retv = -EADDRNOTAVAIL; break; } fl6_free_socklist(sk); ipv6_sock_mc_close(sk); /* * Sock is moving from IPv6 to IPv4 (sk_prot), so * remove it from the refcnt debug socks count in the * original family... */ sk_refcnt_debug_dec(sk); if (sk->sk_protocol == IPPROTO_TCP) { struct inet_connection_sock *icsk = inet_csk(sk); local_bh_disable(); sock_prot_inuse_add(net, sk->sk_prot, -1); sock_prot_inuse_add(net, &tcp_prot, 1); local_bh_enable(); sk->sk_prot = &tcp_prot; icsk->icsk_af_ops = &ipv4_specific; sk->sk_socket->ops = &inet_stream_ops; sk->sk_family = PF_INET; tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); } else { struct proto *prot = &udp_prot; if (sk->sk_protocol == IPPROTO_UDPLITE) prot = &udplite_prot; local_bh_disable(); sock_prot_inuse_add(net, sk->sk_prot, -1); sock_prot_inuse_add(net, prot, 1); local_bh_enable(); sk->sk_prot = prot; sk->sk_socket->ops = &inet_dgram_ops; sk->sk_family = PF_INET; } opt = xchg((__force struct ipv6_txoptions **)&np->opt, NULL); if (opt) { atomic_sub(opt->tot_len, &sk->sk_omem_alloc); txopt_put(opt); } pktopt = xchg(&np->pktoptions, NULL); kfree_skb(pktopt); sk->sk_destruct = inet_sock_destruct; /* * ... and add it to the refcnt debug socks count * in the new family. -acme */ sk_refcnt_debug_inc(sk); module_put(THIS_MODULE); retv = 0; break; } goto e_inval; case IPV6_V6ONLY: if (optlen < sizeof(int) || inet_sk(sk)->inet_num) goto e_inval; sk->sk_ipv6only = valbool; retv = 0; break; case IPV6_RECVPKTINFO: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxinfo = valbool; retv = 0; break; case IPV6_2292PKTINFO: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxoinfo = valbool; retv = 0; break; case IPV6_RECVHOPLIMIT: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxhlim = valbool; retv = 0; break; case IPV6_2292HOPLIMIT: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxohlim = valbool; retv = 0; break; case IPV6_RECVRTHDR: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.srcrt = valbool; retv = 0; break; case IPV6_2292RTHDR: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.osrcrt = valbool; retv = 0; break; case IPV6_RECVHOPOPTS: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.hopopts = valbool; retv = 0; break; case IPV6_2292HOPOPTS: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.ohopopts = valbool; retv = 0; break; case IPV6_RECVDSTOPTS: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.dstopts = valbool; retv = 0; break; case IPV6_2292DSTOPTS: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.odstopts = valbool; retv = 0; break; case IPV6_TCLASS: if (optlen < sizeof(int)) goto e_inval; if (val < -1 || val > 0xff) goto e_inval; /* RFC 3542, 6.5: default traffic class of 0x0 */ if (val == -1) val = 0; np->tclass = val; retv = 0; break; case IPV6_RECVTCLASS: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxtclass = valbool; retv = 0; break; case IPV6_FLOWINFO: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxflow = valbool; retv = 0; break; case IPV6_RECVPATHMTU: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxpmtu = valbool; retv = 0; break; case IPV6_TRANSPARENT: if (valbool && !ns_capable(net->user_ns, CAP_NET_ADMIN) && !ns_capable(net->user_ns, CAP_NET_RAW)) { retv = -EPERM; break; } if (optlen < sizeof(int)) goto e_inval; /* we don't have a separate transparent bit for IPV6 we use the one in the IPv4 socket */ inet_sk(sk)->transparent = valbool; retv = 0; break; case IPV6_RECVORIGDSTADDR: if (optlen < sizeof(int)) goto e_inval; np->rxopt.bits.rxorigdstaddr = valbool; retv = 0; break; case IPV6_HOPOPTS: case IPV6_RTHDRDSTOPTS: case IPV6_RTHDR: case IPV6_DSTOPTS: { struct ipv6_txoptions *opt; /* remove any sticky options header with a zero option * length, per RFC3542. */ if (optlen == 0) optval = NULL; else if (!optval) goto e_inval; else if (optlen < sizeof(struct ipv6_opt_hdr) || optlen & 0x7 || optlen > 8 * 255) goto e_inval; /* hop-by-hop / destination options are privileged option */ retv = -EPERM; if (optname != IPV6_RTHDR && !ns_capable(net->user_ns, CAP_NET_RAW)) break; opt = rcu_dereference_protected(np->opt, sock_owned_by_user(sk)); opt = ipv6_renew_options(sk, opt, optname, (struct ipv6_opt_hdr __user *)optval, optlen); if (IS_ERR(opt)) { retv = PTR_ERR(opt); break; } /* routing header option needs extra check */ retv = -EINVAL; if (optname == IPV6_RTHDR && opt && opt->srcrt) { struct ipv6_rt_hdr *rthdr = opt->srcrt; switch (rthdr->type) { #if IS_ENABLED(CONFIG_IPV6_MIP6) case IPV6_SRCRT_TYPE_2: if (rthdr->hdrlen != 2 || rthdr->segments_left != 1) goto sticky_done; break; #endif default: goto sticky_done; } } retv = 0; opt = ipv6_update_options(sk, opt); sticky_done: if (opt) { atomic_sub(opt->tot_len, &sk->sk_omem_alloc); txopt_put(opt); } break; } case IPV6_PKTINFO: { struct in6_pktinfo pkt; if (optlen == 0) goto e_inval; else if (optlen < sizeof(struct in6_pktinfo) || !optval) goto e_inval; if (copy_from_user(&pkt, optval, sizeof(struct in6_pktinfo))) { retv = -EFAULT; break; } if (sk->sk_bound_dev_if && pkt.ipi6_ifindex != sk->sk_bound_dev_if) goto e_inval; np->sticky_pktinfo.ipi6_ifindex = pkt.ipi6_ifindex; np->sticky_pktinfo.ipi6_addr = pkt.ipi6_addr; retv = 0; break; } case IPV6_2292PKTOPTIONS: { struct ipv6_txoptions *opt = NULL; struct msghdr msg; struct flowi6 fl6; int junk; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; if (optlen == 0) goto update; /* 1K is probably excessive * 1K is surely not enough, 2K per standard header is 16K. */ retv = -EINVAL; if (optlen > 64*1024) break; opt = sock_kmalloc(sk, sizeof(*opt) + optlen, GFP_KERNEL); retv = -ENOBUFS; if (!opt) break; memset(opt, 0, sizeof(*opt)); atomic_set(&opt->refcnt, 1); opt->tot_len = sizeof(*opt) + optlen; retv = -EFAULT; if (copy_from_user(opt+1, optval, optlen)) goto done; msg.msg_controllen = optlen; msg.msg_control = (void *)(opt+1); retv = ip6_datagram_send_ctl(net, sk, &msg, &fl6, opt, &junk, &junk, &junk); if (retv) goto done; update: retv = 0; opt = ipv6_update_options(sk, opt); done: if (opt) { atomic_sub(opt->tot_len, &sk->sk_omem_alloc); txopt_put(opt); } break; } case IPV6_UNICAST_HOPS: if (optlen < sizeof(int)) goto e_inval; if (val > 255 || val < -1) goto e_inval; np->hop_limit = val; retv = 0; break; case IPV6_MULTICAST_HOPS: if (sk->sk_type == SOCK_STREAM) break; if (optlen < sizeof(int)) goto e_inval; if (val > 255 || val < -1) goto e_inval; np->mcast_hops = (val == -1 ? IPV6_DEFAULT_MCASTHOPS : val); retv = 0; break; case IPV6_MULTICAST_LOOP: if (optlen < sizeof(int)) goto e_inval; if (val != valbool) goto e_inval; np->mc_loop = valbool; retv = 0; break; case IPV6_UNICAST_IF: { struct net_device *dev = NULL; int ifindex; if (optlen != sizeof(int)) goto e_inval; ifindex = (__force int)ntohl((__force __be32)val); if (ifindex == 0) { np->ucast_oif = 0; retv = 0; break; } dev = dev_get_by_index(net, ifindex); retv = -EADDRNOTAVAIL; if (!dev) break; dev_put(dev); retv = -EINVAL; if (sk->sk_bound_dev_if) break; np->ucast_oif = ifindex; retv = 0; break; } case IPV6_MULTICAST_IF: if (sk->sk_type == SOCK_STREAM) break; if (optlen < sizeof(int)) goto e_inval; if (val) { struct net_device *dev; if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != val) goto e_inval; dev = dev_get_by_index(net, val); if (!dev) { retv = -ENODEV; break; } dev_put(dev); } np->mcast_oif = val; retv = 0; break; case IPV6_ADD_MEMBERSHIP: case IPV6_DROP_MEMBERSHIP: { struct ipv6_mreq mreq; if (optlen < sizeof(struct ipv6_mreq)) goto e_inval; retv = -EPROTO; if (inet_sk(sk)->is_icsk) break; retv = -EFAULT; if (copy_from_user(&mreq, optval, sizeof(struct ipv6_mreq))) break; if (optname == IPV6_ADD_MEMBERSHIP) retv = ipv6_sock_mc_join(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_multiaddr); else retv = ipv6_sock_mc_drop(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_multiaddr); break; } case IPV6_JOIN_ANYCAST: case IPV6_LEAVE_ANYCAST: { struct ipv6_mreq mreq; if (optlen < sizeof(struct ipv6_mreq)) goto e_inval; retv = -EFAULT; if (copy_from_user(&mreq, optval, sizeof(struct ipv6_mreq))) break; if (optname == IPV6_JOIN_ANYCAST) retv = ipv6_sock_ac_join(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_acaddr); else retv = ipv6_sock_ac_drop(sk, mreq.ipv6mr_ifindex, &mreq.ipv6mr_acaddr); break; } case MCAST_JOIN_GROUP: case MCAST_LEAVE_GROUP: { struct group_req greq; struct sockaddr_in6 *psin6; if (optlen < sizeof(struct group_req)) goto e_inval; retv = -EFAULT; if (copy_from_user(&greq, optval, sizeof(struct group_req))) break; if (greq.gr_group.ss_family != AF_INET6) { retv = -EADDRNOTAVAIL; break; } psin6 = (struct sockaddr_in6 *)&greq.gr_group; if (optname == MCAST_JOIN_GROUP) retv = ipv6_sock_mc_join(sk, greq.gr_interface, &psin6->sin6_addr); else retv = ipv6_sock_mc_drop(sk, greq.gr_interface, &psin6->sin6_addr); break; } case MCAST_JOIN_SOURCE_GROUP: case MCAST_LEAVE_SOURCE_GROUP: case MCAST_BLOCK_SOURCE: case MCAST_UNBLOCK_SOURCE: { struct group_source_req greqs; int omode, add; if (optlen < sizeof(struct group_source_req)) goto e_inval; if (copy_from_user(&greqs, optval, sizeof(greqs))) { retv = -EFAULT; break; } if (greqs.gsr_group.ss_family != AF_INET6 || greqs.gsr_source.ss_family != AF_INET6) { retv = -EADDRNOTAVAIL; break; } if (optname == MCAST_BLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 1; } else if (optname == MCAST_UNBLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 0; } else if (optname == MCAST_JOIN_SOURCE_GROUP) { struct sockaddr_in6 *psin6; psin6 = (struct sockaddr_in6 *)&greqs.gsr_group; retv = ipv6_sock_mc_join(sk, greqs.gsr_interface, &psin6->sin6_addr); /* prior join w/ different source is ok */ if (retv && retv != -EADDRINUSE) break; omode = MCAST_INCLUDE; add = 1; } else /* MCAST_LEAVE_SOURCE_GROUP */ { omode = MCAST_INCLUDE; add = 0; } retv = ip6_mc_source(add, omode, sk, &greqs); break; } case MCAST_MSFILTER: { struct group_filter *gsf; if (optlen < GROUP_FILTER_SIZE(0)) goto e_inval; if (optlen > sysctl_optmem_max) { retv = -ENOBUFS; break; } gsf = kmalloc(optlen, GFP_KERNEL); if (!gsf) { retv = -ENOBUFS; break; } retv = -EFAULT; if (copy_from_user(gsf, optval, optlen)) { kfree(gsf); break; } /* numsrc >= (4G-140)/128 overflow in 32 bits */ if (gsf->gf_numsrc >= 0x1ffffffU || gsf->gf_numsrc > sysctl_mld_max_msf) { kfree(gsf); retv = -ENOBUFS; break; } if (GROUP_FILTER_SIZE(gsf->gf_numsrc) > optlen) { kfree(gsf); retv = -EINVAL; break; } retv = ip6_mc_msfilter(sk, gsf); kfree(gsf); break; } case IPV6_ROUTER_ALERT: if (optlen < sizeof(int)) goto e_inval; retv = ip6_ra_control(sk, val); break; case IPV6_MTU_DISCOVER: if (optlen < sizeof(int)) goto e_inval; if (val < IPV6_PMTUDISC_DONT || val > IPV6_PMTUDISC_OMIT) goto e_inval; np->pmtudisc = val; retv = 0; break; case IPV6_MTU: if (optlen < sizeof(int)) goto e_inval; if (val && val < IPV6_MIN_MTU) goto e_inval; np->frag_size = val; retv = 0; break; case IPV6_RECVERR: if (optlen < sizeof(int)) goto e_inval; np->recverr = valbool; if (!val) skb_queue_purge(&sk->sk_error_queue); retv = 0; break; case IPV6_FLOWINFO_SEND: if (optlen < sizeof(int)) goto e_inval; np->sndflow = valbool; retv = 0; break; case IPV6_FLOWLABEL_MGR: retv = ipv6_flowlabel_opt(sk, optval, optlen); break; case IPV6_IPSEC_POLICY: case IPV6_XFRM_POLICY: retv = -EPERM; if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) break; retv = xfrm_user_policy(sk, optname, optval, optlen); break; case IPV6_ADDR_PREFERENCES: { unsigned int pref = 0; unsigned int prefmask = ~0; if (optlen < sizeof(int)) goto e_inval; retv = -EINVAL; /* check PUBLIC/TMP/PUBTMP_DEFAULT conflicts */ switch (val & (IPV6_PREFER_SRC_PUBLIC| IPV6_PREFER_SRC_TMP| IPV6_PREFER_SRC_PUBTMP_DEFAULT)) { case IPV6_PREFER_SRC_PUBLIC: pref |= IPV6_PREFER_SRC_PUBLIC; break; case IPV6_PREFER_SRC_TMP: pref |= IPV6_PREFER_SRC_TMP; break; case IPV6_PREFER_SRC_PUBTMP_DEFAULT: break; case 0: goto pref_skip_pubtmp; default: goto e_inval; } prefmask &= ~(IPV6_PREFER_SRC_PUBLIC| IPV6_PREFER_SRC_TMP); pref_skip_pubtmp: /* check HOME/COA conflicts */ switch (val & (IPV6_PREFER_SRC_HOME|IPV6_PREFER_SRC_COA)) { case IPV6_PREFER_SRC_HOME: break; case IPV6_PREFER_SRC_COA: pref |= IPV6_PREFER_SRC_COA; case 0: goto pref_skip_coa; default: goto e_inval; } prefmask &= ~IPV6_PREFER_SRC_COA; pref_skip_coa: /* check CGA/NONCGA conflicts */ switch (val & (IPV6_PREFER_SRC_CGA|IPV6_PREFER_SRC_NONCGA)) { case IPV6_PREFER_SRC_CGA: case IPV6_PREFER_SRC_NONCGA: case 0: break; default: goto e_inval; } np->srcprefs = (np->srcprefs & prefmask) | pref; retv = 0; break; } case IPV6_MINHOPCOUNT: if (optlen < sizeof(int)) goto e_inval; if (val < 0 || val > 255) goto e_inval; np->min_hopcount = val; retv = 0; break; case IPV6_DONTFRAG: np->dontfrag = valbool; retv = 0; break; case IPV6_AUTOFLOWLABEL: np->autoflowlabel = valbool; retv = 0; break; } release_sock(sk); if (needs_rtnl) rtnl_unlock(); return retv; e_inval: release_sock(sk); if (needs_rtnl) rtnl_unlock(); return -EINVAL; }
23,686
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: long Segment::DoParseNext( const Cluster*& pResult, long long& pos, long& len) { long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; long long off_next = 0; long long cluster_size = -1; for (;;) { if ((total >= 0) && (pos >= total)) return 1; //EOF if ((segment_stop >= 0) && (pos >= segment_stop)) return 1; //EOF if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; //absolute const long long idoff = pos - m_start; //relative const long long id = ReadUInt(m_pReader, idpos, len); //absolute if (id < 0) //error return static_cast<long>(id); if (id == 0) //weird return -1; //generic error pos += len; //consume ID if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) //error return static_cast<long>(size); pos += len; //consume length of size of element if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if ((segment_stop >= 0) && (size != unknown_size) && ((pos + size) > segment_stop)) { return E_FILE_FORMAT_INVALID; } if (id == 0x0C53BB6B) //Cues ID { if (size == unknown_size) return E_FILE_FORMAT_INVALID; const long long element_stop = pos + size; if ((segment_stop >= 0) && (element_stop > segment_stop)) return E_FILE_FORMAT_INVALID; const long long element_start = idpos; const long long element_size = element_stop - element_start; if (m_pCues == NULL) { m_pCues = new Cues(this, pos, size, element_start, element_size); assert(m_pCues); //TODO } pos += size; //consume payload assert((segment_stop < 0) || (pos <= segment_stop)); continue; } if (id != 0x0F43B675) //not a Cluster ID { if (size == unknown_size) return E_FILE_FORMAT_INVALID; pos += size; //consume payload assert((segment_stop < 0) || (pos <= segment_stop)); continue; } #if 0 //this is commented-out to support incremental cluster parsing len = static_cast<long>(size); if (element_stop > avail) return E_BUFFER_NOT_FULL; #endif off_next = idoff; if (size != unknown_size) cluster_size = size; break; } assert(off_next > 0); //have cluster Cluster** const ii = m_clusters + m_clusterCount; Cluster** i = ii; Cluster** const jj = ii + m_clusterPreloadCount; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); const Cluster* const pNext = *k; assert(pNext); assert(pNext->m_index < 0); pos = pNext->GetPosition(); assert(pos >= 0); if (pos < off_next) i = k + 1; else if (pos > off_next) j = k; else { pResult = pNext; return 0; //success } } assert(i == j); long long pos_; long len_; status = Cluster::HasBlockEntries(this, off_next, pos_, len_); if (status < 0) //error or underflow { pos = pos_; len = len_; return status; } if (status > 0) //means "found at least one block entry" { Cluster* const pNext = Cluster::Create(this, -1, //preloaded off_next); assert(pNext); const ptrdiff_t idx_next = i - m_clusters; //insertion position PreloadCluster(pNext, idx_next); assert(m_clusters); assert(idx_next < m_clusterSize); assert(m_clusters[idx_next] == pNext); pResult = pNext; return 0; //success } if (cluster_size < 0) //unknown size { const long long payload_pos = pos; //absolute pos of cluster payload for (;;) //determine cluster size { if ((total >= 0) && (pos >= total)) break; if ((segment_stop >= 0) && (pos >= segment_stop)) break; //no more clusters if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id < 0) //error (or underflow) return static_cast<long>(id); if (id == 0x0F43B675) //Cluster ID break; if (id == 0x0C53BB6B) //Cues ID break; pos += len; //consume ID (of sub-element) if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) //error return static_cast<long>(size); pos += len; //consume size field of element if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; //not allowed for sub-elements if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird return E_FILE_FORMAT_INVALID; pos += size; //consume payload of sub-element assert((segment_stop < 0) || (pos <= segment_stop)); } //determine cluster size cluster_size = pos - payload_pos; assert(cluster_size >= 0); //TODO: handle cluster_size = 0 pos = payload_pos; //reset and re-parse original cluster } pos += cluster_size; //consume payload assert((segment_stop < 0) || (pos <= segment_stop)); return 2; //try to find a cluster that follows next } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Segment::DoParseNext( pResult = 0; if (pCurr->m_index >= 0) { // loaded (not merely preloaded) assert(m_clusters[pCurr->m_index] == pCurr); const long next_idx = pCurr->m_index + 1; if (next_idx < m_clusterCount) { pResult = m_clusters[next_idx]; return 0; // success } // curr cluster is last among loaded const long result = LoadCluster(pos, len); if (result < 0) // error or underflow return result; if (result > 0) // no more clusters { // pResult = &m_eos; return 1; } pResult = GetLast(); return 0; // success } assert(m_pos > 0); long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; // interrogate curr cluster pos = pCurr->m_element_start; if (pCurr->m_element_size >= 0) pos += pCurr->m_element_size; else { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(m_pReader, pos, len); if (id != 0x0F43B675) // weird: not Cluster ID return -1; pos += len; // consume ID // Read Size if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return static_cast<long>(size); pos += len; // consume size field const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) // TODO: should never happen return E_FILE_FORMAT_INVALID; // TODO: resolve this // assert((pCurr->m_size <= 0) || (pCurr->m_size == size)); if ((segment_stop >= 0) && ((pos + size) > segment_stop)) return E_FILE_FORMAT_INVALID; // Pos now points to start of payload pos += size; // consume payload (that is, the current cluster) assert((segment_stop < 0) || (pos <= segment_stop)); // By consuming the payload, we are assuming that the curr // cluster isn't interesting. That is, we don't bother checking // whether the payload of the curr cluster is less than what // happens to be available (obtained via IMkvReader::Length). // Presumably the caller has already dispensed with the current // cluster, and really does want the next cluster. } // pos now points to just beyond the last fully-loaded cluster for (;;) { const long status = DoParseNext(pResult, pos, len); if (status <= 1) return status; } } long Segment::DoParseNext(const Cluster*& pResult, long long& pos, long& len) { long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; // Parse next cluster. This is strictly a parsing activity. // Creation of a new cluster object happens later, after the // parsing is done. long long off_next = 0; long long cluster_size = -1; for (;;) { if ((total >= 0) && (pos >= total)) return 1; // EOF if ((segment_stop >= 0) && (pos >= segment_stop)) return 1; // EOF if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; // absolute const long long idoff = pos - m_start; // relative const long long id = ReadUInt(m_pReader, idpos, len); // absolute if (id < 0) // error return static_cast<long>(id); if (id == 0) // weird return -1; // generic error pos += len; // consume ID // Read Size if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return static_cast<long>(size); pos += len; // consume length of size of element // Pos now points to start of payload if (size == 0) // weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if ((segment_stop >= 0) && (size != unknown_size) && ((pos + size) > segment_stop)) { return E_FILE_FORMAT_INVALID; } if (id == 0x0C53BB6B) { // Cues ID if (size == unknown_size) return E_FILE_FORMAT_INVALID; const long long element_stop = pos + size; if ((segment_stop >= 0) && (element_stop > segment_stop)) return E_FILE_FORMAT_INVALID; const long long element_start = idpos; const long long element_size = element_stop - element_start; if (m_pCues == NULL) { m_pCues = new Cues(this, pos, size, element_start, element_size); assert(m_pCues); // TODO } pos += size; // consume payload assert((segment_stop < 0) || (pos <= segment_stop)); continue; } if (id != 0x0F43B675) { // not a Cluster ID if (size == unknown_size) return E_FILE_FORMAT_INVALID; pos += size; // consume payload assert((segment_stop < 0) || (pos <= segment_stop)); continue; } #if 0 // this is commented-out to support incremental cluster parsing len = static_cast<long>(size); if (element_stop > avail) return E_BUFFER_NOT_FULL; #endif // We have a cluster. off_next = idoff; if (size != unknown_size) cluster_size = size; break; } assert(off_next > 0); // have cluster // We have parsed the next cluster. // We have not created a cluster object yet. What we need // to do now is determine whether it has already be preloaded //(in which case, an object for this cluster has already been // created), and if not, create a new cluster object. Cluster** const ii = m_clusters + m_clusterCount; Cluster** i = ii; Cluster** const jj = ii + m_clusterPreloadCount; Cluster** j = jj; while (i < j) { // INVARIANT: //[0, i) < pos_next //[i, j) ? //[j, jj) > pos_next Cluster** const k = i + (j - i) / 2; assert(k < jj); const Cluster* const pNext = *k; assert(pNext); assert(pNext->m_index < 0); pos = pNext->GetPosition(); assert(pos >= 0); if (pos < off_next) i = k + 1; else if (pos > off_next) j = k; else { pResult = pNext; return 0; // success } } assert(i == j); long long pos_; long len_; status = Cluster::HasBlockEntries(this, off_next, pos_, len_); if (status < 0) { // error or underflow pos = pos_; len = len_; return status; } if (status > 0) { // means "found at least one block entry" Cluster* const pNext = Cluster::Create(this, -1, // preloaded off_next); // element_size); assert(pNext); const ptrdiff_t idx_next = i - m_clusters; // insertion position PreloadCluster(pNext, idx_next); assert(m_clusters); assert(idx_next < m_clusterSize); assert(m_clusters[idx_next] == pNext); pResult = pNext; return 0; // success } // status == 0 means "no block entries found" if (cluster_size < 0) { // unknown size const long long payload_pos = pos; // absolute pos of cluster payload for (;;) { // determine cluster size if ((total >= 0) && (pos >= total)) break; if ((segment_stop >= 0) && (pos >= segment_stop)) break; // no more clusters // Read ID if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id < 0) // error (or underflow) return static_cast<long>(id); // This is the distinguished set of ID's we use to determine // that we have exhausted the sub-element's inside the cluster // whose ID we parsed earlier. if (id == 0x0F43B675) // Cluster ID break; if (id == 0x0C53BB6B) // Cues ID break; pos += len; // consume ID (of sub-element) // Read Size if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return static_cast<long>(size); pos += len; // consume size field of element // pos now points to start of sub-element's payload if (size == 0) // weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; // not allowed for sub-elements if ((segment_stop >= 0) && ((pos + size) > segment_stop)) // weird return E_FILE_FORMAT_INVALID; pos += size; // consume payload of sub-element assert((segment_stop < 0) || (pos <= segment_stop)); } // determine cluster size cluster_size = pos - payload_pos; assert(cluster_size >= 0); // TODO: handle cluster_size = 0 pos = payload_pos; // reset and re-parse original cluster } pos += cluster_size; // consume payload assert((segment_stop < 0) || (pos <= segment_stop)); return 2; // try to find a cluster that follows next }
19,066
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void CrosLibrary::TestApi::SetLoginLibrary( LoginLibrary* library, bool own) { library_->login_lib_.SetImpl(library, own); } 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 CWE ID: CWE-189
void CrosLibrary::TestApi::SetLoginLibrary(
15,862
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static Image *ReadPCDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickOffsetType offset; MagickSizeType number_pixels; register ssize_t i, y; register PixelPacket *q; register unsigned char *c1, *c2, *yy; size_t height, number_images, rotate, scene, width; ssize_t count, x; unsigned char *chroma1, *chroma2, *header, *luma; unsigned int overview; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a PCD file. */ header=(unsigned char *) AcquireQuantumMemory(0x800,3UL*sizeof(*header)); if (header == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,3*0x800,header); overview=LocaleNCompare((char *) header,"PCD_OPA",7) == 0; if ((count == 0) || ((LocaleNCompare((char *) header+0x800,"PCD",3) != 0) && (overview == 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); rotate=header[0x0e02] & 0x03; number_images=(header[10] << 8) | header[11]; if (number_images > 65535) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); header=(unsigned char *) RelinquishMagickMemory(header); /* Determine resolution by scene specification. */ if ((image->columns == 0) || (image->rows == 0)) scene=3; else { width=192; height=128; for (scene=1; scene < 6; scene++) { if ((width >= image->columns) && (height >= image->rows)) break; width<<=1; height<<=1; } } if (image_info->number_scenes != 0) scene=(size_t) MagickMin(image_info->scene,6); if (overview != 0) scene=1; /* Initialize image structure. */ width=192; height=128; for (i=1; i < (ssize_t) MagickMin(scene,3); i++) { width<<=1; height<<=1; } image->columns=width; image->rows=height; image->depth=8; for ( ; i < (ssize_t) scene; i++) { image->columns<<=1; image->rows<<=1; } /* Allocate luma and chroma memory. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); chroma1=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*chroma1)); chroma2=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*chroma2)); luma=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*luma)); if ((chroma1 == (unsigned char *) NULL) || (chroma2 == (unsigned char *) NULL) || (luma == (unsigned char *) NULL)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Advance to image data. */ offset=93; if (overview != 0) offset=2; else if (scene == 2) offset=20; else if (scene <= 1) offset=1; for (i=0; i < (ssize_t) (offset*0x800); i++) (void) ReadBlobByte(image); if (overview != 0) { Image *overview_image; MagickProgressMonitor progress_monitor; register ssize_t j; /* Read thumbnails from overview image. */ for (j=1; j <= (ssize_t) number_images; j++) { progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) FormatLocaleString(image->filename,MaxTextExtent, "images/img%04ld.pcd",(long) j); (void) FormatLocaleString(image->magick_filename,MaxTextExtent, "images/img%04ld.pcd",(long) j); image->scene=(size_t) j; image->columns=width; image->rows=height; image->depth=8; yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) height; y+=2) { count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width >> 1,c1); c1+=image->columns; count=ReadBlob(image,width >> 1,c2); c2+=image->columns; } Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma1); Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma2); /* Transfer luminance and chrominance channels. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*yy++)); SetPixelGreen(q,ScaleCharToQuantum(*c1++)); SetPixelBlue(q,ScaleCharToQuantum(*c2++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } image->colorspace=YCCColorspace; if (LocaleCompare(image_info->magick,"PCDS") == 0) SetImageColorspace(image,sRGBColorspace); if (j < (ssize_t) number_images) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,j-1,number_images); if (status == MagickFalse) break; } } chroma2=(unsigned char *) RelinquishMagickMemory(chroma2); chroma1=(unsigned char *) RelinquishMagickMemory(chroma1); luma=(unsigned char *) RelinquishMagickMemory(luma); image=GetFirstImageInList(image); overview_image=OverviewImage(image_info,image,exception); return(overview_image); } /* Read interleaved image. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) height; y+=2) { count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width >> 1,c1); c1+=image->columns; count=ReadBlob(image,width >> 1,c2); c2+=image->columns; } if (scene >= 4) { /* Recover luminance deltas for 1536x1024 image. */ Upsample(768,512,image->columns,luma); Upsample(384,256,image->columns,chroma1); Upsample(384,256,image->columns,chroma2); image->rows=1024; for (i=0; i < (4*0x800); i++) (void) ReadBlobByte(image); status=DecodeImage(image,luma,chroma1,chroma2); if ((scene >= 5) && status) { /* Recover luminance deltas for 3072x2048 image. */ Upsample(1536,1024,image->columns,luma); Upsample(768,512,image->columns,chroma1); Upsample(768,512,image->columns,chroma2); image->rows=2048; offset=TellBlob(image)/0x800+12; offset=SeekBlob(image,offset*0x800,SEEK_SET); status=DecodeImage(image,luma,chroma1,chroma2); if ((scene >= 6) && (status != MagickFalse)) { /* Recover luminance deltas for 6144x4096 image (vaporware). */ Upsample(3072,2048,image->columns,luma); Upsample(1536,1024,image->columns,chroma1); Upsample(1536,1024,image->columns,chroma2); image->rows=4096; } } } Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma1); Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma2); /* Transfer luminance and chrominance channels. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*yy++)); SetPixelGreen(q,ScaleCharToQuantum(*c1++)); SetPixelBlue(q,ScaleCharToQuantum(*c2++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } chroma2=(unsigned char *) RelinquishMagickMemory(chroma2); chroma1=(unsigned char *) RelinquishMagickMemory(chroma1); luma=(unsigned char *) RelinquishMagickMemory(luma); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); if (image_info->ping == MagickFalse) if ((rotate == 1) || (rotate == 3)) { double degrees; Image *rotate_image; /* Rotate image. */ degrees=rotate == 1 ? -90.0 : 90.0; rotate_image=RotateImage(image,degrees,exception); if (rotate_image != (Image *) NULL) { image=DestroyImage(image); image=rotate_image; } } /* Set CCIR 709 primaries with a D65 white point. */ image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->gamma=1.000f/2.200f; image->colorspace=YCCColorspace; if (LocaleCompare(image_info->magick,"PCDS") == 0) SetImageColorspace(image,sRGBColorspace); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadPCDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickOffsetType offset; MagickSizeType number_pixels; register ssize_t i, y; register PixelPacket *q; register unsigned char *c1, *c2, *yy; size_t height, number_images, rotate, scene, width; ssize_t count, x; unsigned char *chroma1, *chroma2, *header, *luma; unsigned int overview; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a PCD file. */ header=(unsigned char *) AcquireQuantumMemory(0x800,3UL*sizeof(*header)); if (header == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,3*0x800,header); overview=LocaleNCompare((char *) header,"PCD_OPA",7) == 0; if ((count == 0) || ((LocaleNCompare((char *) header+0x800,"PCD",3) != 0) && (overview == 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); rotate=header[0x0e02] & 0x03; number_images=(header[10] << 8) | header[11]; if (number_images > 65535) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); header=(unsigned char *) RelinquishMagickMemory(header); /* Determine resolution by scene specification. */ if ((image->columns == 0) || (image->rows == 0)) scene=3; else { width=192; height=128; for (scene=1; scene < 6; scene++) { if ((width >= image->columns) && (height >= image->rows)) break; width<<=1; height<<=1; } } if (image_info->number_scenes != 0) scene=(size_t) MagickMin(image_info->scene,6); if (overview != 0) scene=1; /* Initialize image structure. */ width=192; height=128; for (i=1; i < (ssize_t) MagickMin(scene,3); i++) { width<<=1; height<<=1; } image->columns=width; image->rows=height; image->depth=8; for ( ; i < (ssize_t) scene; i++) { image->columns<<=1; image->rows<<=1; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate luma and chroma memory. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); chroma1=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*chroma1)); chroma2=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*chroma2)); luma=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*luma)); if ((chroma1 == (unsigned char *) NULL) || (chroma2 == (unsigned char *) NULL) || (luma == (unsigned char *) NULL)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Advance to image data. */ offset=93; if (overview != 0) offset=2; else if (scene == 2) offset=20; else if (scene <= 1) offset=1; for (i=0; i < (ssize_t) (offset*0x800); i++) (void) ReadBlobByte(image); if (overview != 0) { Image *overview_image; MagickProgressMonitor progress_monitor; register ssize_t j; /* Read thumbnails from overview image. */ for (j=1; j <= (ssize_t) number_images; j++) { progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) FormatLocaleString(image->filename,MaxTextExtent, "images/img%04ld.pcd",(long) j); (void) FormatLocaleString(image->magick_filename,MaxTextExtent, "images/img%04ld.pcd",(long) j); image->scene=(size_t) j; image->columns=width; image->rows=height; image->depth=8; yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) height; y+=2) { count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width >> 1,c1); c1+=image->columns; count=ReadBlob(image,width >> 1,c2); c2+=image->columns; } Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma1); Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma2); /* Transfer luminance and chrominance channels. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*yy++)); SetPixelGreen(q,ScaleCharToQuantum(*c1++)); SetPixelBlue(q,ScaleCharToQuantum(*c2++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } image->colorspace=YCCColorspace; if (LocaleCompare(image_info->magick,"PCDS") == 0) SetImageColorspace(image,sRGBColorspace); if (j < (ssize_t) number_images) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,j-1,number_images); if (status == MagickFalse) break; } } chroma2=(unsigned char *) RelinquishMagickMemory(chroma2); chroma1=(unsigned char *) RelinquishMagickMemory(chroma1); luma=(unsigned char *) RelinquishMagickMemory(luma); image=GetFirstImageInList(image); overview_image=OverviewImage(image_info,image,exception); return(overview_image); } /* Read interleaved image. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) height; y+=2) { count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width >> 1,c1); c1+=image->columns; count=ReadBlob(image,width >> 1,c2); c2+=image->columns; } if (scene >= 4) { /* Recover luminance deltas for 1536x1024 image. */ Upsample(768,512,image->columns,luma); Upsample(384,256,image->columns,chroma1); Upsample(384,256,image->columns,chroma2); image->rows=1024; for (i=0; i < (4*0x800); i++) (void) ReadBlobByte(image); status=DecodeImage(image,luma,chroma1,chroma2); if ((scene >= 5) && status) { /* Recover luminance deltas for 3072x2048 image. */ Upsample(1536,1024,image->columns,luma); Upsample(768,512,image->columns,chroma1); Upsample(768,512,image->columns,chroma2); image->rows=2048; offset=TellBlob(image)/0x800+12; offset=SeekBlob(image,offset*0x800,SEEK_SET); status=DecodeImage(image,luma,chroma1,chroma2); if ((scene >= 6) && (status != MagickFalse)) { /* Recover luminance deltas for 6144x4096 image (vaporware). */ Upsample(3072,2048,image->columns,luma); Upsample(1536,1024,image->columns,chroma1); Upsample(1536,1024,image->columns,chroma2); image->rows=4096; } } } Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma1); Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma2); /* Transfer luminance and chrominance channels. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*yy++)); SetPixelGreen(q,ScaleCharToQuantum(*c1++)); SetPixelBlue(q,ScaleCharToQuantum(*c2++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } chroma2=(unsigned char *) RelinquishMagickMemory(chroma2); chroma1=(unsigned char *) RelinquishMagickMemory(chroma1); luma=(unsigned char *) RelinquishMagickMemory(luma); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); if (image_info->ping == MagickFalse) if ((rotate == 1) || (rotate == 3)) { double degrees; Image *rotate_image; /* Rotate image. */ degrees=rotate == 1 ? -90.0 : 90.0; rotate_image=RotateImage(image,degrees,exception); if (rotate_image != (Image *) NULL) { image=DestroyImage(image); image=rotate_image; } } /* Set CCIR 709 primaries with a D65 white point. */ image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->gamma=1.000f/2.200f; image->colorspace=YCCColorspace; if (LocaleCompare(image_info->magick,"PCDS") == 0) SetImageColorspace(image,sRGBColorspace); return(GetFirstImageInList(image)); }
7,617
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: eigrp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct eigrp_common_header *eigrp_com_header; const struct eigrp_tlv_header *eigrp_tlv_header; const u_char *tptr,*tlv_tptr; u_int tlen,eigrp_tlv_len,eigrp_tlv_type,tlv_tlen, byte_length, bit_length; uint8_t prefix[4]; union { const struct eigrp_tlv_general_parm_t *eigrp_tlv_general_parm; const struct eigrp_tlv_sw_version_t *eigrp_tlv_sw_version; const struct eigrp_tlv_ip_int_t *eigrp_tlv_ip_int; const struct eigrp_tlv_ip_ext_t *eigrp_tlv_ip_ext; const struct eigrp_tlv_at_cable_setup_t *eigrp_tlv_at_cable_setup; const struct eigrp_tlv_at_int_t *eigrp_tlv_at_int; const struct eigrp_tlv_at_ext_t *eigrp_tlv_at_ext; } tlv_ptr; tptr=pptr; eigrp_com_header = (const struct eigrp_common_header *)pptr; ND_TCHECK(*eigrp_com_header); /* * Sanity checking of the header. */ if (eigrp_com_header->version != EIGRP_VERSION) { ND_PRINT((ndo, "EIGRP version %u packet not supported",eigrp_com_header->version)); return; } /* in non-verbose mode just lets print the basic Message Type*/ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "EIGRP %s, length: %u", tok2str(eigrp_opcode_values, "unknown (%u)",eigrp_com_header->opcode), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ tlen=len-sizeof(struct eigrp_common_header); /* FIXME print other header info */ ND_PRINT((ndo, "\n\tEIGRP v%u, opcode: %s (%u), chksum: 0x%04x, Flags: [%s]\n\tseq: 0x%08x, ack: 0x%08x, AS: %u, length: %u", eigrp_com_header->version, tok2str(eigrp_opcode_values, "unknown, type: %u",eigrp_com_header->opcode), eigrp_com_header->opcode, EXTRACT_16BITS(&eigrp_com_header->checksum), tok2str(eigrp_common_header_flag_values, "none", EXTRACT_32BITS(&eigrp_com_header->flags)), EXTRACT_32BITS(&eigrp_com_header->seq), EXTRACT_32BITS(&eigrp_com_header->ack), EXTRACT_32BITS(&eigrp_com_header->asn), tlen)); tptr+=sizeof(const struct eigrp_common_header); while(tlen>0) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct eigrp_tlv_header)); eigrp_tlv_header = (const struct eigrp_tlv_header *)tptr; eigrp_tlv_len=EXTRACT_16BITS(&eigrp_tlv_header->length); eigrp_tlv_type=EXTRACT_16BITS(&eigrp_tlv_header->type); if (eigrp_tlv_len < sizeof(struct eigrp_tlv_header) || eigrp_tlv_len > tlen) { print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",tlen); return; } ND_PRINT((ndo, "\n\t %s TLV (0x%04x), length: %u", tok2str(eigrp_tlv_values, "Unknown", eigrp_tlv_type), eigrp_tlv_type, eigrp_tlv_len)); tlv_tptr=tptr+sizeof(struct eigrp_tlv_header); tlv_tlen=eigrp_tlv_len-sizeof(struct eigrp_tlv_header); /* did we capture enough for fully decoding the object ? */ ND_TCHECK2(*tptr, eigrp_tlv_len); switch(eigrp_tlv_type) { case EIGRP_TLV_GENERAL_PARM: tlv_ptr.eigrp_tlv_general_parm = (const struct eigrp_tlv_general_parm_t *)tlv_tptr; ND_PRINT((ndo, "\n\t holdtime: %us, k1 %u, k2 %u, k3 %u, k4 %u, k5 %u", EXTRACT_16BITS(tlv_ptr.eigrp_tlv_general_parm->holdtime), tlv_ptr.eigrp_tlv_general_parm->k1, tlv_ptr.eigrp_tlv_general_parm->k2, tlv_ptr.eigrp_tlv_general_parm->k3, tlv_ptr.eigrp_tlv_general_parm->k4, tlv_ptr.eigrp_tlv_general_parm->k5)); break; case EIGRP_TLV_SW_VERSION: tlv_ptr.eigrp_tlv_sw_version = (const struct eigrp_tlv_sw_version_t *)tlv_tptr; ND_PRINT((ndo, "\n\t IOS version: %u.%u, EIGRP version %u.%u", tlv_ptr.eigrp_tlv_sw_version->ios_major, tlv_ptr.eigrp_tlv_sw_version->ios_minor, tlv_ptr.eigrp_tlv_sw_version->eigrp_major, tlv_ptr.eigrp_tlv_sw_version->eigrp_minor)); break; case EIGRP_TLV_IP_INT: tlv_ptr.eigrp_tlv_ip_int = (const struct eigrp_tlv_ip_int_t *)tlv_tptr; bit_length = tlv_ptr.eigrp_tlv_ip_int->plen; if (bit_length > 32) { ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length)); break; } byte_length = (bit_length + 7) / 8; /* variable length encoding */ memset(prefix, 0, 4); memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_int->destination,byte_length); ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ", ipaddr_string(ndo, prefix), bit_length)); if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->nexthop) == 0) ND_PRINT((ndo, "self")); else ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_int->nexthop))); ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u", (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->delay)/100), EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->bandwidth), EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_int->mtu), tlv_ptr.eigrp_tlv_ip_int->hopcount, tlv_ptr.eigrp_tlv_ip_int->reliability, tlv_ptr.eigrp_tlv_ip_int->load)); break; case EIGRP_TLV_IP_EXT: tlv_ptr.eigrp_tlv_ip_ext = (const struct eigrp_tlv_ip_ext_t *)tlv_tptr; bit_length = tlv_ptr.eigrp_tlv_ip_ext->plen; if (bit_length > 32) { ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length)); break; } byte_length = (bit_length + 7) / 8; /* variable length encoding */ memset(prefix, 0, 4); memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_ext->destination,byte_length); ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ", ipaddr_string(ndo, prefix), bit_length)); if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->nexthop) == 0) ND_PRINT((ndo, "self")); else ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_ext->nexthop))); ND_PRINT((ndo, "\n\t origin-router %s, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u", ipaddr_string(ndo, tlv_ptr.eigrp_tlv_ip_ext->origin_router), EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->origin_as), tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_ip_ext->proto_id), tlv_ptr.eigrp_tlv_ip_ext->flags, EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->tag), EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->metric))); ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u", (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->delay)/100), EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->bandwidth), EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_ext->mtu), tlv_ptr.eigrp_tlv_ip_ext->hopcount, tlv_ptr.eigrp_tlv_ip_ext->reliability, tlv_ptr.eigrp_tlv_ip_ext->load)); break; case EIGRP_TLV_AT_CABLE_SETUP: tlv_ptr.eigrp_tlv_at_cable_setup = (const struct eigrp_tlv_at_cable_setup_t *)tlv_tptr; ND_PRINT((ndo, "\n\t Cable-range: %u-%u, Router-ID %u", EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_start), EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_end), EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->router_id))); break; case EIGRP_TLV_AT_INT: tlv_ptr.eigrp_tlv_at_int = (const struct eigrp_tlv_at_int_t *)tlv_tptr; ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ", EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_start), EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_end))); if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop) == 0) ND_PRINT((ndo, "self")); else ND_PRINT((ndo, "%u.%u", EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop), EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop[2]))); ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u", (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->delay)/100), EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->bandwidth), EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_int->mtu), tlv_ptr.eigrp_tlv_at_int->hopcount, tlv_ptr.eigrp_tlv_at_int->reliability, tlv_ptr.eigrp_tlv_at_int->load)); break; case EIGRP_TLV_AT_EXT: tlv_ptr.eigrp_tlv_at_ext = (const struct eigrp_tlv_at_ext_t *)tlv_tptr; ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ", EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_start), EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_end))); if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop) == 0) ND_PRINT((ndo, "self")); else ND_PRINT((ndo, "%u.%u", EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop), EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop[2]))); ND_PRINT((ndo, "\n\t origin-router %u, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u", EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_router), EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_as), tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_at_ext->proto_id), tlv_ptr.eigrp_tlv_at_ext->flags, EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->tag), EXTRACT_16BITS(tlv_ptr.eigrp_tlv_at_ext->metric))); ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u", (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->delay)/100), EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->bandwidth), EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_ext->mtu), tlv_ptr.eigrp_tlv_at_ext->hopcount, tlv_ptr.eigrp_tlv_at_ext->reliability, tlv_ptr.eigrp_tlv_at_ext->load)); break; /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case EIGRP_TLV_AUTH: case EIGRP_TLV_SEQ: case EIGRP_TLV_MCAST_SEQ: case EIGRP_TLV_IPX_INT: case EIGRP_TLV_IPX_EXT: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo,tlv_tptr,"\n\t ",tlv_tlen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag > 1) print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ", eigrp_tlv_len-sizeof(struct eigrp_tlv_header)); tptr+=eigrp_tlv_len; tlen-=eigrp_tlv_len; } return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); } Commit Message: CVE-2017-12901/EIGRP: Do more length checks. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
eigrp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct eigrp_common_header *eigrp_com_header; const struct eigrp_tlv_header *eigrp_tlv_header; const u_char *tptr,*tlv_tptr; u_int tlen,eigrp_tlv_len,eigrp_tlv_type,tlv_tlen, byte_length, bit_length; uint8_t prefix[4]; union { const struct eigrp_tlv_general_parm_t *eigrp_tlv_general_parm; const struct eigrp_tlv_sw_version_t *eigrp_tlv_sw_version; const struct eigrp_tlv_ip_int_t *eigrp_tlv_ip_int; const struct eigrp_tlv_ip_ext_t *eigrp_tlv_ip_ext; const struct eigrp_tlv_at_cable_setup_t *eigrp_tlv_at_cable_setup; const struct eigrp_tlv_at_int_t *eigrp_tlv_at_int; const struct eigrp_tlv_at_ext_t *eigrp_tlv_at_ext; } tlv_ptr; tptr=pptr; eigrp_com_header = (const struct eigrp_common_header *)pptr; ND_TCHECK(*eigrp_com_header); /* * Sanity checking of the header. */ if (eigrp_com_header->version != EIGRP_VERSION) { ND_PRINT((ndo, "EIGRP version %u packet not supported",eigrp_com_header->version)); return; } /* in non-verbose mode just lets print the basic Message Type*/ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "EIGRP %s, length: %u", tok2str(eigrp_opcode_values, "unknown (%u)",eigrp_com_header->opcode), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ if (len < sizeof(struct eigrp_common_header)) { ND_PRINT((ndo, "EIGRP %s, length: %u (too short, < %u)", tok2str(eigrp_opcode_values, "unknown (%u)",eigrp_com_header->opcode), len, (u_int) sizeof(struct eigrp_common_header))); return; } tlen=len-sizeof(struct eigrp_common_header); /* FIXME print other header info */ ND_PRINT((ndo, "\n\tEIGRP v%u, opcode: %s (%u), chksum: 0x%04x, Flags: [%s]\n\tseq: 0x%08x, ack: 0x%08x, AS: %u, length: %u", eigrp_com_header->version, tok2str(eigrp_opcode_values, "unknown, type: %u",eigrp_com_header->opcode), eigrp_com_header->opcode, EXTRACT_16BITS(&eigrp_com_header->checksum), tok2str(eigrp_common_header_flag_values, "none", EXTRACT_32BITS(&eigrp_com_header->flags)), EXTRACT_32BITS(&eigrp_com_header->seq), EXTRACT_32BITS(&eigrp_com_header->ack), EXTRACT_32BITS(&eigrp_com_header->asn), tlen)); tptr+=sizeof(const struct eigrp_common_header); while(tlen>0) { /* did we capture enough for fully decoding the object header ? */ ND_TCHECK2(*tptr, sizeof(struct eigrp_tlv_header)); eigrp_tlv_header = (const struct eigrp_tlv_header *)tptr; eigrp_tlv_len=EXTRACT_16BITS(&eigrp_tlv_header->length); eigrp_tlv_type=EXTRACT_16BITS(&eigrp_tlv_header->type); if (eigrp_tlv_len < sizeof(struct eigrp_tlv_header) || eigrp_tlv_len > tlen) { print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ",tlen); return; } ND_PRINT((ndo, "\n\t %s TLV (0x%04x), length: %u", tok2str(eigrp_tlv_values, "Unknown", eigrp_tlv_type), eigrp_tlv_type, eigrp_tlv_len)); if (eigrp_tlv_len < sizeof(struct eigrp_tlv_header)) { ND_PRINT((ndo, " (too short, < %u)", (u_int) sizeof(struct eigrp_tlv_header))); break; } tlv_tptr=tptr+sizeof(struct eigrp_tlv_header); tlv_tlen=eigrp_tlv_len-sizeof(struct eigrp_tlv_header); /* did we capture enough for fully decoding the object ? */ ND_TCHECK2(*tptr, eigrp_tlv_len); switch(eigrp_tlv_type) { case EIGRP_TLV_GENERAL_PARM: tlv_ptr.eigrp_tlv_general_parm = (const struct eigrp_tlv_general_parm_t *)tlv_tptr; if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_general_parm)) { ND_PRINT((ndo, " (too short, < %u)", (u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_general_parm)))); break; } ND_PRINT((ndo, "\n\t holdtime: %us, k1 %u, k2 %u, k3 %u, k4 %u, k5 %u", EXTRACT_16BITS(tlv_ptr.eigrp_tlv_general_parm->holdtime), tlv_ptr.eigrp_tlv_general_parm->k1, tlv_ptr.eigrp_tlv_general_parm->k2, tlv_ptr.eigrp_tlv_general_parm->k3, tlv_ptr.eigrp_tlv_general_parm->k4, tlv_ptr.eigrp_tlv_general_parm->k5)); break; case EIGRP_TLV_SW_VERSION: tlv_ptr.eigrp_tlv_sw_version = (const struct eigrp_tlv_sw_version_t *)tlv_tptr; if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_sw_version)) { ND_PRINT((ndo, " (too short, < %u)", (u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_sw_version)))); break; } ND_PRINT((ndo, "\n\t IOS version: %u.%u, EIGRP version %u.%u", tlv_ptr.eigrp_tlv_sw_version->ios_major, tlv_ptr.eigrp_tlv_sw_version->ios_minor, tlv_ptr.eigrp_tlv_sw_version->eigrp_major, tlv_ptr.eigrp_tlv_sw_version->eigrp_minor)); break; case EIGRP_TLV_IP_INT: tlv_ptr.eigrp_tlv_ip_int = (const struct eigrp_tlv_ip_int_t *)tlv_tptr; if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_ip_int)) { ND_PRINT((ndo, " (too short, < %u)", (u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_ip_int)))); break; } bit_length = tlv_ptr.eigrp_tlv_ip_int->plen; if (bit_length > 32) { ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length)); break; } byte_length = (bit_length + 7) / 8; /* variable length encoding */ memset(prefix, 0, 4); memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_int->destination,byte_length); ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ", ipaddr_string(ndo, prefix), bit_length)); if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->nexthop) == 0) ND_PRINT((ndo, "self")); else ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_int->nexthop))); ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u", (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->delay)/100), EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_int->bandwidth), EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_int->mtu), tlv_ptr.eigrp_tlv_ip_int->hopcount, tlv_ptr.eigrp_tlv_ip_int->reliability, tlv_ptr.eigrp_tlv_ip_int->load)); break; case EIGRP_TLV_IP_EXT: tlv_ptr.eigrp_tlv_ip_ext = (const struct eigrp_tlv_ip_ext_t *)tlv_tptr; if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_ip_ext)) { ND_PRINT((ndo, " (too short, < %u)", (u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_ip_ext)))); break; } bit_length = tlv_ptr.eigrp_tlv_ip_ext->plen; if (bit_length > 32) { ND_PRINT((ndo, "\n\t illegal prefix length %u",bit_length)); break; } byte_length = (bit_length + 7) / 8; /* variable length encoding */ memset(prefix, 0, 4); memcpy(prefix,&tlv_ptr.eigrp_tlv_ip_ext->destination,byte_length); ND_PRINT((ndo, "\n\t IPv4 prefix: %15s/%u, nexthop: ", ipaddr_string(ndo, prefix), bit_length)); if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->nexthop) == 0) ND_PRINT((ndo, "self")); else ND_PRINT((ndo, "%s",ipaddr_string(ndo, &tlv_ptr.eigrp_tlv_ip_ext->nexthop))); ND_PRINT((ndo, "\n\t origin-router %s, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u", ipaddr_string(ndo, tlv_ptr.eigrp_tlv_ip_ext->origin_router), EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->origin_as), tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_ip_ext->proto_id), tlv_ptr.eigrp_tlv_ip_ext->flags, EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->tag), EXTRACT_32BITS(tlv_ptr.eigrp_tlv_ip_ext->metric))); ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u", (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->delay)/100), EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_ip_ext->bandwidth), EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_ip_ext->mtu), tlv_ptr.eigrp_tlv_ip_ext->hopcount, tlv_ptr.eigrp_tlv_ip_ext->reliability, tlv_ptr.eigrp_tlv_ip_ext->load)); break; case EIGRP_TLV_AT_CABLE_SETUP: tlv_ptr.eigrp_tlv_at_cable_setup = (const struct eigrp_tlv_at_cable_setup_t *)tlv_tptr; if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_at_cable_setup)) { ND_PRINT((ndo, " (too short, < %u)", (u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_at_cable_setup)))); break; } ND_PRINT((ndo, "\n\t Cable-range: %u-%u, Router-ID %u", EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_start), EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->cable_end), EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_cable_setup->router_id))); break; case EIGRP_TLV_AT_INT: tlv_ptr.eigrp_tlv_at_int = (const struct eigrp_tlv_at_int_t *)tlv_tptr; if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_at_int)) { ND_PRINT((ndo, " (too short, < %u)", (u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_at_int)))); break; } ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ", EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_start), EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->cable_end))); if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop) == 0) ND_PRINT((ndo, "self")); else ND_PRINT((ndo, "%u.%u", EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop), EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_int->nexthop[2]))); ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u", (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->delay)/100), EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_int->bandwidth), EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_int->mtu), tlv_ptr.eigrp_tlv_at_int->hopcount, tlv_ptr.eigrp_tlv_at_int->reliability, tlv_ptr.eigrp_tlv_at_int->load)); break; case EIGRP_TLV_AT_EXT: tlv_ptr.eigrp_tlv_at_ext = (const struct eigrp_tlv_at_ext_t *)tlv_tptr; if (tlv_tlen < sizeof(*tlv_ptr.eigrp_tlv_at_ext)) { ND_PRINT((ndo, " (too short, < %u)", (u_int) (sizeof(struct eigrp_tlv_header) + sizeof(*tlv_ptr.eigrp_tlv_at_ext)))); break; } ND_PRINT((ndo, "\n\t Cable-Range: %u-%u, nexthop: ", EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_start), EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->cable_end))); if (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop) == 0) ND_PRINT((ndo, "self")); else ND_PRINT((ndo, "%u.%u", EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop), EXTRACT_16BITS(&tlv_ptr.eigrp_tlv_at_ext->nexthop[2]))); ND_PRINT((ndo, "\n\t origin-router %u, origin-as %u, origin-proto %s, flags [0x%02x], tag 0x%08x, metric %u", EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_router), EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->origin_as), tok2str(eigrp_ext_proto_id_values,"unknown",tlv_ptr.eigrp_tlv_at_ext->proto_id), tlv_ptr.eigrp_tlv_at_ext->flags, EXTRACT_32BITS(tlv_ptr.eigrp_tlv_at_ext->tag), EXTRACT_16BITS(tlv_ptr.eigrp_tlv_at_ext->metric))); ND_PRINT((ndo, "\n\t delay %u ms, bandwidth %u Kbps, mtu %u, hop %u, reliability %u, load %u", (EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->delay)/100), EXTRACT_32BITS(&tlv_ptr.eigrp_tlv_at_ext->bandwidth), EXTRACT_24BITS(&tlv_ptr.eigrp_tlv_at_ext->mtu), tlv_ptr.eigrp_tlv_at_ext->hopcount, tlv_ptr.eigrp_tlv_at_ext->reliability, tlv_ptr.eigrp_tlv_at_ext->load)); break; /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case EIGRP_TLV_AUTH: case EIGRP_TLV_SEQ: case EIGRP_TLV_MCAST_SEQ: case EIGRP_TLV_IPX_INT: case EIGRP_TLV_IPX_EXT: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo,tlv_tptr,"\n\t ",tlv_tlen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag > 1) print_unknown_data(ndo,tptr+sizeof(struct eigrp_tlv_header),"\n\t ", eigrp_tlv_len-sizeof(struct eigrp_tlv_header)); tptr+=eigrp_tlv_len; tlen-=eigrp_tlv_len; } return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); }
28,118
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: inline void update_rq_clock(struct rq *rq) { if (!rq->skip_clock_update) { int cpu = cpu_of(rq); u64 irq_time; rq->clock = sched_clock_cpu(cpu); irq_time = irq_time_cpu(cpu); if (rq->clock - irq_time > rq->clock_task) rq->clock_task = rq->clock - irq_time; sched_irq_time_avg_update(rq, irq_time); } } Commit Message: Sched: fix skip_clock_update optimization idle_balance() drops/retakes rq->lock, leaving the previous task vulnerable to set_tsk_need_resched(). Clear it after we return from balancing instead, and in setup_thread_stack() as well, so no successfully descheduled or never scheduled task has it set. Need resched confused the skip_clock_update logic, which assumes that the next call to update_rq_clock() will come nearly immediately after being set. Make the optimization robust against the waking a sleeper before it sucessfully deschedules case by checking that the current task has not been dequeued before setting the flag, since it is that useless clock update we're trying to save, and clear unconditionally in schedule() proper instead of conditionally in put_prev_task(). Signed-off-by: Mike Galbraith <efault@gmx.de> Reported-by: Bjoern B. Brandenburg <bbb.lst@gmail.com> Tested-by: Yong Zhang <yong.zhang0@gmail.com> Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: stable@kernel.org LKML-Reference: <1291802742.1417.9.camel@marge.simson.net> Signed-off-by: Ingo Molnar <mingo@elte.hu> CWE ID:
inline void update_rq_clock(struct rq *rq) { int cpu = cpu_of(rq); u64 irq_time; if (rq->skip_clock_update) return; rq->clock = sched_clock_cpu(cpu); irq_time = irq_time_cpu(cpu); if (rq->clock - irq_time > rq->clock_task) rq->clock_task = rq->clock - irq_time; sched_irq_time_avg_update(rq, irq_time); }
23,369
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool DebuggerAttachFunction::RunAsync() { std::unique_ptr<Attach::Params> params(Attach::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); if (!InitAgentHost()) return false; if (!DevToolsAgentHost::IsSupportedProtocolVersion( params->required_version)) { error_ = ErrorUtils::FormatErrorMessage( keys::kProtocolVersionNotSupportedError, params->required_version); return false; } if (FindClientHost()) { FormatErrorMessage(keys::kAlreadyAttachedError); return false; } new ExtensionDevToolsClientHost(GetProfile(), agent_host_.get(), extension()->id(), extension()->name(), debuggee_); SendResponse(true); return true; } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. TBR=alexclarke@chromium.org Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <dgozman@chromium.org> Reviewed-by: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Nasko Oskov <nasko@chromium.org> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
bool DebuggerAttachFunction::RunAsync() { std::unique_ptr<Attach::Params> params(Attach::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); if (!InitAgentHost()) return false; if (!DevToolsAgentHost::IsSupportedProtocolVersion( params->required_version)) { error_ = ErrorUtils::FormatErrorMessage( keys::kProtocolVersionNotSupportedError, params->required_version); return false; } if (FindClientHost()) { FormatErrorMessage(keys::kAlreadyAttachedError); return false; } auto host = std::make_unique<ExtensionDevToolsClientHost>( GetProfile(), agent_host_.get(), extension()->id(), extension()->name(), debuggee_); if (!host->Attach()) { FormatErrorMessage(keys::kRestrictedError); return false; } host.release(); // An attached client host manages its own lifetime. SendResponse(true); return true; }
10,489
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: DefragIPv4TooLargeTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* Create a fragment that would extend past the max allowable size * for an IPv4 packet. */ p = BuildTestPacket(1, 8183, 0, 'A', 71); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; if (!ENGINE_ISSET_EVENT(p, IPV4_FRAG_PKT_TOO_LARGE)) goto end; /* The fragment should have been ignored so no fragments should have * been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragIPv4TooLargeTest(void) { DefragContext *dc = NULL; Packet *p = NULL; int ret = 0; DefragInit(); dc = DefragContextNew(); if (dc == NULL) goto end; /* Create a fragment that would extend past the max allowable size * for an IPv4 packet. */ p = BuildTestPacket(IPPROTO_ICMP, 1, 8183, 0, 'A', 71); if (p == NULL) goto end; /* We do not expect a packet returned. */ if (Defrag(NULL, NULL, p, NULL) != NULL) goto end; if (!ENGINE_ISSET_EVENT(p, IPV4_FRAG_PKT_TOO_LARGE)) goto end; /* The fragment should have been ignored so no fragments should have * been allocated from the pool. */ if (dc->frag_pool->outstanding != 0) return 0; ret = 1; end: if (dc != NULL) DefragContextDestroy(dc); if (p != NULL) SCFree(p); DefragDestroy(); return ret; }
13,577
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: error::Error GLES2DecoderPassthroughImpl::DoBeginQueryEXT( GLenum target, GLuint id, int32_t sync_shm_id, uint32_t sync_shm_offset) { GLuint service_id = GetQueryServiceID(id, &query_id_map_); QueryInfo* query_info = &query_info_map_[service_id]; scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id); if (!buffer) return error::kInvalidArguments; QuerySync* sync = static_cast<QuerySync*>( buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync))); if (!sync) return error::kOutOfBounds; if (IsEmulatedQueryTarget(target)) { if (active_queries_.find(target) != active_queries_.end()) { InsertError(GL_INVALID_OPERATION, "Query already active on target."); return error::kNoError; } if (id == 0) { InsertError(GL_INVALID_OPERATION, "Query id is 0."); return error::kNoError; } if (query_info->type != GL_NONE && query_info->type != target) { InsertError(GL_INVALID_OPERATION, "Query type does not match the target."); return error::kNoError; } } else { CheckErrorCallbackState(); api()->glBeginQueryFn(target, service_id); if (CheckErrorCallbackState()) { return error::kNoError; } } query_info->type = target; RemovePendingQuery(service_id); ActiveQuery query; query.service_id = service_id; query.shm = std::move(buffer); query.sync = sync; active_queries_[target] = std::move(query); return error::kNoError; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
error::Error GLES2DecoderPassthroughImpl::DoBeginQueryEXT( GLenum target, GLuint id, int32_t sync_shm_id, uint32_t sync_shm_offset) { GLuint service_id = GetQueryServiceID(id, &query_id_map_); QueryInfo* query_info = &query_info_map_[service_id]; scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id); if (!buffer) return error::kInvalidArguments; QuerySync* sync = static_cast<QuerySync*>( buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync))); if (!sync) return error::kOutOfBounds; if (target == GL_PROGRAM_COMPLETION_QUERY_CHROMIUM) { linking_program_service_id_ = 0u; } if (IsEmulatedQueryTarget(target)) { if (active_queries_.find(target) != active_queries_.end()) { InsertError(GL_INVALID_OPERATION, "Query already active on target."); return error::kNoError; } if (id == 0) { InsertError(GL_INVALID_OPERATION, "Query id is 0."); return error::kNoError; } if (query_info->type != GL_NONE && query_info->type != target) { InsertError(GL_INVALID_OPERATION, "Query type does not match the target."); return error::kNoError; } } else { CheckErrorCallbackState(); api()->glBeginQueryFn(target, service_id); if (CheckErrorCallbackState()) { return error::kNoError; } } query_info->type = target; RemovePendingQuery(service_id); ActiveQuery query; query.service_id = service_id; query.shm = std::move(buffer); query.sync = sync; active_queries_[target] = std::move(query); return error::kNoError; }
5,062
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; switch (ioctl) { case KVM_ARM_VCPU_INIT: { struct kvm_vcpu_init init; if (copy_from_user(&init, argp, sizeof(init))) return -EFAULT; return kvm_vcpu_set_target(vcpu, &init); } case KVM_SET_ONE_REG: case KVM_GET_ONE_REG: { struct kvm_one_reg reg; if (copy_from_user(&reg, argp, sizeof(reg))) return -EFAULT; if (ioctl == KVM_SET_ONE_REG) return kvm_arm_set_reg(vcpu, &reg); else return kvm_arm_get_reg(vcpu, &reg); } case KVM_GET_REG_LIST: { struct kvm_reg_list __user *user_list = argp; struct kvm_reg_list reg_list; unsigned n; if (copy_from_user(&reg_list, user_list, sizeof(reg_list))) return -EFAULT; n = reg_list.n; reg_list.n = kvm_arm_num_regs(vcpu); if (copy_to_user(user_list, &reg_list, sizeof(reg_list))) return -EFAULT; if (n < reg_list.n) return -E2BIG; return kvm_arm_copy_reg_indices(vcpu, user_list->reg); } default: return -EINVAL; } } Commit Message: ARM: KVM: prevent NULL pointer dereferences with KVM VCPU ioctl Some ARM KVM VCPU ioctls require the vCPU to be properly initialized with the KVM_ARM_VCPU_INIT ioctl before being used with further requests. KVM_RUN checks whether this initialization has been done, but other ioctls do not. Namely KVM_GET_REG_LIST will dereference an array with index -1 without initialization and thus leads to a kernel oops. Fix this by adding checks before executing the ioctl handlers. [ Removed superflous comment from static function - Christoffer ] Changes from v1: * moved check into a static function with a meaningful name Signed-off-by: Andre Przywara <andre.przywara@linaro.org> Signed-off-by: Christoffer Dall <cdall@cs.columbia.edu> CWE ID: CWE-399
long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; switch (ioctl) { case KVM_ARM_VCPU_INIT: { struct kvm_vcpu_init init; if (copy_from_user(&init, argp, sizeof(init))) return -EFAULT; return kvm_vcpu_set_target(vcpu, &init); } case KVM_SET_ONE_REG: case KVM_GET_ONE_REG: { struct kvm_one_reg reg; if (unlikely(!kvm_vcpu_initialized(vcpu))) return -ENOEXEC; if (copy_from_user(&reg, argp, sizeof(reg))) return -EFAULT; if (ioctl == KVM_SET_ONE_REG) return kvm_arm_set_reg(vcpu, &reg); else return kvm_arm_get_reg(vcpu, &reg); } case KVM_GET_REG_LIST: { struct kvm_reg_list __user *user_list = argp; struct kvm_reg_list reg_list; unsigned n; if (unlikely(!kvm_vcpu_initialized(vcpu))) return -ENOEXEC; if (copy_from_user(&reg_list, user_list, sizeof(reg_list))) return -EFAULT; n = reg_list.n; reg_list.n = kvm_arm_num_regs(vcpu); if (copy_to_user(user_list, &reg_list, sizeof(reg_list))) return -EFAULT; if (n < reg_list.n) return -E2BIG; return kvm_arm_copy_reg_indices(vcpu, user_list->reg); } default: return -EINVAL; } }
24,550
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void CopyFromOMX(const OMX_BUFFERHEADERTYPE *header) { if (!mIsBackup) { return; } sp<ABuffer> codec = getBuffer(header, false /* backup */, true /* limit */); memcpy((OMX_U8 *)mMem->pointer() + header->nOffset, codec->data(), codec->size()); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
void CopyFromOMX(const OMX_BUFFERHEADERTYPE *header) { if (!mCopyFromOmx) { return; } sp<ABuffer> codec = getBuffer(header, false /* backup */, true /* limit */); memcpy((OMX_U8 *)mMem->pointer() + header->nOffset, codec->data(), codec->size()); }
25,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void ConnectPanelServiceSignals() { if (!ibus_) { return; } IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (!ibus_panel_service) { LOG(ERROR) << "IBusPanelService is NOT available."; return; } g_signal_connect(ibus_panel_service, "focus-in", G_CALLBACK(FocusInCallback), this); g_signal_connect(ibus_panel_service, "register-properties", G_CALLBACK(RegisterPropertiesCallback), this); g_signal_connect(ibus_panel_service, "update-property", G_CALLBACK(UpdatePropertyCallback), this); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ConnectPanelServiceSignals() { if (!ibus_) { return; } IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE( g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey)); if (!ibus_panel_service) { LOG(ERROR) << "IBusPanelService is NOT available."; return; } g_signal_connect(ibus_panel_service, "focus-in", G_CALLBACK(FocusInThunk), this); g_signal_connect(ibus_panel_service, "register-properties", G_CALLBACK(RegisterPropertiesThunk), this); g_signal_connect(ibus_panel_service, "update-property", G_CALLBACK(UpdatePropertyThunk), this); }
20,263
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void WebGL2RenderingContextBase::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLintptr offset) { if (isContextLost()) return; if (!ValidateTexture2DBinding("texSubImage2D", target)) return; if (!bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage2D", "no bound PIXEL_UNPACK_BUFFER"); return; } if (!ValidateTexFunc("texSubImage2D", kTexSubImage, kSourceUnpackBuffer, target, level, 0, width, height, 1, 0, format, type, xoffset, yoffset, 0)) return; if (!ValidateValueFitNonNegInt32("texSubImage2D", "offset", offset)) return; ContextGL()->TexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, reinterpret_cast<const void*>(offset)); } Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA. BUG=774174 TEST=https://github.com/KhronosGroup/WebGL/pull/2555 R=kbr@chromium.org Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I4f4e7636314502451104730501a5048a5d7b9f3f Reviewed-on: https://chromium-review.googlesource.com/808665 Commit-Queue: Zhenyao Mo <zmo@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#522003} CWE ID: CWE-125
void WebGL2RenderingContextBase::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLintptr offset) { if (isContextLost()) return; if (!ValidateTexture2DBinding("texSubImage2D", target)) return; if (!bound_pixel_unpack_buffer_) { SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage2D", "no bound PIXEL_UNPACK_BUFFER"); return; } if (unpack_flip_y_ || unpack_premultiply_alpha_) { SynthesizeGLError( GL_INVALID_OPERATION, "texSubImage2D", "FLIP_Y or PREMULTIPLY_ALPHA isn't allowed while uploading from PBO"); return; } if (!ValidateTexFunc("texSubImage2D", kTexSubImage, kSourceUnpackBuffer, target, level, 0, width, height, 1, 0, format, type, xoffset, yoffset, 0)) return; if (!ValidateValueFitNonNegInt32("texSubImage2D", "offset", offset)) return; ContextGL()->TexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, reinterpret_cast<const void*>(offset)); }
23,926
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void MediaStreamManager::StopStreamDevice(int render_process_id, int render_frame_id, const std::string& device_id, int session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "StopStreamDevice({render_frame_id = " << render_frame_id << "} " << ", {device_id = " << device_id << "}, session_id = " << session_id << "})"; Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <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} CWE ID: CWE-189
void MediaStreamManager::StopStreamDevice(int render_process_id, int render_frame_id, int requester_id, const std::string& device_id, int session_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DVLOG(1) << "StopStreamDevice({render_frame_id = " << render_frame_id << "} " << ", {device_id = " << device_id << "}, session_id = " << session_id << "})";
8,515
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_p_b_slice(dec_state_t *ps_dec) { WORD16 *pi2_vld_out; UWORD32 i; yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf; UWORD32 u4_frm_offset = 0; const dec_mb_params_t *ps_dec_mb_params; IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; pi2_vld_out = ps_dec->ai2_vld_buf; memset(ps_dec->ai2_pred_mv,0,sizeof(ps_dec->ai2_pred_mv)); ps_dec->u2_prev_intra_mb = 0; ps_dec->u2_first_mb = 1; ps_dec->u2_picture_width = ps_dec->u2_frame_width; if(ps_dec->u2_picture_structure != FRAME_PICTURE) { ps_dec->u2_picture_width <<= 1; if(ps_dec->u2_picture_structure == BOTTOM_FIELD) { u4_frm_offset = ps_dec->u2_frame_width; } } do { UWORD32 u4_x_offset, u4_y_offset; WORD32 ret; UWORD32 u4_x_dst_offset = 0; UWORD32 u4_y_dst_offset = 0; UWORD8 *pu1_out_p; UWORD8 *pu1_pred; WORD32 u4_pred_strd; IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); if(ps_dec->e_pic_type == B_PIC) ret = impeg2d_dec_pnb_mb_params(ps_dec); else ret = impeg2d_dec_p_mb_params(ps_dec); if(ret) return IMPEG2D_MB_TEX_DECODE_ERR; IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); u4_y_dst_offset = (ps_dec->u2_mb_y << 4) * ps_dec->u2_picture_width; pu1_out_p = ps_cur_frm_buf->pu1_y + u4_x_dst_offset + u4_y_dst_offset; if(ps_dec->u2_prev_intra_mb == 0) { UWORD32 offset_x, offset_y, stride; UWORD16 index = (ps_dec->u2_motion_type); /*only for non intra mb's*/ if(ps_dec->e_mb_pred == BIDIRECT) { ps_dec_mb_params = &ps_dec->ps_func_bi_direct[index]; } else { ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index]; } stride = ps_dec->u2_picture_width; offset_x = u4_frm_offset + (ps_dec->u2_mb_x << 4); offset_y = (ps_dec->u2_mb_y << 4); ps_dec->s_dest_buf.pu1_y = ps_cur_frm_buf->pu1_y + offset_y * stride + offset_x; stride = stride >> 1; ps_dec->s_dest_buf.pu1_u = ps_cur_frm_buf->pu1_u + (offset_y >> 1) * stride + (offset_x >> 1); ps_dec->s_dest_buf.pu1_v = ps_cur_frm_buf->pu1_v + (offset_y >> 1) * stride + (offset_x >> 1); PROFILE_DISABLE_MC_IF0 ps_dec_mb_params->pf_mc(ps_dec); } for(i = 0; i < NUM_LUMA_BLKS; ++i) { if((ps_dec->u2_cbp & (1 << (BLOCKS_IN_MB - 1 - i))) != 0) { e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, Y_LUMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } u4_x_offset = gai2_impeg2_blk_x_off[i]; if(ps_dec->u2_field_dct == 0) u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ; else u4_y_offset = gai2_impeg2_blk_y_off_fld[i] ; IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset; u4_pred_strd = ps_dec->u2_picture_width << ps_dec->u2_field_dct; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset, 8, u4_pred_strd, ps_dec->u2_picture_width << ps_dec->u2_field_dct, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } } /* For U and V blocks, divide the x and y offsets by 2. */ u4_x_dst_offset >>= 1; u4_y_dst_offset >>= 2; /* In case of chrominance blocks the DCT will be frame DCT */ /* i = 0, U component and i = 1 is V componet */ if((ps_dec->u2_cbp & 0x02) != 0) { pu1_out_p = ps_cur_frm_buf->pu1_u + u4_x_dst_offset + u4_y_dst_offset; e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, U_CHROMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p; u4_pred_strd = ps_dec->u2_picture_width >> 1; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p, 8, u4_pred_strd, ps_dec->u2_picture_width >> 1, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } if((ps_dec->u2_cbp & 0x01) != 0) { pu1_out_p = ps_cur_frm_buf->pu1_v + u4_x_dst_offset + u4_y_dst_offset; e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, V_CHROMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p; u4_pred_strd = ps_dec->u2_picture_width >> 1; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p, 8, u4_pred_strd, ps_dec->u2_picture_width >> 1, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } ps_dec->u2_num_mbs_left--; ps_dec->u2_first_mb = 0; ps_dec->u2_mb_x++; if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset) { return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; } else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb) { ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y++; } } while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0); return e_error; } Commit Message: Fixed Memory Overflow Errors In function impeg2d_dec_p_b_slice, there was no check for num_mbs_left == 0 after skip_mbs function call. Hence, even though it should have returned as an error, it goes ahead to decode the frame and writes beyond the buffer allocated for output. Put a check for the same. Bug: 38207066 Test: before/after execution of PoC on angler/nyc-mr2-dev Change-Id: If4b7bea51032bf2fe2edd03f64a68847aa4f6a00 (cherry picked from commit 2df080153464bf57084d68ba3594e199bc140eb4) CWE ID: CWE-119
IMPEG2D_ERROR_CODES_T impeg2d_dec_p_b_slice(dec_state_t *ps_dec) { WORD16 *pi2_vld_out; UWORD32 i; yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf; UWORD32 u4_frm_offset = 0; const dec_mb_params_t *ps_dec_mb_params; IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; pi2_vld_out = ps_dec->ai2_vld_buf; memset(ps_dec->ai2_pred_mv,0,sizeof(ps_dec->ai2_pred_mv)); ps_dec->u2_prev_intra_mb = 0; ps_dec->u2_first_mb = 1; ps_dec->u2_picture_width = ps_dec->u2_frame_width; if(ps_dec->u2_picture_structure != FRAME_PICTURE) { ps_dec->u2_picture_width <<= 1; if(ps_dec->u2_picture_structure == BOTTOM_FIELD) { u4_frm_offset = ps_dec->u2_frame_width; } } do { UWORD32 u4_x_offset, u4_y_offset; WORD32 ret; UWORD32 u4_x_dst_offset = 0; UWORD32 u4_y_dst_offset = 0; UWORD8 *pu1_out_p; UWORD8 *pu1_pred; WORD32 u4_pred_strd; IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); if(ps_dec->e_pic_type == B_PIC) ret = impeg2d_dec_pnb_mb_params(ps_dec); else ret = impeg2d_dec_p_mb_params(ps_dec); if(ret) return IMPEG2D_MB_TEX_DECODE_ERR; if(0 >= ps_dec->u2_num_mbs_left) { break; } IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); u4_y_dst_offset = (ps_dec->u2_mb_y << 4) * ps_dec->u2_picture_width; pu1_out_p = ps_cur_frm_buf->pu1_y + u4_x_dst_offset + u4_y_dst_offset; if(ps_dec->u2_prev_intra_mb == 0) { UWORD32 offset_x, offset_y, stride; UWORD16 index = (ps_dec->u2_motion_type); /*only for non intra mb's*/ if(ps_dec->e_mb_pred == BIDIRECT) { ps_dec_mb_params = &ps_dec->ps_func_bi_direct[index]; } else { ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index]; } stride = ps_dec->u2_picture_width; offset_x = u4_frm_offset + (ps_dec->u2_mb_x << 4); offset_y = (ps_dec->u2_mb_y << 4); ps_dec->s_dest_buf.pu1_y = ps_cur_frm_buf->pu1_y + offset_y * stride + offset_x; stride = stride >> 1; ps_dec->s_dest_buf.pu1_u = ps_cur_frm_buf->pu1_u + (offset_y >> 1) * stride + (offset_x >> 1); ps_dec->s_dest_buf.pu1_v = ps_cur_frm_buf->pu1_v + (offset_y >> 1) * stride + (offset_x >> 1); PROFILE_DISABLE_MC_IF0 ps_dec_mb_params->pf_mc(ps_dec); } for(i = 0; i < NUM_LUMA_BLKS; ++i) { if((ps_dec->u2_cbp & (1 << (BLOCKS_IN_MB - 1 - i))) != 0) { e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, Y_LUMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } u4_x_offset = gai2_impeg2_blk_x_off[i]; if(ps_dec->u2_field_dct == 0) u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ; else u4_y_offset = gai2_impeg2_blk_y_off_fld[i] ; IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset; u4_pred_strd = ps_dec->u2_picture_width << ps_dec->u2_field_dct; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset, 8, u4_pred_strd, ps_dec->u2_picture_width << ps_dec->u2_field_dct, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } } /* For U and V blocks, divide the x and y offsets by 2. */ u4_x_dst_offset >>= 1; u4_y_dst_offset >>= 2; /* In case of chrominance blocks the DCT will be frame DCT */ /* i = 0, U component and i = 1 is V componet */ if((ps_dec->u2_cbp & 0x02) != 0) { pu1_out_p = ps_cur_frm_buf->pu1_u + u4_x_dst_offset + u4_y_dst_offset; e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, U_CHROMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p; u4_pred_strd = ps_dec->u2_picture_width >> 1; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p, 8, u4_pred_strd, ps_dec->u2_picture_width >> 1, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } if((ps_dec->u2_cbp & 0x01) != 0) { pu1_out_p = ps_cur_frm_buf->pu1_v + u4_x_dst_offset + u4_y_dst_offset; e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, ps_dec->u2_prev_intra_mb, V_CHROMA, 0); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); PROFILE_DISABLE_IDCT_IF0 { WORD32 idx; if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) idx = 0; else idx = 1; if(0 == ps_dec->u2_prev_intra_mb) { pu1_pred = pu1_out_p; u4_pred_strd = ps_dec->u2_picture_width >> 1; } else { pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; u4_pred_strd = 8; } ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, ps_dec->ai2_idct_stg1, pu1_pred, pu1_out_p, 8, u4_pred_strd, ps_dec->u2_picture_width >> 1, ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); } } ps_dec->u2_num_mbs_left--; ps_dec->u2_first_mb = 0; ps_dec->u2_mb_x++; if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset) { return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; } else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb) { ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y++; } } while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0); return e_error; }
11,505
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void WebContentsImpl::AttachInterstitialPage( InterstitialPageImpl* interstitial_page) { DCHECK(interstitial_page); GetRenderManager()->set_interstitial_page(interstitial_page); CancelActiveAndPendingDialogs(); for (auto& observer : observers_) observer.DidAttachInterstitialPage(); if (frame_tree_.IsLoading()) LoadingStateChanged(true, true, nullptr); if (node_.OuterContentsFrameTreeNode()) { if (GetRenderManager()->GetProxyToOuterDelegate()) { DCHECK( static_cast<RenderWidgetHostViewBase*>(interstitial_page->GetView()) ->IsRenderWidgetHostViewChildFrame()); RenderWidgetHostViewChildFrame* view = static_cast<RenderWidgetHostViewChildFrame*>( interstitial_page->GetView()); GetRenderManager()->SetRWHViewForInnerContents(view); } } } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
void WebContentsImpl::AttachInterstitialPage( InterstitialPageImpl* interstitial_page) { DCHECK(!interstitial_page_ && interstitial_page); interstitial_page_ = interstitial_page; CancelActiveAndPendingDialogs(); for (auto& observer : observers_) observer.DidAttachInterstitialPage(); if (frame_tree_.IsLoading()) LoadingStateChanged(true, true, nullptr); if (node_.OuterContentsFrameTreeNode()) { if (GetRenderManager()->GetProxyToOuterDelegate()) { DCHECK( static_cast<RenderWidgetHostViewBase*>(interstitial_page->GetView()) ->IsRenderWidgetHostViewChildFrame()); RenderWidgetHostViewChildFrame* view = static_cast<RenderWidgetHostViewChildFrame*>( interstitial_page->GetView()); GetRenderManager()->SetRWHViewForInnerContents(view); } } }
5,984
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void FileAPIMessageFilter::OnCreateSnapshotFile( int request_id, const GURL& blob_url, const GURL& path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); FileSystemURL url(path); base::Callback<void(const FilePath&)> register_file_callback = base::Bind(&FileAPIMessageFilter::RegisterFileAsBlob, this, blob_url, url.path()); FileSystemOperation* operation = GetNewOperation(url, request_id); if (!operation) return; operation->CreateSnapshotFile( url, base::Bind(&FileAPIMessageFilter::DidCreateSnapshot, this, request_id, register_file_callback)); } Commit Message: File permission fix: now we selectively grant read permission for Sandboxed files We also need to check the read permission and call GrantReadFile() for sandboxed files for CreateSnapshotFile(). BUG=162114 TEST=manual Review URL: https://codereview.chromium.org/11280231 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@170181 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void FileAPIMessageFilter::OnCreateSnapshotFile( int request_id, const GURL& blob_url, const GURL& path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); FileSystemURL url(path); base::Callback<void(const FilePath&)> register_file_callback = base::Bind(&FileAPIMessageFilter::RegisterFileAsBlob, this, blob_url, url); // Make sure if this file can be read by the renderer as this is // called when the renderer is about to create a new File object // (for reading the file). base::PlatformFileError error; if (!HasPermissionsForFile(url, kReadFilePermissions, &error)) { Send(new FileSystemMsg_DidFail(request_id, error)); return; } FileSystemOperation* operation = GetNewOperation(url, request_id); if (!operation) return; operation->CreateSnapshotFile( url, base::Bind(&FileAPIMessageFilter::DidCreateSnapshot, this, request_id, register_file_callback)); }
21,854
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void CairoOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, 1, 1); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmalloc (row_stride * maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int x, y; int invert_bit; invert_bit = maskInvert ? 1 : 0; for (y = 0; y < maskHeight; y++) { pix = maskImgStr->getLine(); maskDest = maskBuffer + y * row_stride; for (x = 0; x < maskWidth; x++) { if (pix[x] ^ invert_bit) *maskDest++ = 0; else *maskDest++ = 255; } } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; int is_identity_transform; buffer = (unsigned char *)gmalloc (width * height * 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf ("drawMaskedImage %dx%d\n", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); /* scale the mask to the size of the image unlike softMask */ cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &matrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; } Commit Message: CWE ID: CWE-189
void CairoOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, 1, 1); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmallocn (row_stride, maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int x, y; int invert_bit; invert_bit = maskInvert ? 1 : 0; for (y = 0; y < maskHeight; y++) { pix = maskImgStr->getLine(); maskDest = maskBuffer + y * row_stride; for (x = 0; x < maskWidth; x++) { if (pix[x] ^ invert_bit) *maskDest++ = 0; else *maskDest++ = 255; } } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; int is_identity_transform; buffer = (unsigned char *)gmallocn3 (width, height, 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf ("drawMaskedImage %dx%d\n", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); /* scale the mask to the size of the image unlike softMask */ cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &matrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; }
22,592
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: VP8XChunk::VP8XChunk(Container* parent) : Chunk(parent, kChunk_VP8X) { this->needsRewrite = true; this->size = 10; this->data.resize(this->size); this->data.assign(this->size, 0); XMP_Uns8* bitstream = (XMP_Uns8*)parent->chunks[WEBP_CHUNK_IMAGE][0]->data.data(); XMP_Uns32 width = ((bitstream[7] << 8) | bitstream[6]) & 0x3fff; XMP_Uns32 height = ((bitstream[9] << 8) | bitstream[8]) & 0x3fff; this->width(width); this->height(height); parent->vp8x = this; VP8XChunk::VP8XChunk(Container* parent, WEBP_MetaHandler* handler) : Chunk(parent, handler) { this->size = 10; this->needsRewrite = true; parent->vp8x = this; } XMP_Uns32 VP8XChunk::width() { return GetLE24(&this->data[4]) + 1; } void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val > 0 ? val - 1 : 0); } XMP_Uns32 VP8XChunk::height() { return GetLE24(&this->data[7]) + 1; } void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val > 0 ? val - 1 : 0); } bool VP8XChunk::xmp() { XMP_Uns32 flags = GetLE32(&this->data[0]); return (bool)((flags >> XMP_FLAG_BIT) & 1); } void VP8XChunk::xmp(bool hasXMP) { XMP_Uns32 flags = GetLE32(&this->data[0]); flags ^= (-hasXMP ^ flags) & (1 << XMP_FLAG_BIT); PutLE32(&this->data[0], flags); } Container::Container(WEBP_MetaHandler* handler) : Chunk(NULL, handler) { this->needsRewrite = false; XMP_IO* file = handler->parent->ioRef; file->Seek(12, kXMP_SeekFromStart); XMP_Int64 size = handler->initialFileSize; XMP_Uns32 peek = 0; while (file->Offset() < size) { peek = XIO::PeekUns32_LE(file); switch (peek) { case kChunk_XMP_: this->addChunk(new XMPChunk(this, handler)); break; case kChunk_VP8X: this->addChunk(new VP8XChunk(this, handler)); break; default: this->addChunk(new Chunk(this, handler)); break; } } if (this->chunks[WEBP_CHUNK_IMAGE].size() == 0) { XMP_Throw("File has no image bitstream", kXMPErr_BadFileFormat); } if (this->chunks[WEBP_CHUNK_VP8X].size() == 0) { this->needsRewrite = true; this->addChunk(new VP8XChunk(this)); } if (this->chunks[WEBP_CHUNK_XMP].size() == 0) { XMPChunk* xmpChunk = new XMPChunk(this); this->addChunk(xmpChunk); handler->xmpChunk = xmpChunk; this->vp8x->xmp(true); } } Chunk* Container::getExifChunk() { if (this->chunks[WEBP::WEBP_CHUNK_EXIF].size() == 0) { return NULL; } return this->chunks[WEBP::WEBP_CHUNK_EXIF][0]; } void Container::addChunk(Chunk* chunk) { ChunkId idx; try { idx = chunkMap.at(chunk->tag); } catch (const std::out_of_range& e) { idx = WEBP_CHUNK_UNKNOWN; } this->chunks[idx].push_back(chunk); } void Container::write(WEBP_MetaHandler* handler) { XMP_IO* file = handler->parent->ioRef; file->Rewind(); XIO::WriteUns32_LE(file, this->tag); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); XIO::WriteUns32_LE(file, kChunk_WEBP); size_t i, j; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; for (j = 0; j < chunkVect.size(); j++) { chunkVect.at(j)->write(handler); } } XMP_Int64 lastOffset = file->Offset(); this->size = lastOffset - 8; file->Seek(this->pos + 4, kXMP_SeekFromStart); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); file->Seek(lastOffset, kXMP_SeekFromStart); if (lastOffset < handler->initialFileSize) { file->Truncate(lastOffset); } } Container::~Container() { Chunk* chunk; size_t i; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; while (!chunkVect.empty()) { chunk = chunkVect.back(); delete chunk; chunkVect.pop_back(); } } } } Commit Message: CWE ID: CWE-476
VP8XChunk::VP8XChunk(Container* parent) : Chunk(parent, kChunk_VP8X) { this->needsRewrite = true; this->size = 10; this->data.resize(this->size); this->data.assign(this->size, 0); XMP_Uns8* bitstream = (XMP_Uns8*)parent->chunks[WEBP_CHUNK_IMAGE][0]->data.data(); // See bug https://bugs.freedesktop.org/show_bug.cgi?id=105247 // bitstream could be NULL. XMP_Uns32 width = bitstream ? ((bitstream[7] << 8) | bitstream[6]) & 0x3fff : 0; XMP_Uns32 height = bitstream ? ((bitstream[9] << 8) | bitstream[8]) & 0x3fff : 0; this->width(width); this->height(height); parent->vp8x = this; VP8XChunk::VP8XChunk(Container* parent, WEBP_MetaHandler* handler) : Chunk(parent, handler) { this->size = 10; this->needsRewrite = true; parent->vp8x = this; } XMP_Uns32 VP8XChunk::width() { return GetLE24(&this->data[4]) + 1; } void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val > 0 ? val - 1 : 0); } XMP_Uns32 VP8XChunk::height() { return GetLE24(&this->data[7]) + 1; } void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val > 0 ? val - 1 : 0); } bool VP8XChunk::xmp() { XMP_Uns32 flags = GetLE32(&this->data[0]); return (bool)((flags >> XMP_FLAG_BIT) & 1); } void VP8XChunk::xmp(bool hasXMP) { XMP_Uns32 flags = GetLE32(&this->data[0]); flags ^= (-hasXMP ^ flags) & (1 << XMP_FLAG_BIT); PutLE32(&this->data[0], flags); } Container::Container(WEBP_MetaHandler* handler) : Chunk(NULL, handler) { this->needsRewrite = false; XMP_IO* file = handler->parent->ioRef; file->Seek(12, kXMP_SeekFromStart); XMP_Int64 size = handler->initialFileSize; XMP_Uns32 peek = 0; while (file->Offset() < size) { peek = XIO::PeekUns32_LE(file); switch (peek) { case kChunk_XMP_: this->addChunk(new XMPChunk(this, handler)); break; case kChunk_VP8X: this->addChunk(new VP8XChunk(this, handler)); break; default: this->addChunk(new Chunk(this, handler)); break; } } if (this->chunks[WEBP_CHUNK_IMAGE].size() == 0) { XMP_Throw("File has no image bitstream", kXMPErr_BadFileFormat); } if (this->chunks[WEBP_CHUNK_VP8X].size() == 0) { this->needsRewrite = true; this->addChunk(new VP8XChunk(this)); } if (this->chunks[WEBP_CHUNK_XMP].size() == 0) { XMPChunk* xmpChunk = new XMPChunk(this); this->addChunk(xmpChunk); handler->xmpChunk = xmpChunk; this->vp8x->xmp(true); } } Chunk* Container::getExifChunk() { if (this->chunks[WEBP::WEBP_CHUNK_EXIF].size() == 0) { return NULL; } return this->chunks[WEBP::WEBP_CHUNK_EXIF][0]; } void Container::addChunk(Chunk* chunk) { ChunkId idx; try { idx = chunkMap.at(chunk->tag); } catch (const std::out_of_range& e) { idx = WEBP_CHUNK_UNKNOWN; } this->chunks[idx].push_back(chunk); } void Container::write(WEBP_MetaHandler* handler) { XMP_IO* file = handler->parent->ioRef; file->Rewind(); XIO::WriteUns32_LE(file, this->tag); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); XIO::WriteUns32_LE(file, kChunk_WEBP); size_t i, j; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; for (j = 0; j < chunkVect.size(); j++) { chunkVect.at(j)->write(handler); } } XMP_Int64 lastOffset = file->Offset(); this->size = lastOffset - 8; file->Seek(this->pos + 4, kXMP_SeekFromStart); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); file->Seek(lastOffset, kXMP_SeekFromStart); if (lastOffset < handler->initialFileSize) { file->Truncate(lastOffset); } } Container::~Container() { Chunk* chunk; size_t i; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; while (!chunkVect.empty()) { chunk = chunkVect.back(); delete chunk; chunkVect.pop_back(); } } } }
20,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int decode_level3_header(LHAFileHeader **header, LHAInputStream *stream) { unsigned int header_len; if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) { return 0; } if (!extend_raw_data(header, stream, LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) { return 0; } header_len = lha_decode_uint32(&RAW_DATA(header, 24)); if (header_len > LEVEL_3_MAX_HEADER_LEN) { return 0; } if (!extend_raw_data(header, stream, header_len - RAW_DATA_LEN(header))) { return 0; } memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5); (*header)->compress_method[5] = '\0'; (*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7)); (*header)->length = lha_decode_uint32(&RAW_DATA(header, 11)); (*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15)); (*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21)); (*header)->os_type = RAW_DATA(header, 23); if (!decode_extended_headers(header, 28)) { return 0; } return 1; } Commit Message: Fix integer underflow vulnerability in L3 decode. Marcin 'Icewall' Noga of Cisco TALOS discovered that the level 3 header decoding routines were vulnerable to an integer underflow, if the 32-bit header length was less than the base level 3 header length. This could lead to an exploitable heap corruption condition. Thanks go to Marcin Noga and Regina Wilson of Cisco TALOS for reporting this vulnerability. CWE ID: CWE-190
static int decode_level3_header(LHAFileHeader **header, LHAInputStream *stream) { unsigned int header_len; if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) { return 0; } if (!extend_raw_data(header, stream, LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) { return 0; } header_len = lha_decode_uint32(&RAW_DATA(header, 24)); if (header_len > LEVEL_3_MAX_HEADER_LEN || header_len < RAW_DATA_LEN(header)) { return 0; } if (!extend_raw_data(header, stream, header_len - RAW_DATA_LEN(header))) { return 0; } memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5); (*header)->compress_method[5] = '\0'; (*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7)); (*header)->length = lha_decode_uint32(&RAW_DATA(header, 11)); (*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15)); (*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21)); (*header)->os_type = RAW_DATA(header, 23); if (!decode_extended_headers(header, 28)) { return 0; } return 1; }
29,903
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void WebGLRenderingContextBase::TexImageHelperHTMLVideoElement( const SecurityOrigin* security_origin, TexImageFunctionID function_id, GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, GLint xoffset, GLint yoffset, GLint zoffset, HTMLVideoElement* video, const IntRect& source_image_rect, GLsizei depth, GLint unpack_image_height, ExceptionState& exception_state) { const char* func_name = GetTexImageFunctionName(function_id); if (isContextLost()) return; if (!ValidateHTMLVideoElement(security_origin, func_name, video, exception_state)) return; WebGLTexture* texture = ValidateTexImageBinding(func_name, function_id, target); if (!texture) return; TexImageFunctionType function_type; if (function_id == kTexImage2D || function_id == kTexImage3D) function_type = kTexImage; else function_type = kTexSubImage; if (!ValidateTexFunc(func_name, function_type, kSourceHTMLVideoElement, target, level, internalformat, video->videoWidth(), video->videoHeight(), 1, 0, format, type, xoffset, yoffset, zoffset)) return; WebMediaPlayer::VideoFrameUploadMetadata frame_metadata = {}; int already_uploaded_id = -1; WebMediaPlayer::VideoFrameUploadMetadata* frame_metadata_ptr = nullptr; if (RuntimeEnabledFeatures::ExperimentalCanvasFeaturesEnabled()) { already_uploaded_id = texture->GetLastUploadedVideoFrameId(); frame_metadata_ptr = &frame_metadata; } bool source_image_rect_is_default = source_image_rect == SentinelEmptyRect() || source_image_rect == IntRect(0, 0, video->videoWidth(), video->videoHeight()); const bool use_copyTextureCHROMIUM = function_id == kTexImage2D && source_image_rect_is_default && depth == 1 && GL_TEXTURE_2D == target && CanUseTexImageByGPU(format, type); if (use_copyTextureCHROMIUM) { DCHECK_EQ(xoffset, 0); DCHECK_EQ(yoffset, 0); DCHECK_EQ(zoffset, 0); if (video->CopyVideoTextureToPlatformTexture( ContextGL(), target, texture->Object(), internalformat, format, type, level, unpack_premultiply_alpha_, unpack_flip_y_, already_uploaded_id, frame_metadata_ptr)) { texture->UpdateLastUploadedFrame(frame_metadata); return; } } if (source_image_rect_is_default) { ScopedUnpackParametersResetRestore( this, unpack_flip_y_ || unpack_premultiply_alpha_); if (video->TexImageImpl( static_cast<WebMediaPlayer::TexImageFunctionID>(function_id), target, ContextGL(), texture->Object(), level, ConvertTexInternalFormat(internalformat, type), format, type, xoffset, yoffset, zoffset, unpack_flip_y_, unpack_premultiply_alpha_ && unpack_colorspace_conversion_ == GL_NONE)) { texture->ClearLastUploadedFrame(); return; } } if (use_copyTextureCHROMIUM) { std::unique_ptr<ImageBufferSurface> surface = WTF::WrapUnique(new AcceleratedImageBufferSurface( IntSize(video->videoWidth(), video->videoHeight()))); if (surface->IsValid()) { std::unique_ptr<ImageBuffer> image_buffer( ImageBuffer::Create(std::move(surface))); if (image_buffer) { video->PaintCurrentFrame( image_buffer->Canvas(), IntRect(0, 0, video->videoWidth(), video->videoHeight()), nullptr, already_uploaded_id, frame_metadata_ptr); TexImage2DBase(target, level, internalformat, video->videoWidth(), video->videoHeight(), 0, format, type, nullptr); if (image_buffer->CopyToPlatformTexture( FunctionIDToSnapshotReason(function_id), ContextGL(), target, texture->Object(), unpack_premultiply_alpha_, unpack_flip_y_, IntPoint(0, 0), IntRect(0, 0, video->videoWidth(), video->videoHeight()))) { texture->UpdateLastUploadedFrame(frame_metadata); return; } } } } scoped_refptr<Image> image = VideoFrameToImage(video, already_uploaded_id, frame_metadata_ptr); if (!image) return; TexImageImpl(function_id, target, level, internalformat, xoffset, yoffset, zoffset, format, type, image.get(), WebGLImageConversion::kHtmlDomVideo, unpack_flip_y_, unpack_premultiply_alpha_, source_image_rect, depth, unpack_image_height); texture->UpdateLastUploadedFrame(frame_metadata); } Commit Message: Tighten about IntRect use in WebGL with overflow detection BUG=784183 TEST=test case in the bug in ASAN build R=kbr@chromium.org Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: Ie25ca328af99de7828e28e6a6e3d775f1bebc43f Reviewed-on: https://chromium-review.googlesource.com/811826 Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#522213} CWE ID: CWE-125
void WebGLRenderingContextBase::TexImageHelperHTMLVideoElement( const SecurityOrigin* security_origin, TexImageFunctionID function_id, GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, GLint xoffset, GLint yoffset, GLint zoffset, HTMLVideoElement* video, const IntRect& source_image_rect, GLsizei depth, GLint unpack_image_height, ExceptionState& exception_state) { const char* func_name = GetTexImageFunctionName(function_id); if (isContextLost()) return; if (!ValidateHTMLVideoElement(security_origin, func_name, video, exception_state)) return; WebGLTexture* texture = ValidateTexImageBinding(func_name, function_id, target); if (!texture) return; TexImageFunctionType function_type; if (function_id == kTexImage2D || function_id == kTexImage3D) function_type = kTexImage; else function_type = kTexSubImage; if (!ValidateTexFunc(func_name, function_type, kSourceHTMLVideoElement, target, level, internalformat, video->videoWidth(), video->videoHeight(), 1, 0, format, type, xoffset, yoffset, zoffset)) return; WebMediaPlayer::VideoFrameUploadMetadata frame_metadata = {}; int already_uploaded_id = -1; WebMediaPlayer::VideoFrameUploadMetadata* frame_metadata_ptr = nullptr; if (RuntimeEnabledFeatures::ExperimentalCanvasFeaturesEnabled()) { already_uploaded_id = texture->GetLastUploadedVideoFrameId(); frame_metadata_ptr = &frame_metadata; } if (!source_image_rect.IsValid()) { SynthesizeGLError(GL_INVALID_OPERATION, func_name, "source sub-rectangle specified via pixel unpack " "parameters is invalid"); return; } bool source_image_rect_is_default = source_image_rect == SentinelEmptyRect() || source_image_rect == IntRect(0, 0, video->videoWidth(), video->videoHeight()); const bool use_copyTextureCHROMIUM = function_id == kTexImage2D && source_image_rect_is_default && depth == 1 && GL_TEXTURE_2D == target && CanUseTexImageByGPU(format, type); if (use_copyTextureCHROMIUM) { DCHECK_EQ(xoffset, 0); DCHECK_EQ(yoffset, 0); DCHECK_EQ(zoffset, 0); if (video->CopyVideoTextureToPlatformTexture( ContextGL(), target, texture->Object(), internalformat, format, type, level, unpack_premultiply_alpha_, unpack_flip_y_, already_uploaded_id, frame_metadata_ptr)) { texture->UpdateLastUploadedFrame(frame_metadata); return; } } if (source_image_rect_is_default) { ScopedUnpackParametersResetRestore( this, unpack_flip_y_ || unpack_premultiply_alpha_); if (video->TexImageImpl( static_cast<WebMediaPlayer::TexImageFunctionID>(function_id), target, ContextGL(), texture->Object(), level, ConvertTexInternalFormat(internalformat, type), format, type, xoffset, yoffset, zoffset, unpack_flip_y_, unpack_premultiply_alpha_ && unpack_colorspace_conversion_ == GL_NONE)) { texture->ClearLastUploadedFrame(); return; } } if (use_copyTextureCHROMIUM) { std::unique_ptr<ImageBufferSurface> surface = WTF::WrapUnique(new AcceleratedImageBufferSurface( IntSize(video->videoWidth(), video->videoHeight()))); if (surface->IsValid()) { std::unique_ptr<ImageBuffer> image_buffer( ImageBuffer::Create(std::move(surface))); if (image_buffer) { video->PaintCurrentFrame( image_buffer->Canvas(), IntRect(0, 0, video->videoWidth(), video->videoHeight()), nullptr, already_uploaded_id, frame_metadata_ptr); TexImage2DBase(target, level, internalformat, video->videoWidth(), video->videoHeight(), 0, format, type, nullptr); if (image_buffer->CopyToPlatformTexture( FunctionIDToSnapshotReason(function_id), ContextGL(), target, texture->Object(), unpack_premultiply_alpha_, unpack_flip_y_, IntPoint(0, 0), IntRect(0, 0, video->videoWidth(), video->videoHeight()))) { texture->UpdateLastUploadedFrame(frame_metadata); return; } } } } scoped_refptr<Image> image = VideoFrameToImage(video, already_uploaded_id, frame_metadata_ptr); if (!image) return; TexImageImpl(function_id, target, level, internalformat, xoffset, yoffset, zoffset, format, type, image.get(), WebGLImageConversion::kHtmlDomVideo, unpack_flip_y_, unpack_premultiply_alpha_, source_image_rect, depth, unpack_image_height); texture->UpdateLastUploadedFrame(frame_metadata); }
13,269
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static Image *ReadPIXImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; IndexPacket index; MagickBooleanType status; Quantum blue, green, red; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; size_t bits_per_pixel, height, length, width; ssize_t y; /* 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); } /* Read PIX image. */ width=ReadBlobMSBShort(image); height=ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); /* x-offset */ (void) ReadBlobMSBShort(image); /* y-offset */ bits_per_pixel=ReadBlobMSBShort(image); if ((width == 0UL) || (height == 0UL) || ((bits_per_pixel != 8) && (bits_per_pixel != 24))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Initialize image structure. */ image->columns=width; image->rows=height; if (bits_per_pixel == 8) if (AcquireImageColormap(image,256) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Convert PIX raster image to pixel packets. */ red=(Quantum) 0; green=(Quantum) 0; blue=(Quantum) 0; index=(IndexPacket) 0; length=0; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if (length == 0) { length=(size_t) ReadBlobByte(image); if (bits_per_pixel == 8) index=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); else { blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } } if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x,index); SetPixelBlue(q,blue); SetPixelGreen(q,green); SetPixelRed(q,red); length--; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; width=ReadBlobMSBLong(image); height=ReadBlobMSBLong(image); (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); bits_per_pixel=ReadBlobMSBShort(image); status=(width != 0UL) && (height == 0UL) && ((bits_per_pixel == 8) || (bits_per_pixel == 24)) ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* 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 (status != MagickFalse); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadPIXImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; IndexPacket index; MagickBooleanType status; Quantum blue, green, red; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; size_t bits_per_pixel, height, length, width; ssize_t y; /* 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); } /* Read PIX image. */ width=ReadBlobMSBShort(image); height=ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); /* x-offset */ (void) ReadBlobMSBShort(image); /* y-offset */ bits_per_pixel=ReadBlobMSBShort(image); if ((width == 0UL) || (height == 0UL) || ((bits_per_pixel != 8) && (bits_per_pixel != 24))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Initialize image structure. */ image->columns=width; image->rows=height; if (bits_per_pixel == 8) if (AcquireImageColormap(image,256) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert PIX raster image to pixel packets. */ red=(Quantum) 0; green=(Quantum) 0; blue=(Quantum) 0; index=(IndexPacket) 0; length=0; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if (length == 0) { length=(size_t) ReadBlobByte(image); if (bits_per_pixel == 8) index=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); else { blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); } } if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x,index); SetPixelBlue(q,blue); SetPixelGreen(q,green); SetPixelRed(q,red); length--; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (image->storage_class == PseudoClass) (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; width=ReadBlobMSBLong(image); height=ReadBlobMSBLong(image); (void) ReadBlobMSBShort(image); (void) ReadBlobMSBShort(image); bits_per_pixel=ReadBlobMSBShort(image); status=(width != 0UL) && (height == 0UL) && ((bits_per_pixel == 8) || (bits_per_pixel == 24)) ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* 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 (status != MagickFalse); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
7,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode) { long err = 0; unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { err = compat_get_bitmap(bm, nmask, nr_bits); nm = compat_alloc_user_space(alloc_size); err |= copy_to_user(nm, bm, alloc_size); } if (err) return -EFAULT; return sys_set_mempolicy(mode, nm, nr_bits+1); } Commit Message: mm/mempolicy.c: fix error handling in set_mempolicy and mbind. In the case that compat_get_bitmap fails we do not want to copy the bitmap to the user as it will contain uninitialized stack data and leak sensitive data. Signed-off-by: Chris Salls <salls@cs.ucsb.edu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-388
COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode) { unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { if (compat_get_bitmap(bm, nmask, nr_bits)) return -EFAULT; nm = compat_alloc_user_space(alloc_size); if (copy_to_user(nm, bm, alloc_size)) return -EFAULT; } return sys_set_mempolicy(mode, nm, nr_bits+1); }
28,782
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static pfn_t kvm_pin_pages(struct kvm_memory_slot *slot, gfn_t gfn, unsigned long size) { gfn_t end_gfn; pfn_t pfn; pfn = gfn_to_pfn_memslot(slot, gfn); end_gfn = gfn + (size >> PAGE_SHIFT); gfn += 1; if (is_error_noslot_pfn(pfn)) return pfn; while (gfn < end_gfn) gfn_to_pfn_memslot(slot, gfn++); return pfn; } Commit Message: kvm: fix excessive pages un-pinning in kvm_iommu_map error path. The third parameter of kvm_unpin_pages() when called from kvm_iommu_map_pages() is wrong, it should be the number of pages to un-pin and not the page size. This error was facilitated with an inconsistent API: kvm_pin_pages() takes a size, but kvn_unpin_pages() takes a number of pages, so fix the problem by matching the two. This was introduced by commit 350b8bd ("kvm: iommu: fix the third parameter of kvm_iommu_put_pages (CVE-2014-3601)"), which fixes the lack of un-pinning for pages intended to be un-pinned (i.e. memory leak) but unfortunately potentially aggravated the number of pages we un-pin that should have stayed pinned. As far as I understand though, the same practical mitigations apply. This issue was found during review of Red Hat 6.6 patches to prepare Ksplice rebootless updates. Thanks to Vegard for his time on a late Friday evening to help me in understanding this code. Fixes: 350b8bd ("kvm: iommu: fix the third parameter of... (CVE-2014-3601)") Cc: stable@vger.kernel.org Signed-off-by: Quentin Casasnovas <quentin.casasnovas@oracle.com> Signed-off-by: Vegard Nossum <vegard.nossum@oracle.com> Signed-off-by: Jamie Iles <jamie.iles@oracle.com> Reviewed-by: Sasha Levin <sasha.levin@oracle.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> CWE ID: CWE-189
static pfn_t kvm_pin_pages(struct kvm_memory_slot *slot, gfn_t gfn, unsigned long npages) { gfn_t end_gfn; pfn_t pfn; pfn = gfn_to_pfn_memslot(slot, gfn); end_gfn = gfn + npages; gfn += 1; if (is_error_noslot_pfn(pfn)) return pfn; while (gfn < end_gfn) gfn_to_pfn_memslot(slot, gfn++); return pfn; }
20,913
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int mailimf_group_parse(const char * message, size_t length, size_t * indx, struct mailimf_group ** result) { size_t cur_token; char * display_name; struct mailimf_mailbox_list * mailbox_list; struct mailimf_group * group; int r; int res; cur_token = * indx; mailbox_list = NULL; r = mailimf_display_name_parse(message, length, &cur_token, &display_name); if (r != MAILIMF_NO_ERROR) { res = r; goto err; } r = mailimf_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_display_name; } r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list); switch (r) { case MAILIMF_NO_ERROR: break; case MAILIMF_ERROR_PARSE: r = mailimf_cfws_parse(message, length, &cur_token); if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) { res = r; goto free_display_name; } break; default: res = r; goto free_display_name; } r = mailimf_semi_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_mailbox_list; } group = mailimf_group_new(display_name, mailbox_list); if (group == NULL) { res = MAILIMF_ERROR_MEMORY; goto free_mailbox_list; } * indx = cur_token; * result = group; return MAILIMF_NO_ERROR; free_mailbox_list: if (mailbox_list != NULL) { mailimf_mailbox_list_free(mailbox_list); } free_display_name: mailimf_display_name_free(display_name); err: return res; } Commit Message: Fixed crash #274 CWE ID: CWE-476
static int mailimf_group_parse(const char * message, size_t length, size_t * indx, struct mailimf_group ** result) { size_t cur_token; char * display_name; struct mailimf_mailbox_list * mailbox_list; struct mailimf_group * group; int r; int res; clist * list; cur_token = * indx; mailbox_list = NULL; r = mailimf_display_name_parse(message, length, &cur_token, &display_name); if (r != MAILIMF_NO_ERROR) { res = r; goto err; } r = mailimf_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_display_name; } r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list); switch (r) { case MAILIMF_NO_ERROR: break; case MAILIMF_ERROR_PARSE: r = mailimf_cfws_parse(message, length, &cur_token); if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) { res = r; goto free_display_name; } list = clist_new(); if (list == NULL) { res = MAILIMF_ERROR_MEMORY; goto free_display_name; } mailbox_list = mailimf_mailbox_list_new(list); if (mailbox_list == NULL) { res = MAILIMF_ERROR_MEMORY; clist_free(list); goto free_display_name; } break; default: res = r; goto free_display_name; } r = mailimf_semi_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_mailbox_list; } group = mailimf_group_new(display_name, mailbox_list); if (group == NULL) { res = MAILIMF_ERROR_MEMORY; goto free_mailbox_list; } * indx = cur_token; * result = group; return MAILIMF_NO_ERROR; free_mailbox_list: if (mailbox_list != NULL) { mailimf_mailbox_list_free(mailbox_list); } free_display_name: mailimf_display_name_free(display_name); err: return res; }
26,984
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_ce_exception, 0, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; size_t fname_len, alias_len = 0; int arch_len, entry_len, is_data; zend_long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; zend_long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data); if (is_data) { if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } ZVAL_STRINGL(&arg1, fname, fname_len); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); zval_ptr_dtor(&arg1); if (!phar_data->is_persistent) { phar_obj->archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_str_add_ptr(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive), phar_obj); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_ce_exception, 0, "Cannot instantiate Phar object without SPL extension"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; size_t fname_len, alias_len = 0; int arch_len, entry_len, is_data; zend_long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; zend_long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data); if (is_data) { if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p|ls!l", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p|ls!", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "%s", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar creation or opening failed"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "PharData class can only be used for non-executable tar and zip archives"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Phar class can only be used for executable tar and zip archives"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, "phar://%s%s", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, "phar://%s", phar_data->fname); } ZVAL_STRINGL(&arg1, fname, fname_len); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg1, &arg2); zval_ptr_dtor(&arg1); if (!phar_data->is_persistent) { phar_obj->archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_str_add_ptr(&PHAR_G(phar_persist_map), (const char *) phar_obj->archive, sizeof(phar_obj->archive), phar_obj); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ }
9,230
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool AppCacheDatabase::InsertCache(const CacheRecord* record) { if (!LazyOpen(kCreateIfNeeded)) return false; static const char kSql[] = "INSERT INTO Caches (cache_id, group_id, online_wildcard," " update_time, cache_size)" " VALUES(?, ?, ?, ?, ?)"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, record->cache_id); statement.BindInt64(1, record->group_id); statement.BindBool(2, record->online_wildcard); statement.BindInt64(3, record->update_time.ToInternalValue()); statement.BindInt64(4, record->cache_size); return statement.Run(); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <staphany@chromium.org> > Reviewed-by: Victor Costan <pwnall@chromium.org> > Reviewed-by: Marijn Kruisselbrink <mek@chromium.org> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <pwnall@chromium.org> Commit-Queue: Staphany Park <staphany@chromium.org> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
bool AppCacheDatabase::InsertCache(const CacheRecord* record) { if (!LazyOpen(kCreateIfNeeded)) return false; static const char kSql[] = "INSERT INTO Caches (cache_id, group_id, online_wildcard," " update_time, cache_size, padding_size)" " VALUES(?, ?, ?, ?, ?, ?)"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, record->cache_id); statement.BindInt64(1, record->group_id); statement.BindBool(2, record->online_wildcard); statement.BindInt64(3, record->update_time.ToInternalValue()); DCHECK_GE(record->cache_size, 0); statement.BindInt64(4, record->cache_size); DCHECK_GE(record->padding_size, 0); statement.BindInt64(5, record->padding_size); return statement.Run(); }
11,596
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: PHP_FUNCTION(mcrypt_cfb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_cfb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); }
5,754
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev, struct nci_rf_intf_activated_ntf *ntf, __u8 *data) { struct activation_params_nfca_poll_iso_dep *nfca_poll; struct activation_params_nfcb_poll_iso_dep *nfcb_poll; switch (ntf->activation_rf_tech_and_mode) { case NCI_NFC_A_PASSIVE_POLL_MODE: nfca_poll = &ntf->activation_params.nfca_poll_iso_dep; nfca_poll->rats_res_len = *data++; pr_debug("rats_res_len %d\n", nfca_poll->rats_res_len); if (nfca_poll->rats_res_len > 0) { memcpy(nfca_poll->rats_res, data, nfca_poll->rats_res_len); } break; case NCI_NFC_B_PASSIVE_POLL_MODE: nfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep; nfcb_poll->attrib_res_len = *data++; pr_debug("attrib_res_len %d\n", nfcb_poll->attrib_res_len); if (nfcb_poll->attrib_res_len > 0) { memcpy(nfcb_poll->attrib_res, data, nfcb_poll->attrib_res_len); } break; default: pr_err("unsupported activation_rf_tech_and_mode 0x%x\n", ntf->activation_rf_tech_and_mode); return NCI_STATUS_RF_PROTOCOL_ERROR; } return NCI_STATUS_OK; } Commit Message: NFC: Prevent multiple buffer overflows in NCI Fix multiple remotely-exploitable stack-based buffer overflows due to the NCI code pulling length fields directly from incoming frames and copying too much data into statically-sized arrays. Signed-off-by: Dan Rosenberg <dan.j.rosenberg@gmail.com> Cc: stable@kernel.org Cc: security@kernel.org Cc: Lauro Ramos Venancio <lauro.venancio@openbossa.org> Cc: Aloisio Almeida Jr <aloisio.almeida@openbossa.org> Cc: Samuel Ortiz <sameo@linux.intel.com> Cc: David S. Miller <davem@davemloft.net> Acked-by: Ilan Elias <ilane@ti.com> Signed-off-by: Samuel Ortiz <sameo@linux.intel.com> CWE ID: CWE-119
static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev, struct nci_rf_intf_activated_ntf *ntf, __u8 *data) { struct activation_params_nfca_poll_iso_dep *nfca_poll; struct activation_params_nfcb_poll_iso_dep *nfcb_poll; switch (ntf->activation_rf_tech_and_mode) { case NCI_NFC_A_PASSIVE_POLL_MODE: nfca_poll = &ntf->activation_params.nfca_poll_iso_dep; nfca_poll->rats_res_len = min_t(__u8, *data++, 20); pr_debug("rats_res_len %d\n", nfca_poll->rats_res_len); if (nfca_poll->rats_res_len > 0) { memcpy(nfca_poll->rats_res, data, nfca_poll->rats_res_len); } break; case NCI_NFC_B_PASSIVE_POLL_MODE: nfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep; nfcb_poll->attrib_res_len = min_t(__u8, *data++, 50); pr_debug("attrib_res_len %d\n", nfcb_poll->attrib_res_len); if (nfcb_poll->attrib_res_len > 0) { memcpy(nfcb_poll->attrib_res, data, nfcb_poll->attrib_res_len); } break; default: pr_err("unsupported activation_rf_tech_and_mode 0x%x\n", ntf->activation_rf_tech_and_mode); return NCI_STATUS_RF_PROTOCOL_ERROR; } return NCI_STATUS_OK; }
23,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static char* get_private_subtags(const char* loc_name) { char* result =NULL; int singletonPos = 0; int len =0; const char* mod_loc_name =NULL; if( loc_name && (len = strlen(loc_name)>0 ) ){ mod_loc_name = loc_name ; len = strlen(mod_loc_name); while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){ if( singletonPos!=-1){ if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){ /* private subtag start found */ if( singletonPos + 2 == len){ /* loc_name ends with '-x-' ; return NULL */ } else{ /* result = mod_loc_name + singletonPos +2; */ result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) ); } break; } else{ if( singletonPos + 1 >= len){ /* String end */ break; } else { /* singleton found but not a private subtag , hence check further in the string for the private subtag */ mod_loc_name = mod_loc_name + singletonPos +1; len = strlen(mod_loc_name); } } } } /* end of while */ } return result; } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static char* get_private_subtags(const char* loc_name) { char* result =NULL; int singletonPos = 0; int len =0; const char* mod_loc_name =NULL; if( loc_name && (len = strlen(loc_name)>0 ) ){ mod_loc_name = loc_name ; len = strlen(mod_loc_name); while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){ if( singletonPos!=-1){ if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){ /* private subtag start found */ if( singletonPos + 2 == len){ /* loc_name ends with '-x-' ; return NULL */ } else{ /* result = mod_loc_name + singletonPos +2; */ result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) ); } break; } else{ if( singletonPos + 1 >= len){ /* String end */ break; } else { /* singleton found but not a private subtag , hence check further in the string for the private subtag */ mod_loc_name = mod_loc_name + singletonPos +1; len = strlen(mod_loc_name); } } } } /* end of while */ } return result; }
17,057
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static void mcf_fec_do_tx(mcf_fec_state *s) { uint32_t addr; uint32_t addr; mcf_fec_bd bd; int frame_size; int len; uint8_t frame[FEC_MAX_FRAME_SIZE]; uint8_t *ptr; ptr = frame; ptr = frame; frame_size = 0; addr = s->tx_descriptor; while (1) { mcf_fec_read_bd(&bd, addr); DPRINTF("tx_bd %x flags %04x len %d data %08x\n", addr, bd.flags, bd.length, bd.data); /* Run out of descriptors to transmit. */ break; } len = bd.length; if (frame_size + len > FEC_MAX_FRAME_SIZE) { len = FEC_MAX_FRAME_SIZE - frame_size; s->eir |= FEC_INT_BABT; } cpu_physical_memory_read(bd.data, ptr, len); ptr += len; frame_size += len; if (bd.flags & FEC_BD_L) { /* Last buffer in frame. */ DPRINTF("Sending packet\n"); qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->eir |= FEC_INT_TXF; } s->eir |= FEC_INT_TXB; bd.flags &= ~FEC_BD_R; /* Write back the modified descriptor. */ mcf_fec_write_bd(&bd, addr); /* Advance to the next descriptor. */ if ((bd.flags & FEC_BD_W) != 0) { addr = s->etdsr; } else { addr += 8; } } Commit Message: CWE ID: CWE-399
static void mcf_fec_do_tx(mcf_fec_state *s) { uint32_t addr; uint32_t addr; mcf_fec_bd bd; int frame_size; int len, descnt = 0; uint8_t frame[FEC_MAX_FRAME_SIZE]; uint8_t *ptr; ptr = frame; ptr = frame; frame_size = 0; addr = s->tx_descriptor; while (descnt++ < FEC_MAX_DESC) { mcf_fec_read_bd(&bd, addr); DPRINTF("tx_bd %x flags %04x len %d data %08x\n", addr, bd.flags, bd.length, bd.data); /* Run out of descriptors to transmit. */ break; } len = bd.length; if (frame_size + len > FEC_MAX_FRAME_SIZE) { len = FEC_MAX_FRAME_SIZE - frame_size; s->eir |= FEC_INT_BABT; } cpu_physical_memory_read(bd.data, ptr, len); ptr += len; frame_size += len; if (bd.flags & FEC_BD_L) { /* Last buffer in frame. */ DPRINTF("Sending packet\n"); qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->eir |= FEC_INT_TXF; } s->eir |= FEC_INT_TXB; bd.flags &= ~FEC_BD_R; /* Write back the modified descriptor. */ mcf_fec_write_bd(&bd, addr); /* Advance to the next descriptor. */ if ((bd.flags & FEC_BD_W) != 0) { addr = s->etdsr; } else { addr += 8; } }
2,674
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int ras_getcmap(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap) { int i; int j; int x; int c; int numcolors; int actualnumcolors; switch (hdr->maptype) { case RAS_MT_NONE: break; case RAS_MT_EQUALRGB: { jas_eprintf("warning: palettized images not fully supported\n"); numcolors = 1 << hdr->depth; assert(numcolors <= RAS_CMAP_MAXSIZ); actualnumcolors = hdr->maplength / 3; for (i = 0; i < numcolors; i++) { cmap->data[i] = 0; } if ((hdr->maplength % 3) || hdr->maplength < 0 || hdr->maplength > 3 * numcolors) { return -1; } for (i = 0; i < 3; i++) { for (j = 0; j < actualnumcolors; j++) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } x = 0; switch (i) { case 0: x = RAS_RED(c); break; case 1: x = RAS_GREEN(c); break; case 2: x = RAS_BLUE(c); break; } cmap->data[j] |= x; } } } break; default: return -1; break; } return 0; } Commit Message: Fixed a few bugs in the RAS encoder and decoder where errors were tested with assertions instead of being gracefully handled. CWE ID:
static int ras_getcmap(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap) { int i; int j; int x; int c; int numcolors; int actualnumcolors; switch (hdr->maptype) { case RAS_MT_NONE: break; case RAS_MT_EQUALRGB: { jas_eprintf("warning: palettized images not fully supported\n"); numcolors = 1 << hdr->depth; if (numcolors > RAS_CMAP_MAXSIZ) { return -1; } actualnumcolors = hdr->maplength / 3; for (i = 0; i < numcolors; i++) { cmap->data[i] = 0; } if ((hdr->maplength % 3) || hdr->maplength < 0 || hdr->maplength > 3 * numcolors) { return -1; } for (i = 0; i < 3; i++) { for (j = 0; j < actualnumcolors; j++) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } x = 0; switch (i) { case 0: x = RAS_RED(c); break; case 1: x = RAS_GREEN(c); break; case 2: x = RAS_BLUE(c); break; } cmap->data[j] |= x; } } } break; default: return -1; break; } return 0; }
23,846
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: PepperMediaDeviceManager* PepperMediaDeviceManager::GetForRenderFrame( RenderFrame* render_frame) { PepperMediaDeviceManager* handler = PepperMediaDeviceManager::Get(render_frame); if (!handler) handler = new PepperMediaDeviceManager(render_frame); return handler; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
PepperMediaDeviceManager* PepperMediaDeviceManager::GetForRenderFrame( base::WeakPtr<PepperMediaDeviceManager> PepperMediaDeviceManager::GetForRenderFrame( RenderFrame* render_frame) { PepperMediaDeviceManager* handler = PepperMediaDeviceManager::Get(render_frame); if (!handler) handler = new PepperMediaDeviceManager(render_frame); return handler->AsWeakPtr(); }
4,006
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function 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); } Commit Message: BQ: fix some uninitialized variables Bug 27555981 Bug 27556038 Change-Id: I436b6fec589677d7e36c0e980f6e59808415dc0e CWE ID: CWE-200
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))); memset(output, 0, 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); }
15,909
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function 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; } 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. CWE ID: CWE-59
static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent) static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int exclusive, 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, exclusive ? "wx.ufdio" : "a.ufdio"); umask(old_umask); /* If reopening, make sure the file is what we expect */ if (!exclusive && wfd != NULL && !linkSane(wfd, dest)) { rc = RPMERR_OPEN_FAILED; goto exit; } } 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; }
9,367
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn, xkb_mod_mask_t *mods_rtrn, CompatInfo *info) { if (expr == NULL) { *pred_rtrn = MATCH_ANY_OR_NONE; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } *pred_rtrn = MATCH_EXACTLY; if (expr->expr.op == EXPR_ACTION_DECL) { const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name); if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) { log_err(info->ctx, "Illegal modifier predicate \"%s\"; Ignored\n", pred_txt); return false; } expr = expr->action.args; } else if (expr->expr.op == EXPR_IDENT) { const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident); if (pred_txt && istreq(pred_txt, "any")) { *pred_rtrn = MATCH_ANY; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } } return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods, mods_rtrn); } Commit Message: xkbcomp: Don't crash on no-op modmask expressions If we have an expression of the form 'l1' in an interp section, we unconditionally try to dereference its args, even if it has none. Signed-off-by: Daniel Stone <daniels@collabora.com> CWE ID: CWE-476
ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn, xkb_mod_mask_t *mods_rtrn, CompatInfo *info) { if (expr == NULL) { *pred_rtrn = MATCH_ANY_OR_NONE; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } *pred_rtrn = MATCH_EXACTLY; if (expr->expr.op == EXPR_ACTION_DECL) { const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name); if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn) || !expr->action.args) { log_err(info->ctx, "Illegal modifier predicate \"%s\"; Ignored\n", pred_txt); return false; } expr = expr->action.args; } else if (expr->expr.op == EXPR_IDENT) { const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident); if (pred_txt && istreq(pred_txt, "any")) { *pred_rtrn = MATCH_ANY; *mods_rtrn = MOD_REAL_MASK_ALL; return true; } } return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods, mods_rtrn); }
7,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: virtual void SetUp() { UUT_ = GET_PARAM(2); /* Set up guard blocks for an inner block centered in the outer block */ for (int i = 0; i < kOutputBufferSize; ++i) { if (IsIndexInBorder(i)) output_[i] = 255; else output_[i] = 0; } ::libvpx_test::ACMRandom prng; for (int i = 0; i < kInputBufferSize; ++i) input_[i] = prng.Rand8Extremes(); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { UUT_ = GET_PARAM(2); #if CONFIG_VP9_HIGHBITDEPTH if (UUT_->use_highbd_ != 0) mask_ = (1 << UUT_->use_highbd_) - 1; else mask_ = 255; #endif /* Set up guard blocks for an inner block centered in the outer block */ for (int i = 0; i < kOutputBufferSize; ++i) { if (IsIndexInBorder(i)) output_[i] = 255; else output_[i] = 0; } ::libvpx_test::ACMRandom prng; for (int i = 0; i < kInputBufferSize; ++i) { if (i & 1) { input_[i] = 255; #if CONFIG_VP9_HIGHBITDEPTH input16_[i] = mask_; #endif } else { input_[i] = prng.Rand8Extremes(); #if CONFIG_VP9_HIGHBITDEPTH input16_[i] = prng.Rand16() & mask_; #endif } } }
1,958
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: int tls1_setup_key_block(SSL *s) { unsigned char *p; const EVP_CIPHER *c; const EVP_MD *hash; int num; SSL_COMP *comp; int mac_type = NID_undef, mac_secret_size = 0; int ret = 0; if (s->s3->tmp.key_block_length != 0) return (1); if (!ssl_cipher_get_evp (s->session, &c, &hash, &mac_type, &mac_secret_size, &comp, SSL_USE_ETM(s))) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE); return (0); } s->s3->tmp.new_sym_enc = c; s->s3->tmp.new_hash = hash; s->s3->tmp.new_mac_pkey_type = mac_type; s->s3->tmp.new_mac_secret_size = mac_secret_size; num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c); num *= 2; ssl3_cleanup_key_block(s); if ((p = OPENSSL_malloc(num)) == NULL) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE); goto err; } s->s3->tmp.key_block_length = num; s->s3->tmp.key_block = p; #ifdef SSL_DEBUG printf("client random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->client_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("server random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->server_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("master key\n"); { int z; for (z = 0; z < s->session->master_key_length; z++) printf("%02X%c", s->session->master_key[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!tls1_generate_key_block(s, p, num)) goto err; #ifdef SSL_DEBUG printf("\nkey block\n"); { int z; for (z = 0; z < num; z++) printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) && s->method->version <= TLS1_VERSION) { /* * enable vulnerability countermeasure for CBC ciphers with known-IV * problem (http://www.openssl.org/~bodo/tls-cbc.txt) */ s->s3->need_empty_fragments = 1; if (s->session->cipher != NULL) { if (s->session->cipher->algorithm_enc == SSL_eNULL) s->s3->need_empty_fragments = 0; #ifndef OPENSSL_NO_RC4 if (s->session->cipher->algorithm_enc == SSL_RC4) s->s3->need_empty_fragments = 0; #endif } } ret = 1; err: return (ret); } Commit Message: Don't change the state of the ETM flags until CCS processing Changing the ciphersuite during a renegotiation can result in a crash leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS so this is TLS only. The problem is caused by changing the flag indicating whether to use ETM or not immediately on negotiation of ETM, rather than at CCS. Therefore, during a renegotiation, if the ETM state is changing (usually due to a change of ciphersuite), then an error/crash will occur. Due to the fact that there are separate CCS messages for read and write we actually now need two flags to determine whether to use ETM or not. CVE-2017-3733 Reviewed-by: Richard Levitte <levitte@openssl.org> CWE ID: CWE-20
int tls1_setup_key_block(SSL *s) { unsigned char *p; const EVP_CIPHER *c; const EVP_MD *hash; int num; SSL_COMP *comp; int mac_type = NID_undef, mac_secret_size = 0; int ret = 0; if (s->s3->tmp.key_block_length != 0) return (1); if (!ssl_cipher_get_evp(s->session, &c, &hash, &mac_type, &mac_secret_size, &comp, s->tlsext_use_etm)) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE); return (0); } s->s3->tmp.new_sym_enc = c; s->s3->tmp.new_hash = hash; s->s3->tmp.new_mac_pkey_type = mac_type; s->s3->tmp.new_mac_secret_size = mac_secret_size; num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c); num *= 2; ssl3_cleanup_key_block(s); if ((p = OPENSSL_malloc(num)) == NULL) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE); goto err; } s->s3->tmp.key_block_length = num; s->s3->tmp.key_block = p; #ifdef SSL_DEBUG printf("client random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->client_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("server random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->server_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("master key\n"); { int z; for (z = 0; z < s->session->master_key_length; z++) printf("%02X%c", s->session->master_key[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!tls1_generate_key_block(s, p, num)) goto err; #ifdef SSL_DEBUG printf("\nkey block\n"); { int z; for (z = 0; z < num; z++) printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) && s->method->version <= TLS1_VERSION) { /* * enable vulnerability countermeasure for CBC ciphers with known-IV * problem (http://www.openssl.org/~bodo/tls-cbc.txt) */ s->s3->need_empty_fragments = 1; if (s->session->cipher != NULL) { if (s->session->cipher->algorithm_enc == SSL_eNULL) s->s3->need_empty_fragments = 0; #ifndef OPENSSL_NO_RC4 if (s->session->cipher->algorithm_enc == SSL_RC4) s->s3->need_empty_fragments = 0; #endif } } ret = 1; err: return (ret); }
29,988
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: PHP_FUNCTION(imagetruecolortopalette) { zval *IM; zend_bool dither; long ncolors; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (ncolors <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero"); RETURN_FALSE; } gdImageTrueColorToPalette(im, dither, ncolors); RETURN_TRUE; } Commit Message: Fix bug#72697 - select_colors write out-of-bounds CWE ID: CWE-787
PHP_FUNCTION(imagetruecolortopalette) { zval *IM; zend_bool dither; long ncolors; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rbl", &IM, &dither, &ncolors) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); if (ncolors <= 0 || ncolors > INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of colors has to be greater than zero and no more than %d", INT_MAX); RETURN_FALSE; } gdImageTrueColorToPalette(im, dither, (int)ncolors); RETURN_TRUE; }
12,603
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool DebuggerDetachFunction::RunAsync() { std::unique_ptr<Detach::Params> params(Detach::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); if (!InitClientHost()) return false; client_host_->Close(); SendResponse(true); return true; } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. TBR=alexclarke@chromium.org Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <dgozman@chromium.org> Reviewed-by: Devlin <rdevlin.cronin@chromium.org> Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Nasko Oskov <nasko@chromium.org> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
bool DebuggerDetachFunction::RunAsync() { std::unique_ptr<Detach::Params> params(Detach::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); if (!InitClientHost()) return false; client_host_->RespondDetachedToPendingRequests(); client_host_->Close(); SendResponse(true); return true; }
19,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static void v9fs_walk(void *opaque) { int name_idx; V9fsFidState *newfidp = NULL; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames); if (err < 0) { pdu_complete(pdu, err); return ; } V9fsFidState *newfidp = NULL; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames); if (err < 0) { for (i = 0; i < nwnames; i++) { err = pdu_unmarshal(pdu, offset, "s", &wnames[i]); if (err < 0) { goto out_nofid; } if (name_is_illegal(wnames[i].data)) { err = -ENOENT; goto out_nofid; } offset += err; } } else if (nwnames > P9_MAXWELEM) { err = -EINVAL; goto out_nofid; } fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -ENOENT; goto out_nofid; } v9fs_path_init(&dpath); v9fs_path_init(&path); /* * Both dpath and path initially poin to fidp. * Needed to handle request with nwnames == 0 */ v9fs_path_copy(&dpath, &fidp->path); err = -ENOENT; goto out_nofid; } Commit Message: CWE ID: CWE-22
static void v9fs_walk(void *opaque) { int name_idx; V9fsFidState *newfidp = NULL; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames); if (err < 0) { pdu_complete(pdu, err); return ; } V9fsFidState *newfidp = NULL; V9fsPDU *pdu = opaque; V9fsState *s = pdu->s; V9fsQID qid; err = pdu_unmarshal(pdu, offset, "ddw", &fid, &newfid, &nwnames); if (err < 0) { for (i = 0; i < nwnames; i++) { err = pdu_unmarshal(pdu, offset, "s", &wnames[i]); if (err < 0) { goto out_nofid; } if (name_is_illegal(wnames[i].data)) { err = -ENOENT; goto out_nofid; } offset += err; } } else if (nwnames > P9_MAXWELEM) { err = -EINVAL; goto out_nofid; } fidp = get_fid(pdu, fid); if (fidp == NULL) { err = -ENOENT; goto out_nofid; } v9fs_path_init(&dpath); v9fs_path_init(&path); /* * Both dpath and path initially poin to fidp. * Needed to handle request with nwnames == 0 */ v9fs_path_copy(&dpath, &fidp->path); err = -ENOENT; goto out_nofid; }
9,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: TouchpadLibrary* CrosLibrary::GetTouchpadLibrary() { return touchpad_lib_.GetDefaultImpl(use_stub_impl_); } 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 CWE ID: CWE-189
TouchpadLibrary* CrosLibrary::GetTouchpadLibrary() {
17,461
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void RunAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); uint32_t max_error = 0; int64_t total_error = 0; const int count_test_block = 10000; for (int i = 0; i < count_test_block; ++i) { DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs); for (int j = 0; j < kNumCoeffs; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; } REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block, test_temp_block, pitch_)); REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { const uint32_t diff = dst[j] - src[j]; const uint32_t error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(1u, max_error) << "Error: 4x4 FHT/IHT has an individual round trip error > 1"; EXPECT_GE(count_test_block , total_error) << "Error: 4x4 FHT/IHT has average round trip error > 1 per block"; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunAccuracyCheck() { void RunAccuracyCheck(int limit) { ACMRandom rnd(ACMRandom::DeterministicSeed()); uint32_t max_error = 0; int64_t total_error = 0; const int count_test_block = 10000; for (int i = 0; i < count_test_block; ++i) { DECLARE_ALIGNED(16, int16_t, test_input_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, test_temp_block[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]); #if CONFIG_VP9_HIGHBITDEPTH DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]); DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]); #endif for (int j = 0; j < kNumCoeffs; ++j) { if (bit_depth_ == VPX_BITS_8) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; #if CONFIG_VP9_HIGHBITDEPTH } else { src16[j] = rnd.Rand16() & mask_; dst16[j] = rnd.Rand16() & mask_; test_input_block[j] = src16[j] - dst16[j]; #endif } } ASM_REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block, test_temp_block, pitch_)); if (bit_depth_ == VPX_BITS_8) { ASM_REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_)); #if CONFIG_VP9_HIGHBITDEPTH } else { ASM_REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_)); #endif } for (int j = 0; j < kNumCoeffs; ++j) { #if CONFIG_VP9_HIGHBITDEPTH const uint32_t diff = bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; #else ASSERT_EQ(VPX_BITS_8, bit_depth_); const uint32_t diff = dst[j] - src[j]; #endif const uint32_t error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(static_cast<uint32_t>(limit), max_error) << "Error: 4x4 FHT/IHT has an individual round trip error > " << limit; EXPECT_GE(count_test_block * limit, total_error) << "Error: 4x4 FHT/IHT has average round trip error > " << limit << " per block"; }
24,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void OpenSession() { const int render_process_id = 1; const int render_frame_id = 1; const int page_request_id = 1; const url::Origin security_origin = url::Origin::Create(GURL("http://test.com")); ASSERT_TRUE(opened_device_label_.empty()); MediaDeviceInfoArray video_devices; { base::RunLoop run_loop; MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true; media_stream_manager_->media_devices_manager()->EnumerateDevices( devices_to_enumerate, base::BindOnce(&VideoInputDevicesEnumerated, run_loop.QuitClosure(), browser_context_.GetMediaDeviceIDSalt(), security_origin, &video_devices)); run_loop.Run(); } ASSERT_FALSE(video_devices.empty()); { base::RunLoop run_loop; media_stream_manager_->OpenDevice( render_process_id, render_frame_id, page_request_id, video_devices[0].device_id, MEDIA_DEVICE_VIDEO_CAPTURE, MediaDeviceSaltAndOrigin{browser_context_.GetMediaDeviceIDSalt(), browser_context_.GetMediaDeviceIDSalt(), security_origin}, base::BindOnce(&VideoCaptureTest::OnDeviceOpened, base::Unretained(this), run_loop.QuitClosure()), MediaStreamManager::DeviceStoppedCallback()); run_loop.Run(); } ASSERT_NE(MediaStreamDevice::kNoId, opened_session_id_); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <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} CWE ID: CWE-189
void OpenSession() { const int render_process_id = 1; const int render_frame_id = 1; const int requester_id = 1; const int page_request_id = 1; const url::Origin security_origin = url::Origin::Create(GURL("http://test.com")); ASSERT_TRUE(opened_device_label_.empty()); MediaDeviceInfoArray video_devices; { base::RunLoop run_loop; MediaDevicesManager::BoolDeviceTypes devices_to_enumerate; devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true; media_stream_manager_->media_devices_manager()->EnumerateDevices( devices_to_enumerate, base::BindOnce(&VideoInputDevicesEnumerated, run_loop.QuitClosure(), browser_context_.GetMediaDeviceIDSalt(), security_origin, &video_devices)); run_loop.Run(); } ASSERT_FALSE(video_devices.empty()); { base::RunLoop run_loop; media_stream_manager_->OpenDevice( render_process_id, render_frame_id, requester_id, page_request_id, video_devices[0].device_id, MEDIA_DEVICE_VIDEO_CAPTURE, MediaDeviceSaltAndOrigin{browser_context_.GetMediaDeviceIDSalt(), browser_context_.GetMediaDeviceIDSalt(), security_origin}, base::BindOnce(&VideoCaptureTest::OnDeviceOpened, base::Unretained(this), run_loop.QuitClosure()), MediaStreamManager::DeviceStoppedCallback()); run_loop.Run(); } ASSERT_NE(MediaStreamDevice::kNoId, opened_session_id_); }
14,525
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: RenderFrameHostManager::GetSiteInstanceForNavigationRequest( const NavigationRequest& request) { SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); bool no_renderer_swap_allowed = false; bool was_server_redirect = request.navigation_handle() && request.navigation_handle()->WasServerRedirect(); if (frame_tree_node_->IsMainFrame()) { bool can_renderer_initiate_transfer = (request.state() == NavigationRequest::FAILED && SiteIsolationPolicy::IsErrorPageIsolationEnabled( true /* in_main_frame */)) || (render_frame_host_->IsRenderFrameLive() && IsURLHandledByNetworkStack(request.common_params().url) && IsRendererTransferNeededForNavigation(render_frame_host_.get(), request.common_params().url)); no_renderer_swap_allowed |= request.from_begin_navigation() && !can_renderer_initiate_transfer; } else { no_renderer_swap_allowed |= !CanSubframeSwapProcess( request.common_params().url, request.source_site_instance(), request.dest_site_instance(), was_server_redirect); } if (no_renderer_swap_allowed) return scoped_refptr<SiteInstance>(current_site_instance); SiteInstance* candidate_site_instance = speculative_render_frame_host_ ? speculative_render_frame_host_->GetSiteInstance() : nullptr; scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation( request.common_params().url, request.source_site_instance(), request.dest_site_instance(), candidate_site_instance, request.common_params().transition, request.state() == NavigationRequest::FAILED, request.restore_type() != RestoreType::NONE, request.is_view_source(), was_server_redirect); return dest_site_instance; } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <alexmos@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Commit-Queue: Charlie Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285
RenderFrameHostManager::GetSiteInstanceForNavigationRequest( const NavigationRequest& request) { SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); bool no_renderer_swap_allowed = false; bool was_server_redirect = request.navigation_handle() && request.navigation_handle()->WasServerRedirect(); if (frame_tree_node_->IsMainFrame()) { bool can_renderer_initiate_transfer = (request.state() == NavigationRequest::FAILED && SiteIsolationPolicy::IsErrorPageIsolationEnabled( true /* in_main_frame */)) || (render_frame_host_->IsRenderFrameLive() && IsURLHandledByNetworkStack(request.common_params().url) && IsRendererTransferNeededForNavigation(render_frame_host_.get(), request.common_params().url)); no_renderer_swap_allowed |= request.from_begin_navigation() && !can_renderer_initiate_transfer; } else { no_renderer_swap_allowed |= !CanSubframeSwapProcess( request.common_params().url, request.source_site_instance(), request.dest_site_instance()); } if (no_renderer_swap_allowed) return scoped_refptr<SiteInstance>(current_site_instance); SiteInstance* candidate_site_instance = speculative_render_frame_host_ ? speculative_render_frame_host_->GetSiteInstance() : nullptr; scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigation( request.common_params().url, request.source_site_instance(), request.dest_site_instance(), candidate_site_instance, request.common_params().transition, request.state() == NavigationRequest::FAILED, request.restore_type() != RestoreType::NONE, request.is_view_source(), was_server_redirect); return dest_site_instance; }
29,795
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: struct tcp_sock_t *tcp_open(uint16_t port) { struct tcp_sock_t *this = calloc(1, sizeof *this); if (this == NULL) { ERR("callocing this failed"); goto error; } this->sd = -1; this->sd = socket(AF_INET6, SOCK_STREAM, 0); if (this->sd < 0) { ERR("sockect open failed"); goto error; } struct sockaddr_in6 addr; memset(&addr, 0, sizeof addr); addr.sin6_family = AF_INET6; addr.sin6_port = htons(port); addr.sin6_addr = in6addr_any; if (bind(this->sd, (struct sockaddr *)&addr, sizeof addr) < 0) { if (g_options.only_desired_port == 1) ERR("Bind on port failed. " "Requested port may be taken or require root permissions."); goto error; } if (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) { ERR("listen failed on socket"); goto error; } return this; error: if (this != NULL) { if (this->sd != -1) { close(this->sd); } free(this); } return NULL; } Commit Message: SECURITY FIX: Actually restrict the access to the printer to localhost Before, any machine in any network connected by any of the interfaces (as listed by "ifconfig") could access to an IPP-over-USB printer on the assigned port, allowing users on remote machines to print and to access the web configuration interface of a IPP-over-USB printer in contrary to conventional USB printers which are only accessible locally. CWE ID: CWE-264
struct tcp_sock_t *tcp_open(uint16_t port) { struct tcp_sock_t *this = calloc(1, sizeof *this); if (this == NULL) { ERR("IPv4: callocing this failed"); goto error; } // Open [S]ocket [D]escriptor this->sd = -1; this->sd = socket(AF_INET, SOCK_STREAM, 0); if (this->sd < 0) { ERR("IPv4 socket open failed"); goto error; } // Configure socket params struct sockaddr_in addr; memset(&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(0x7F000001); // Bind to localhost if (bind(this->sd, (struct sockaddr *)&addr, sizeof addr) < 0) { if (g_options.only_desired_port == 1) ERR("IPv4 bind on port failed. " "Requested port may be taken or require root permissions."); goto error; } // Let kernel over-accept max number of connections if (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) { ERR("IPv4 listen failed on socket"); goto error; } return this; error: if (this != NULL) { if (this->sd != -1) { close(this->sd); } free(this); } return NULL; } struct tcp_sock_t *tcp6_open(uint16_t port) { struct tcp_sock_t *this = calloc(1, sizeof *this); if (this == NULL) { ERR("IPv6: callocing this failed"); goto error; } this->sd = -1; this->sd = socket(AF_INET6, SOCK_STREAM, 0); if (this->sd < 0) { ERR("Ipv6 socket open failed"); goto error; } struct sockaddr_in6 addr; memset(&addr, 0, sizeof addr); addr.sin6_family = AF_INET6; addr.sin6_port = htons(port); addr.sin6_addr = in6addr_loopback; if (bind(this->sd, (struct sockaddr *)&addr, sizeof addr) < 0) { if (g_options.only_desired_port == 1) ERR("IPv6 bind on port failed. " "Requested port may be taken or require root permissions."); goto error; } if (listen(this->sd, HTTP_MAX_PENDING_CONNS) < 0) { ERR("IPv6 listen failed on socket"); goto error; } return this; error: if (this != NULL) { if (this->sd != -1) { close(this->sd); } free(this); } return NULL; }
8,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 0) encoder->Control(VP8E_SET_NOISE_SENSITIVITY, denoiser_on_); if (denoiser_offon_test_) { ASSERT_GT(denoiser_offon_period_, 0) << "denoiser_offon_period_ is not positive."; if ((video->frame() + 1) % denoiser_offon_period_ == 0) { // Flip denoiser_on_ periodically denoiser_on_ ^= 1; } encoder->Control(VP8E_SET_NOISE_SENSITIVITY, denoiser_on_); } const vpx_rational_t tb = video->timebase(); timebase_ = static_cast<double>(tb.num) / tb.den; duration_ = 0; }
3,643
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: read_header(struct archive_read *a, struct archive_entry *entry, char head_type) { const void *h; const char *p, *endp; struct rar *rar; struct rar_header rar_header; struct rar_file_header file_header; int64_t header_size; unsigned filename_size, end; char *filename; char *strp; char packed_size[8]; char unp_size[8]; int ttime; struct archive_string_conv *sconv, *fn_sconv; unsigned long crc32_val; int ret = (ARCHIVE_OK), ret2; rar = (struct rar *)(a->format->data); /* Setup a string conversion object for non-rar-unicode filenames. */ sconv = rar->opt_sconv; if (sconv == NULL) { if (!rar->init_default_conversion) { rar->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); rar->init_default_conversion = 1; } sconv = rar->sconv_default; } if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(&rar_header, p, sizeof(rar_header)); rar->file_flags = archive_le16dec(rar_header.flags); header_size = archive_le16dec(rar_header.size); if (header_size < (int64_t)sizeof(file_header) + 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2); __archive_read_consume(a, 7); if (!(rar->file_flags & FHD_SOLID)) { rar->compression_method = 0; rar->packed_size = 0; rar->unp_size = 0; rar->mtime = 0; rar->ctime = 0; rar->atime = 0; rar->arctime = 0; rar->mode = 0; memset(&rar->salt, 0, sizeof(rar->salt)); rar->atime = 0; rar->ansec = 0; rar->ctime = 0; rar->cnsec = 0; rar->mtime = 0; rar->mnsec = 0; rar->arctime = 0; rar->arcnsec = 0; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR solid archive support unavailable."); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); /* File Header CRC check. */ crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7)); if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } /* If no CRC error, Go on parsing File Header. */ p = h; endp = p + header_size - 7; memcpy(&file_header, p, sizeof(file_header)); p += sizeof(file_header); rar->compression_method = file_header.method; ttime = archive_le32dec(file_header.file_time); rar->mtime = get_time(ttime); rar->file_crc = archive_le32dec(file_header.file_crc); if (rar->file_flags & FHD_PASSWORD) { archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); /* Since it is only the data part itself that is encrypted we can at least extract information about the currently processed entry and don't need to return ARCHIVE_FATAL here. */ /*return (ARCHIVE_FATAL);*/ } if (rar->file_flags & FHD_LARGE) { memcpy(packed_size, file_header.pack_size, 4); memcpy(packed_size + 4, p, 4); /* High pack size */ p += 4; memcpy(unp_size, file_header.unp_size, 4); memcpy(unp_size + 4, p, 4); /* High unpack size */ p += 4; rar->packed_size = archive_le64dec(&packed_size); rar->unp_size = archive_le64dec(&unp_size); } else { rar->packed_size = archive_le32dec(file_header.pack_size); rar->unp_size = archive_le32dec(file_header.unp_size); } if (rar->packed_size < 0 || rar->unp_size < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid sizes specified."); return (ARCHIVE_FATAL); } rar->bytes_remaining = rar->packed_size; /* TODO: RARv3 subblocks contain comments. For now the complete block is * consumed at the end. */ if (head_type == NEWSUB_HEAD) { size_t distance = p - (const char *)h; header_size += rar->packed_size; /* Make sure we have the extended data. */ if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; endp = p + header_size - 7; p += distance; } filename_size = archive_le16dec(file_header.name_size); if (p + filename_size > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename size"); return (ARCHIVE_FATAL); } if (rar->filename_allocated < filename_size * 2 + 2) { char *newptr; size_t newsize = filename_size * 2 + 2; newptr = realloc(rar->filename, newsize); if (newptr == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->filename = newptr; rar->filename_allocated = newsize; } filename = rar->filename; memcpy(filename, p, filename_size); filename[filename_size] = '\0'; if (rar->file_flags & FHD_UNICODE) { if (filename_size != strlen(filename)) { unsigned char highbyte, flagbits, flagbyte; unsigned fn_end, offset; end = filename_size; fn_end = filename_size * 2; filename_size = 0; offset = (unsigned)strlen(filename) + 1; highbyte = *(p + offset++); flagbits = 0; flagbyte = 0; while (offset < end && filename_size < fn_end) { if (!flagbits) { flagbyte = *(p + offset++); flagbits = 8; } flagbits -= 2; switch((flagbyte >> flagbits) & 3) { case 0: filename[filename_size++] = '\0'; filename[filename_size++] = *(p + offset++); break; case 1: filename[filename_size++] = highbyte; filename[filename_size++] = *(p + offset++); break; case 2: filename[filename_size++] = *(p + offset + 1); filename[filename_size++] = *(p + offset); offset += 2; break; case 3: { char extra, high; uint8_t length = *(p + offset++); if (length & 0x80) { extra = *(p + offset++); high = (char)highbyte; } else extra = high = 0; length = (length & 0x7f) + 2; while (length && filename_size < fn_end) { unsigned cp = filename_size >> 1; filename[filename_size++] = high; filename[filename_size++] = p[cp] + extra; length--; } } break; } } if (filename_size > fn_end) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename"); return (ARCHIVE_FATAL); } filename[filename_size++] = '\0'; filename[filename_size++] = '\0'; /* Decoded unicode form is UTF-16BE, so we have to update a string * conversion object for it. */ if (rar->sconv_utf16be == NULL) { rar->sconv_utf16be = archive_string_conversion_from_charset( &a->archive, "UTF-16BE", 1); if (rar->sconv_utf16be == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf16be; strp = filename; while (memcmp(strp, "\x00\x00", 2)) { if (!memcmp(strp, "\x00\\", 2)) *(strp + 1) = '/'; strp += 2; } p += offset; } else { /* * If FHD_UNICODE is set but no unicode data, this file name form * is UTF-8, so we have to update a string conversion object for * it accordingly. */ if (rar->sconv_utf8 == NULL) { rar->sconv_utf8 = archive_string_conversion_from_charset( &a->archive, "UTF-8", 1); if (rar->sconv_utf8 == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf8; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } } else { fn_sconv = sconv; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } /* Split file in multivolume RAR. No more need to process header. */ if (rar->filename_save && filename_size == rar->filename_save_size && !memcmp(rar->filename, rar->filename_save, filename_size + 1)) { __archive_read_consume(a, header_size - 7); rar->cursor++; if (rar->cursor >= rar->nodes) { rar->nodes++; if ((rar->dbo = realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[rar->cursor].header_size = header_size; rar->dbo[rar->cursor].start_offset = -1; rar->dbo[rar->cursor].end_offset = -1; } if (rar->dbo[rar->cursor].start_offset < 0) { rar->dbo[rar->cursor].start_offset = a->filter->position; rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset + rar->packed_size; } return ret; } rar->filename_save = (char*)realloc(rar->filename_save, filename_size + 1); memcpy(rar->filename_save, rar->filename, filename_size + 1); rar->filename_save_size = filename_size; /* Set info for seeking */ free(rar->dbo); if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[0].header_size = header_size; rar->dbo[0].start_offset = -1; rar->dbo[0].end_offset = -1; rar->cursor = 0; rar->nodes = 1; if (rar->file_flags & FHD_SALT) { if (p + 8 > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } memcpy(rar->salt, p, 8); p += 8; } if (rar->file_flags & FHD_EXTTIME) { if (read_exttime(p, rar, endp) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } } __archive_read_consume(a, header_size - 7); rar->dbo[0].start_offset = a->filter->position; rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size; switch(file_header.host_os) { case OS_MSDOS: case OS_OS2: case OS_WIN32: rar->mode = archive_le32dec(file_header.file_attr); if (rar->mode & FILE_ATTRIBUTE_DIRECTORY) rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; else rar->mode = AE_IFREG; rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case OS_UNIX: case OS_MAC_OS: case OS_BEOS: rar->mode = archive_le32dec(file_header.file_attr); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown file attributes from RAR file's host OS"); return (ARCHIVE_FATAL); } rar->bytes_uncopied = rar->bytes_unconsumed = 0; rar->lzss.position = rar->offset = 0; rar->offset_seek = 0; rar->dictionary_size = 0; rar->offset_outgoing = 0; rar->br.cache_avail = 0; rar->br.avail_in = 0; rar->crc_calculated = 0; rar->entry_eof = 0; rar->valid = 1; rar->is_ppmd_block = 0; rar->start_new_table = 1; free(rar->unp_buffer); rar->unp_buffer = NULL; rar->unp_offset = 0; rar->unp_buffer_size = UNP_BUFFER_SIZE; memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->ppmd_valid = rar->ppmd_eod = 0; /* Don't set any archive entries for non-file header types */ if (head_type == NEWSUB_HEAD) return ret; archive_entry_set_mtime(entry, rar->mtime, rar->mnsec); archive_entry_set_ctime(entry, rar->ctime, rar->cnsec); archive_entry_set_atime(entry, rar->atime, rar->ansec); archive_entry_set_size(entry, rar->unp_size); archive_entry_set_mode(entry, rar->mode); if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(fn_sconv)); ret = (ARCHIVE_WARN); } if (((rar->mode) & AE_IFMT) == AE_IFLNK) { /* Make sure a symbolic-link file does not have its body. */ rar->bytes_remaining = 0; archive_entry_set_size(entry, 0); /* Read a symbolic-link name. */ if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN)) return ret2; if (ret > ret2) ret = ret2; } if (rar->bytes_remaining == 0) rar->entry_eof = 1; return ret; } Commit Message: Avoid a read off-by-one error for UTF16 names in RAR archives. Reported-By: OSS-Fuzz issue 573 CWE ID: CWE-125
read_header(struct archive_read *a, struct archive_entry *entry, char head_type) { const void *h; const char *p, *endp; struct rar *rar; struct rar_header rar_header; struct rar_file_header file_header; int64_t header_size; unsigned filename_size, end; char *filename; char *strp; char packed_size[8]; char unp_size[8]; int ttime; struct archive_string_conv *sconv, *fn_sconv; unsigned long crc32_val; int ret = (ARCHIVE_OK), ret2; rar = (struct rar *)(a->format->data); /* Setup a string conversion object for non-rar-unicode filenames. */ sconv = rar->opt_sconv; if (sconv == NULL) { if (!rar->init_default_conversion) { rar->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); rar->init_default_conversion = 1; } sconv = rar->sconv_default; } if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(&rar_header, p, sizeof(rar_header)); rar->file_flags = archive_le16dec(rar_header.flags); header_size = archive_le16dec(rar_header.size); if (header_size < (int64_t)sizeof(file_header) + 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2); __archive_read_consume(a, 7); if (!(rar->file_flags & FHD_SOLID)) { rar->compression_method = 0; rar->packed_size = 0; rar->unp_size = 0; rar->mtime = 0; rar->ctime = 0; rar->atime = 0; rar->arctime = 0; rar->mode = 0; memset(&rar->salt, 0, sizeof(rar->salt)); rar->atime = 0; rar->ansec = 0; rar->ctime = 0; rar->cnsec = 0; rar->mtime = 0; rar->mnsec = 0; rar->arctime = 0; rar->arcnsec = 0; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR solid archive support unavailable."); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); /* File Header CRC check. */ crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7)); if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } /* If no CRC error, Go on parsing File Header. */ p = h; endp = p + header_size - 7; memcpy(&file_header, p, sizeof(file_header)); p += sizeof(file_header); rar->compression_method = file_header.method; ttime = archive_le32dec(file_header.file_time); rar->mtime = get_time(ttime); rar->file_crc = archive_le32dec(file_header.file_crc); if (rar->file_flags & FHD_PASSWORD) { archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); /* Since it is only the data part itself that is encrypted we can at least extract information about the currently processed entry and don't need to return ARCHIVE_FATAL here. */ /*return (ARCHIVE_FATAL);*/ } if (rar->file_flags & FHD_LARGE) { memcpy(packed_size, file_header.pack_size, 4); memcpy(packed_size + 4, p, 4); /* High pack size */ p += 4; memcpy(unp_size, file_header.unp_size, 4); memcpy(unp_size + 4, p, 4); /* High unpack size */ p += 4; rar->packed_size = archive_le64dec(&packed_size); rar->unp_size = archive_le64dec(&unp_size); } else { rar->packed_size = archive_le32dec(file_header.pack_size); rar->unp_size = archive_le32dec(file_header.unp_size); } if (rar->packed_size < 0 || rar->unp_size < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid sizes specified."); return (ARCHIVE_FATAL); } rar->bytes_remaining = rar->packed_size; /* TODO: RARv3 subblocks contain comments. For now the complete block is * consumed at the end. */ if (head_type == NEWSUB_HEAD) { size_t distance = p - (const char *)h; header_size += rar->packed_size; /* Make sure we have the extended data. */ if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; endp = p + header_size - 7; p += distance; } filename_size = archive_le16dec(file_header.name_size); if (p + filename_size > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename size"); return (ARCHIVE_FATAL); } if (rar->filename_allocated < filename_size * 2 + 2) { char *newptr; size_t newsize = filename_size * 2 + 2; newptr = realloc(rar->filename, newsize); if (newptr == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->filename = newptr; rar->filename_allocated = newsize; } filename = rar->filename; memcpy(filename, p, filename_size); filename[filename_size] = '\0'; if (rar->file_flags & FHD_UNICODE) { if (filename_size != strlen(filename)) { unsigned char highbyte, flagbits, flagbyte; unsigned fn_end, offset; end = filename_size; fn_end = filename_size * 2; filename_size = 0; offset = (unsigned)strlen(filename) + 1; highbyte = *(p + offset++); flagbits = 0; flagbyte = 0; while (offset < end && filename_size < fn_end) { if (!flagbits) { flagbyte = *(p + offset++); flagbits = 8; } flagbits -= 2; switch((flagbyte >> flagbits) & 3) { case 0: filename[filename_size++] = '\0'; filename[filename_size++] = *(p + offset++); break; case 1: filename[filename_size++] = highbyte; filename[filename_size++] = *(p + offset++); break; case 2: filename[filename_size++] = *(p + offset + 1); filename[filename_size++] = *(p + offset); offset += 2; break; case 3: { char extra, high; uint8_t length = *(p + offset++); if (length & 0x80) { extra = *(p + offset++); high = (char)highbyte; } else extra = high = 0; length = (length & 0x7f) + 2; while (length && filename_size < fn_end) { unsigned cp = filename_size >> 1; filename[filename_size++] = high; filename[filename_size++] = p[cp] + extra; length--; } } break; } } if (filename_size > fn_end) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename"); return (ARCHIVE_FATAL); } filename[filename_size++] = '\0'; /* * Do not increment filename_size here as the computations below * add the space for the terminating NUL explicitly. */ filename[filename_size] = '\0'; /* Decoded unicode form is UTF-16BE, so we have to update a string * conversion object for it. */ if (rar->sconv_utf16be == NULL) { rar->sconv_utf16be = archive_string_conversion_from_charset( &a->archive, "UTF-16BE", 1); if (rar->sconv_utf16be == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf16be; strp = filename; while (memcmp(strp, "\x00\x00", 2)) { if (!memcmp(strp, "\x00\\", 2)) *(strp + 1) = '/'; strp += 2; } p += offset; } else { /* * If FHD_UNICODE is set but no unicode data, this file name form * is UTF-8, so we have to update a string conversion object for * it accordingly. */ if (rar->sconv_utf8 == NULL) { rar->sconv_utf8 = archive_string_conversion_from_charset( &a->archive, "UTF-8", 1); if (rar->sconv_utf8 == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf8; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } } else { fn_sconv = sconv; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } /* Split file in multivolume RAR. No more need to process header. */ if (rar->filename_save && filename_size == rar->filename_save_size && !memcmp(rar->filename, rar->filename_save, filename_size + 1)) { __archive_read_consume(a, header_size - 7); rar->cursor++; if (rar->cursor >= rar->nodes) { rar->nodes++; if ((rar->dbo = realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[rar->cursor].header_size = header_size; rar->dbo[rar->cursor].start_offset = -1; rar->dbo[rar->cursor].end_offset = -1; } if (rar->dbo[rar->cursor].start_offset < 0) { rar->dbo[rar->cursor].start_offset = a->filter->position; rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset + rar->packed_size; } return ret; } rar->filename_save = (char*)realloc(rar->filename_save, filename_size + 1); memcpy(rar->filename_save, rar->filename, filename_size + 1); rar->filename_save_size = filename_size; /* Set info for seeking */ free(rar->dbo); if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[0].header_size = header_size; rar->dbo[0].start_offset = -1; rar->dbo[0].end_offset = -1; rar->cursor = 0; rar->nodes = 1; if (rar->file_flags & FHD_SALT) { if (p + 8 > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } memcpy(rar->salt, p, 8); p += 8; } if (rar->file_flags & FHD_EXTTIME) { if (read_exttime(p, rar, endp) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } } __archive_read_consume(a, header_size - 7); rar->dbo[0].start_offset = a->filter->position; rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size; switch(file_header.host_os) { case OS_MSDOS: case OS_OS2: case OS_WIN32: rar->mode = archive_le32dec(file_header.file_attr); if (rar->mode & FILE_ATTRIBUTE_DIRECTORY) rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; else rar->mode = AE_IFREG; rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case OS_UNIX: case OS_MAC_OS: case OS_BEOS: rar->mode = archive_le32dec(file_header.file_attr); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown file attributes from RAR file's host OS"); return (ARCHIVE_FATAL); } rar->bytes_uncopied = rar->bytes_unconsumed = 0; rar->lzss.position = rar->offset = 0; rar->offset_seek = 0; rar->dictionary_size = 0; rar->offset_outgoing = 0; rar->br.cache_avail = 0; rar->br.avail_in = 0; rar->crc_calculated = 0; rar->entry_eof = 0; rar->valid = 1; rar->is_ppmd_block = 0; rar->start_new_table = 1; free(rar->unp_buffer); rar->unp_buffer = NULL; rar->unp_offset = 0; rar->unp_buffer_size = UNP_BUFFER_SIZE; memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->ppmd_valid = rar->ppmd_eod = 0; /* Don't set any archive entries for non-file header types */ if (head_type == NEWSUB_HEAD) return ret; archive_entry_set_mtime(entry, rar->mtime, rar->mnsec); archive_entry_set_ctime(entry, rar->ctime, rar->cnsec); archive_entry_set_atime(entry, rar->atime, rar->ansec); archive_entry_set_size(entry, rar->unp_size); archive_entry_set_mode(entry, rar->mode); if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(fn_sconv)); ret = (ARCHIVE_WARN); } if (((rar->mode) & AE_IFMT) == AE_IFLNK) { /* Make sure a symbolic-link file does not have its body. */ rar->bytes_remaining = 0; archive_entry_set_size(entry, 0); /* Read a symbolic-link name. */ if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN)) return ret2; if (ret > ret2) ret = ret2; } if (rar->bytes_remaining == 0) rar->entry_eof = 1; return ret; }
15,160
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: usage(int iExitCode) { char word[32]; sprintf( word, getJobActionString(mode) ); fprintf( stderr, "Usage: %s [options] [constraints]\n", MyName ); fprintf( stderr, " where [options] is zero or more of:\n" ); fprintf( stderr, " -help Display this message and exit\n" ); fprintf( stderr, " -version Display version information and exit\n" ); fprintf( stderr, " -name schedd_name Connect to the given schedd\n" ); fprintf( stderr, " -pool hostname Use the given central manager to find daemons\n" ); fprintf( stderr, " -addr <ip:port> Connect directly to the given \"sinful string\"\n" ); if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -reason reason Use the given RemoveReason\n"); } else if( mode == JA_RELEASE_JOBS ) { fprintf( stderr, " -reason reason Use the given ReleaseReason\n"); } else if( mode == JA_HOLD_JOBS ) { fprintf( stderr, " -reason reason Use the given HoldReason\n"); fprintf( stderr, " -subcode number Set HoldReasonSubCode\n"); } if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -forcex Force the immediate local removal of jobs in the X state\n" " (only affects jobs already being removed)\n" ); } if( mode == JA_VACATE_JOBS || mode == JA_VACATE_FAST_JOBS ) { fprintf( stderr, " -fast Use a fast vacate (hardkill)\n" ); } fprintf( stderr, " and where [constraints] is one of:\n" ); fprintf( stderr, " cluster.proc %s the given job\n", word ); fprintf( stderr, " cluster %s the given cluster of jobs\n", word ); fprintf( stderr, " user %s all jobs owned by user\n", word ); fprintf( stderr, " -constraint expr %s all jobs matching the boolean expression\n", word ); fprintf( stderr, " -all %s all jobs " "(cannot be used with other constraints)\n", word ); exit( iExitCode ); } Commit Message: CWE ID: CWE-134
usage(int iExitCode) { char word[32]; sprintf( word, "%s", getJobActionString(mode) ); fprintf( stderr, "Usage: %s [options] [constraints]\n", MyName ); fprintf( stderr, " where [options] is zero or more of:\n" ); fprintf( stderr, " -help Display this message and exit\n" ); fprintf( stderr, " -version Display version information and exit\n" ); fprintf( stderr, " -name schedd_name Connect to the given schedd\n" ); fprintf( stderr, " -pool hostname Use the given central manager to find daemons\n" ); fprintf( stderr, " -addr <ip:port> Connect directly to the given \"sinful string\"\n" ); if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -reason reason Use the given RemoveReason\n"); } else if( mode == JA_RELEASE_JOBS ) { fprintf( stderr, " -reason reason Use the given ReleaseReason\n"); } else if( mode == JA_HOLD_JOBS ) { fprintf( stderr, " -reason reason Use the given HoldReason\n"); fprintf( stderr, " -subcode number Set HoldReasonSubCode\n"); } if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) { fprintf( stderr, " -forcex Force the immediate local removal of jobs in the X state\n" " (only affects jobs already being removed)\n" ); } if( mode == JA_VACATE_JOBS || mode == JA_VACATE_FAST_JOBS ) { fprintf( stderr, " -fast Use a fast vacate (hardkill)\n" ); } fprintf( stderr, " and where [constraints] is one of:\n" ); fprintf( stderr, " cluster.proc %s the given job\n", word ); fprintf( stderr, " cluster %s the given cluster of jobs\n", word ); fprintf( stderr, " user %s all jobs owned by user\n", word ); fprintf( stderr, " -constraint expr %s all jobs matching the boolean expression\n", word ); fprintf( stderr, " -all %s all jobs " "(cannot be used with other constraints)\n", word ); exit( iExitCode ); }
370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static void testInspectorDefault(InspectorTest* test, gconstpointer) { test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); test->resizeView(200, 200); test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); test->showAndWaitUntilFinished(false); GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(test->m_inspector); g_assert(inspectorView.get()); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inspectorView.get())); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), ==, 0); Vector<InspectorTest::InspectorEvents>& events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->showAndWaitUntilFinished(true); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Attach); test->m_events.clear(); test->detachAndWaitUntilWindowOpened(); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->closeAndWaitUntilClosed(); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Closed); test->m_events.clear(); } Commit Message: [GTK] Inspector should set a default attached height before being attached https://bugs.webkit.org/show_bug.cgi?id=90767 Reviewed by Xan Lopez. We are currently using the minimum attached height in WebKitWebViewBase as the default height for the inspector when attached. It would be easier for WebKitWebViewBase and embedders implementing attach() if the inspector already had an attached height set when it's being attached. * UIProcess/API/gtk/WebKitWebViewBase.cpp: (webkitWebViewBaseContainerAdd): Don't initialize inspectorViewHeight. (webkitWebViewBaseSetInspectorViewHeight): Allow to set the inspector view height before having an inpector view, but only queue a resize when the view already has an inspector view. * UIProcess/API/gtk/tests/TestInspector.cpp: (testInspectorDefault): (testInspectorManualAttachDetach): * UIProcess/gtk/WebInspectorProxyGtk.cpp: (WebKit::WebInspectorProxy::platformAttach): Set the default attached height before attach the inspector view. git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void testInspectorDefault(InspectorTest* test, gconstpointer) { test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL); test->resizeView(200, 200); test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0); test->waitUntilLoadFinished(); test->showAndWaitUntilFinished(false); GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(test->m_inspector); g_assert(inspectorView.get()); test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inspectorView.get())); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), ==, 0); Vector<InspectorTest::InspectorEvents>& events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->showAndWaitUntilFinished(true); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::BringToFront); test->m_events.clear(); test->resizeViewAndAttach(); g_assert(webkit_web_inspector_is_attached(test->m_inspector)); g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), >=, InspectorTest::gMinimumAttachedInspectorHeight); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Attach); test->m_events.clear(); test->detachAndWaitUntilWindowOpened(); g_assert(!webkit_web_inspector_is_attached(test->m_inspector)); events = test->m_events; g_assert_cmpint(events.size(), ==, 2); g_assert_cmpint(events[0], ==, InspectorTest::Detach); g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow); test->m_events.clear(); test->closeAndWaitUntilClosed(); events = test->m_events; g_assert_cmpint(events.size(), ==, 1); g_assert_cmpint(events[0], ==, InspectorTest::Closed); test->m_events.clear(); }
12,319
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer, raptor_option option, int value) { if(value < 0 || !raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER)) return 1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: if(value) turtle_writer->flags |= TURTLE_WRITER_AUTO_INDENT; else turtle_writer->flags &= ~TURTLE_WRITER_AUTO_INDENT; break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: turtle_writer->indent = value; break; case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: break; /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: return -1; break; } return 0; } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer, raptor_option option, int value) { if(value < 0 || !raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER)) return 1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: if(value) turtle_writer->flags |= TURTLE_WRITER_AUTO_INDENT; else turtle_writer->flags &= ~TURTLE_WRITER_AUTO_INDENT; break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: turtle_writer->indent = value; break; case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: break; /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: return -1; break; } return 0; }
19,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void FragmentPaintPropertyTreeBuilder::UpdateOverflowClip() { DCHECK(properties_); if (NeedsPaintPropertyUpdate()) { if (NeedsOverflowClip(object_) && !CanOmitOverflowClip(object_)) { ClipPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; if (!RuntimeEnabledFeatures::SlimmingPaintV175Enabled() && object_.IsSVGForeignObject()) { state.clip_rect = ToClipRect(ToLayoutBox(object_).FrameRect()); } else if (object_.IsBox()) { state.clip_rect = ToClipRect(ToLayoutBox(object_).OverflowClipRect( context_.current.paint_offset)); state.clip_rect_excluding_overlay_scrollbars = ToClipRect(ToLayoutBox(object_).OverflowClipRect( context_.current.paint_offset, kExcludeOverlayScrollbarSizeForHitTesting)); } else { DCHECK(object_.IsSVGViewportContainer()); const auto& viewport_container = ToLayoutSVGViewportContainer(object_); state.clip_rect = FloatRoundedRect( viewport_container.LocalToSVGParentTransform().Inverse().MapRect( viewport_container.Viewport())); } const ClipPaintPropertyNode* existing = properties_->OverflowClip(); bool equal_ignoring_hit_test_rects = !!existing && existing->EqualIgnoringHitTestRects(context_.current.clip, state); OnUpdateClip(properties_->UpdateOverflowClip(context_.current.clip, std::move(state)), equal_ignoring_hit_test_rects); } else { OnClearClip(properties_->ClearOverflowClip()); } } if (auto* overflow_clip = properties_->OverflowClip()) context_.current.clip = overflow_clip; } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <trchen@chromium.org> > > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > > Cr-Commit-Position: refs/heads/master@{#554626} > > TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> > Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> > Cr-Commit-Position: refs/heads/master@{#554653} TBR=wangxianzhu@chromium.org,trchen@chromium.org,chrishtr@chromium.org # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <wangxianzhu@chromium.org> Reviewed-by: Xianzhu Wang <wangxianzhu@chromium.org> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
void FragmentPaintPropertyTreeBuilder::UpdateOverflowClip() { DCHECK(properties_); if (NeedsPaintPropertyUpdate()) { if (NeedsOverflowClip(object_) && !CanOmitOverflowClip(object_)) { ClipPaintPropertyNode::State state; state.local_transform_space = context_.current.transform; if (!RuntimeEnabledFeatures::SlimmingPaintV175Enabled() && object_.IsSVGForeignObject()) { state.clip_rect = ToClipRect(ToLayoutBox(object_).FrameRect()); } else if (object_.IsBox()) { state.clip_rect = ToClipRect(ToLayoutBox(object_).OverflowClipRect( context_.current.paint_offset)); state.clip_rect_excluding_overlay_scrollbars = ToClipRect(ToLayoutBox(object_).OverflowClipRect( context_.current.paint_offset, kExcludeOverlayScrollbarSizeForHitTesting)); } else { DCHECK(object_.IsSVGViewportContainer()); const auto& viewport_container = ToLayoutSVGViewportContainer(object_); state.clip_rect = FloatRoundedRect( viewport_container.LocalToSVGParentTransform().Inverse().MapRect( viewport_container.Viewport())); } const ClipPaintPropertyNode* existing = properties_->OverflowClip(); bool equal_ignoring_hit_test_rects = !!existing && existing->EqualIgnoringHitTestRects(context_.current.clip, state); OnUpdateClip(properties_->UpdateOverflowClip(*context_.current.clip, std::move(state)), equal_ignoring_hit_test_rects); } else { OnClearClip(properties_->ClearOverflowClip()); } } if (auto* overflow_clip = properties_->OverflowClip()) context_.current.clip = overflow_clip; }
18,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/550 CWE ID: CWE-772
static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) { if (color_image != (Image *) NULL) color_image=DestroyImage(color_image); if (color_image_info != (Image *) NULL) color_image_info=DestroyImageInfo(color_image_info); ThrowReaderException(CorruptImageError,"CorruptImage"); } p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); }
29,403
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: find_file (const char *currpath, grub_fshelp_node_t currroot, grub_fshelp_node_t *currfound, struct grub_fshelp_find_file_closure *c) { #ifndef _MSC_VER char fpath[grub_strlen (currpath) + 1]; #else char *fpath = grub_malloc (grub_strlen (currpath) + 1); #endif char *name = fpath; char *next; enum grub_fshelp_filetype type = GRUB_FSHELP_DIR; grub_fshelp_node_t currnode = currroot; grub_fshelp_node_t oldnode = currroot; c->currroot = currroot; grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1); /* Remove all leading slashes. */ while (*name == '/') name++; if (! *name) { *currfound = currnode; return 0; } for (;;) { int found; struct find_file_closure cc; /* Extract the actual part from the pathname. */ next = grub_strchr (name, '/'); if (next) { /* Remove all leading slashes. */ while (*next == '/') *(next++) = '\0'; } /* At this point it is expected that the current node is a directory, check if this is true. */ if (type != GRUB_FSHELP_DIR) { free_node (currnode, c); return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory"); } cc.name = name; cc.type = &type; cc.oldnode = &oldnode; cc.currnode = &currnode; /* Iterate over the directory. */ found = c->iterate_dir (currnode, iterate, &cc); if (! found) { if (grub_errno) return grub_errno; break; } /* Read in the symlink and follow it. */ if (type == GRUB_FSHELP_SYMLINK) { char *symlink; /* Test if the symlink does not loop. */ if (++(c->symlinknest) == 8) { free_node (currnode, c); free_node (oldnode, c); return grub_error (GRUB_ERR_SYMLINK_LOOP, "too deep nesting of symlinks"); } symlink = c->read_symlink (currnode); free_node (currnode, c); if (!symlink) { free_node (oldnode, c); return grub_errno; } /* The symlink is an absolute path, go back to the root inode. */ if (symlink[0] == '/') { free_node (oldnode, c); oldnode = c->rootnode; } /* Lookup the node the symlink points to. */ find_file (symlink, oldnode, &currnode, c); type = c->foundtype; grub_free (symlink); if (grub_errno) { free_node (oldnode, c); return grub_errno; } } free_node (oldnode, c); /* Found the node! */ if (! next || *next == '\0') { *currfound = currnode; c->foundtype = type; return 0; } name = next; } return grub_error (GRUB_ERR_FILE_NOT_FOUND, "file not found"); } Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack CWE ID: CWE-119
find_file (const char *currpath, grub_fshelp_node_t currroot, grub_fshelp_node_t *currfound, struct grub_fshelp_find_file_closure *c) { char *fpath = grub_malloc (grub_strlen (currpath) + 1); char *name = fpath; char *next; enum grub_fshelp_filetype type = GRUB_FSHELP_DIR; grub_fshelp_node_t currnode = currroot; grub_fshelp_node_t oldnode = currroot; c->currroot = currroot; grub_strncpy (fpath, currpath, grub_strlen (currpath) + 1); /* Remove all leading slashes. */ while (*name == '/') name++; if (! *name) { *currfound = currnode; free (fpath); return 0; } for (;;) { int found; struct find_file_closure cc; /* Extract the actual part from the pathname. */ next = grub_strchr (name, '/'); if (next) { /* Remove all leading slashes. */ while (*next == '/') *(next++) = '\0'; } /* At this point it is expected that the current node is a directory, check if this is true. */ if (type != GRUB_FSHELP_DIR) { free_node (currnode, c); free (fpath); return grub_error (GRUB_ERR_BAD_FILE_TYPE, "not a directory"); } cc.name = name; cc.type = &type; cc.oldnode = &oldnode; cc.currnode = &currnode; /* Iterate over the directory. */ found = c->iterate_dir (currnode, iterate, &cc); if (! found) { if (grub_errno) { free (fpath); return grub_errno; } break; } /* Read in the symlink and follow it. */ if (type == GRUB_FSHELP_SYMLINK) { char *symlink; /* Test if the symlink does not loop. */ if (++(c->symlinknest) == 8) { free_node (currnode, c); free_node (oldnode, c); free (fpath); return grub_error (GRUB_ERR_SYMLINK_LOOP, "too deep nesting of symlinks"); } symlink = c->read_symlink (currnode); free_node (currnode, c); if (!symlink) { free_node (oldnode, c); free (fpath); return grub_errno; } /* The symlink is an absolute path, go back to the root inode. */ if (symlink[0] == '/') { free_node (oldnode, c); oldnode = c->rootnode; } /* Lookup the node the symlink points to. */ find_file (symlink, oldnode, &currnode, c); type = c->foundtype; grub_free (symlink); if (grub_errno) { free_node (oldnode, c); free (fpath); return grub_errno; } } free_node (oldnode, c); /* Found the node! */ if (! next || *next == '\0') { *currfound = currnode; c->foundtype = type; free (fpath); return 0; } name = next; } free (fpath); return grub_error (GRUB_ERR_FILE_NOT_FOUND, "file not found"); }
18,484
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static void br_multicast_del_pg(struct net_bridge *br, struct net_bridge_port_group *pg) { struct net_bridge_mdb_htable *mdb; struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p; struct net_bridge_port_group __rcu **pp; mdb = mlock_dereference(br->mdb, br); mp = br_mdb_ip_get(mdb, &pg->addr); if (WARN_ON(!mp)) return; for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (p != pg) continue; rcu_assign_pointer(*pp, p->next); hlist_del_init(&p->mglist); del_timer(&p->timer); call_rcu_bh(&p->rcu, br_multicast_free_pg); if (!mp->ports && !mp->mglist && netif_running(br->dev)) mod_timer(&mp->timer, jiffies); return; } WARN_ON(1); } Commit Message: bridge: fix some kernel warning in multicast timer Several people reported the warning: "kernel BUG at kernel/timer.c:729!" and the stack trace is: #7 [ffff880214d25c10] mod_timer+501 at ffffffff8106d905 #8 [ffff880214d25c50] br_multicast_del_pg.isra.20+261 at ffffffffa0731d25 [bridge] #9 [ffff880214d25c80] br_multicast_disable_port+88 at ffffffffa0732948 [bridge] #10 [ffff880214d25cb0] br_stp_disable_port+154 at ffffffffa072bcca [bridge] #11 [ffff880214d25ce8] br_device_event+520 at ffffffffa072a4e8 [bridge] #12 [ffff880214d25d18] notifier_call_chain+76 at ffffffff8164aafc #13 [ffff880214d25d50] raw_notifier_call_chain+22 at ffffffff810858f6 #14 [ffff880214d25d60] call_netdevice_notifiers+45 at ffffffff81536aad #15 [ffff880214d25d80] dev_close_many+183 at ffffffff81536d17 #16 [ffff880214d25dc0] rollback_registered_many+168 at ffffffff81537f68 #17 [ffff880214d25de8] rollback_registered+49 at ffffffff81538101 #18 [ffff880214d25e10] unregister_netdevice_queue+72 at ffffffff815390d8 #19 [ffff880214d25e30] __tun_detach+272 at ffffffffa074c2f0 [tun] #20 [ffff880214d25e88] tun_chr_close+45 at ffffffffa074c4bd [tun] #21 [ffff880214d25ea8] __fput+225 at ffffffff8119b1f1 #22 [ffff880214d25ef0] ____fput+14 at ffffffff8119b3fe #23 [ffff880214d25f00] task_work_run+159 at ffffffff8107cf7f #24 [ffff880214d25f30] do_notify_resume+97 at ffffffff810139e1 #25 [ffff880214d25f50] int_signal+18 at ffffffff8164f292 this is due to I forgot to check if mp->timer is armed in br_multicast_del_pg(). This bug is introduced by commit 9f00b2e7cf241fa389733d41b6 (bridge: only expire the mdb entry when query is received). Same for __br_mdb_del(). Tested-by: poma <pomidorabelisima@gmail.com> Reported-by: LiYonghua <809674045@qq.com> Reported-by: Robert Hancock <hancockrwd@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Cc: Stephen Hemminger <stephen@networkplumber.org> Cc: "David S. Miller" <davem@davemloft.net> Signed-off-by: Cong Wang <amwang@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
static void br_multicast_del_pg(struct net_bridge *br, struct net_bridge_port_group *pg) { struct net_bridge_mdb_htable *mdb; struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p; struct net_bridge_port_group __rcu **pp; mdb = mlock_dereference(br->mdb, br); mp = br_mdb_ip_get(mdb, &pg->addr); if (WARN_ON(!mp)) return; for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (p != pg) continue; rcu_assign_pointer(*pp, p->next); hlist_del_init(&p->mglist); del_timer(&p->timer); call_rcu_bh(&p->rcu, br_multicast_free_pg); if (!mp->ports && !mp->mglist && mp->timer_armed && netif_running(br->dev)) mod_timer(&mp->timer, jiffies); return; } WARN_ON(1); }
16,065
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) { REGION16_DATA* newItems; const RECTANGLE_16* srcPtr, *endPtr, *srcExtents; RECTANGLE_16* dstPtr; UINT32 nbRects, usedRects; RECTANGLE_16 common, newExtents; assert(src); assert(src->data); srcPtr = region16_rects(src, &nbRects); if (!nbRects) { region16_clear(dst); return TRUE; } srcExtents = region16_extents(src); if (nbRects == 1) { BOOL intersects = rectangles_intersection(srcExtents, rect, &common); region16_clear(dst); if (intersects) return region16_union_rect(dst, dst, &common); return TRUE; } newItems = allocateRegion(nbRects); if (!newItems) return FALSE; dstPtr = (RECTANGLE_16*)(&newItems[1]); usedRects = 0; ZeroMemory(&newExtents, sizeof(newExtents)); /* accumulate intersecting rectangles, the final region16_simplify_bands() will * do all the bad job to recreate correct rectangles */ for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++) { if (rectangles_intersection(srcPtr, rect, &common)) { *dstPtr = common; usedRects++; dstPtr++; if (rectangle_is_empty(&newExtents)) { /* Check if the existing newExtents is empty. If it is empty, use * new common directly. We do not need to check common rectangle * because the rectangles_intersection() ensures that it is not empty. */ newExtents = common; } else { newExtents.top = MIN(common.top, newExtents.top); newExtents.left = MIN(common.left, newExtents.left); newExtents.bottom = MAX(common.bottom, newExtents.bottom); newExtents.right = MAX(common.right, newExtents.right); } } } newItems->nbRects = usedRects; newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); if ((dst->data->size > 0) && (dst->data != &empty_region)) free(dst->data); dst->data = realloc(newItems, newItems->size); if (!dst->data) { free(newItems); return FALSE; } dst->extents = newExtents; return region16_simplify_bands(dst); } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772
BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) { REGION16_DATA* data; REGION16_DATA* newItems; const RECTANGLE_16* srcPtr, *endPtr, *srcExtents; RECTANGLE_16* dstPtr; UINT32 nbRects, usedRects; RECTANGLE_16 common, newExtents; assert(src); assert(src->data); srcPtr = region16_rects(src, &nbRects); if (!nbRects) { region16_clear(dst); return TRUE; } srcExtents = region16_extents(src); if (nbRects == 1) { BOOL intersects = rectangles_intersection(srcExtents, rect, &common); region16_clear(dst); if (intersects) return region16_union_rect(dst, dst, &common); return TRUE; } newItems = allocateRegion(nbRects); if (!newItems) return FALSE; dstPtr = (RECTANGLE_16*)(&newItems[1]); usedRects = 0; ZeroMemory(&newExtents, sizeof(newExtents)); /* accumulate intersecting rectangles, the final region16_simplify_bands() will * do all the bad job to recreate correct rectangles */ for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++) { if (rectangles_intersection(srcPtr, rect, &common)) { *dstPtr = common; usedRects++; dstPtr++; if (rectangle_is_empty(&newExtents)) { /* Check if the existing newExtents is empty. If it is empty, use * new common directly. We do not need to check common rectangle * because the rectangles_intersection() ensures that it is not empty. */ newExtents = common; } else { newExtents.top = MIN(common.top, newExtents.top); newExtents.left = MIN(common.left, newExtents.left); newExtents.bottom = MAX(common.bottom, newExtents.bottom); newExtents.right = MAX(common.right, newExtents.right); } } } newItems->nbRects = usedRects; newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); if ((dst->data->size > 0) && (dst->data != &empty_region)) free(dst->data); data = realloc(newItems, newItems->size); if (!data) free(dst->data); dst->data = data; if (!dst->data) { free(newItems); return FALSE; } dst->extents = newExtents; return region16_simplify_bands(dst); }
14,514
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void PlatformSensorProviderLinux::CreateSensorAndNotify( mojom::SensorType type, SensorInfoLinux* sensor_device) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); scoped_refptr<PlatformSensorLinux> sensor; mojo::ScopedSharedBufferMapping mapping = MapSharedBufferForType(type); if (sensor_device && mapping && StartPollingThread()) { sensor = new PlatformSensorLinux(type, std::move(mapping), this, sensor_device, polling_thread_->task_runner()); } NotifySensorCreated(type, sensor); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 R=mattcary@chromium.org,alexilin@chromium.org,juncai@chromium.org,reillyg@chromium.org Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <digit@chromium.org> Reviewed-by: Reilly Grant <reillyg@chromium.org> Reviewed-by: Matthew Cary <mattcary@chromium.org> Reviewed-by: Alexandr Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732
void PlatformSensorProviderLinux::CreateSensorAndNotify( mojom::SensorType type, SensorInfoLinux* sensor_device) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); scoped_refptr<PlatformSensorLinux> sensor; SensorReadingSharedBuffer* reading_buffer = GetSensorReadingSharedBufferForType(type); if (sensor_device && reading_buffer && StartPollingThread()) { sensor = new PlatformSensorLinux(type, reading_buffer, this, sensor_device, polling_thread_->task_runner()); } NotifySensorCreated(type, sensor); }
16,957
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool AppCache::AddOrModifyEntry(const GURL& url, const AppCacheEntry& entry) { std::pair<EntryMap::iterator, bool> ret = entries_.insert(EntryMap::value_type(url, entry)); if (!ret.second) ret.first->second.add_types(entry.types()); else cache_size_ += entry.response_size(); // New entry. Add to cache size. return ret.second; } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <staphany@chromium.org> > Reviewed-by: Victor Costan <pwnall@chromium.org> > Reviewed-by: Marijn Kruisselbrink <mek@chromium.org> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <pwnall@chromium.org> Commit-Queue: Staphany Park <staphany@chromium.org> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
bool AppCache::AddOrModifyEntry(const GURL& url, const AppCacheEntry& entry) { std::pair<EntryMap::iterator, bool> ret = entries_.insert(EntryMap::value_type(url, entry)); if (!ret.second) { ret.first->second.add_types(entry.types()); } else { cache_size_ += entry.response_size(); // New entry. Add to cache size. padding_size_ += entry.padding_size(); } return ret.second; }
26,663
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many) { int current; cmap_splay *tree; if (low > high) { fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name); return; } tree = cmap->tree; if (cmap->tlen) { unsigned int move = cmap->ttop; unsigned int gt = EMPTY; unsigned int lt = EMPTY; if (check_for_overlap) { /* Check for collision with the current node */ do { current = move; /* Cases we might meet: * tree[i]: <-----> * case 0: <-> * case 1: <-------> * case 2: <-------------> * case 3: <-> * case 4: <-------> * case 5: <-> */ if (low <= tree[current].low && tree[current].low <= high) { /* case 1, reduces to case 0 */ /* or case 2, deleting the node */ tree[current].out += high + 1 - tree[current].low; tree[current].low = high + 1; if (tree[current].low > tree[current].high) { move = delete_node(cmap, current); current = EMPTY; continue; } } else if (low <= tree[current].high && tree[current].high <= high) { /* case 4, reduces to case 5 */ tree[current].high = low - 1; assert(tree[current].low <= tree[current].high); } else if (tree[current].low < low && high < tree[current].high) { /* case 3, reduces to case 5 */ int new_high = tree[current].high; tree[current].high = low-1; add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, many); } /* Now look for where to move to next (left for case 0, right for case 5) */ if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } else { do { current = move; if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } /* current is now the node to which we would be adding the new node */ /* lt is the last node we traversed which is lt the new node. */ /* gt is the last node we traversed which is gt the new node. */ if (!many) { /* Check for the 'merge' cases. */ if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low) { tree[lt].high = high; if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[lt].high = tree[gt].high; delete_node(cmap, gt); } goto exit; } if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[gt].low = low; tree[gt].out = out; goto exit; } } } else current = EMPTY; if (cmap->tlen == cmap->tcap) { int new_cap = cmap->tcap ? cmap->tcap * 2 : 256; tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree); cmap->tcap = new_cap; } tree[cmap->tlen].low = low; tree[cmap->tlen].high = high; tree[cmap->tlen].out = out; tree[cmap->tlen].parent = current; tree[cmap->tlen].left = EMPTY; tree[cmap->tlen].right = EMPTY; tree[cmap->tlen].many = many; cmap->tlen++; if (current == EMPTY) cmap->ttop = 0; else if (tree[current].low > high) tree[current].left = cmap->tlen-1; else { assert(tree[current].high < low); tree[current].right = cmap->tlen-1; } move_to_root(tree, cmap->tlen-1); cmap->ttop = cmap->tlen-1; exit: {} #ifdef CHECK_SPLAY check_splay(cmap->tree, cmap->ttop, 0); #endif #ifdef DUMP_SPLAY dump_splay(cmap->tree, cmap->ttop, 0, ""); #endif } Commit Message: CWE ID: CWE-416
add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many) { int current; cmap_splay *tree; if (low > high) { fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name); return; } tree = cmap->tree; if (cmap->tlen) { unsigned int move = cmap->ttop; unsigned int gt = EMPTY; unsigned int lt = EMPTY; if (check_for_overlap) { /* Check for collision with the current node */ do { current = move; /* Cases we might meet: * tree[i]: <-----> * case 0: <-> * case 1: <-------> * case 2: <-------------> * case 3: <-> * case 4: <-------> * case 5: <-> */ if (low <= tree[current].low && tree[current].low <= high) { /* case 1, reduces to case 0 */ /* or case 2, deleting the node */ tree[current].out += high + 1 - tree[current].low; tree[current].low = high + 1; if (tree[current].low > tree[current].high) { move = delete_node(cmap, current); current = EMPTY; continue; } } else if (low <= tree[current].high && tree[current].high <= high) { /* case 4, reduces to case 5 */ tree[current].high = low - 1; assert(tree[current].low <= tree[current].high); } else if (tree[current].low < low && high < tree[current].high) { /* case 3, reduces to case 5 */ int new_high = tree[current].high; tree[current].high = low-1; add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many); } /* Now look for where to move to next (left for case 0, right for case 5) */ if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } else { do { current = move; if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } /* current is now the node to which we would be adding the new node */ /* lt is the last node we traversed which is lt the new node. */ /* gt is the last node we traversed which is gt the new node. */ if (!many) { /* Check for the 'merge' cases. */ if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low) { tree[lt].high = high; if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[lt].high = tree[gt].high; delete_node(cmap, gt); } goto exit; } if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[gt].low = low; tree[gt].out = out; goto exit; } } } else current = EMPTY; if (cmap->tlen == cmap->tcap) { int new_cap = cmap->tcap ? cmap->tcap * 2 : 256; tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree); cmap->tcap = new_cap; } tree[cmap->tlen].low = low; tree[cmap->tlen].high = high; tree[cmap->tlen].out = out; tree[cmap->tlen].parent = current; tree[cmap->tlen].left = EMPTY; tree[cmap->tlen].right = EMPTY; tree[cmap->tlen].many = many; cmap->tlen++; if (current == EMPTY) cmap->ttop = 0; else if (tree[current].low > high) tree[current].left = cmap->tlen-1; else { assert(tree[current].high < low); tree[current].right = cmap->tlen-1; } move_to_root(tree, cmap->tlen-1); cmap->ttop = cmap->tlen-1; exit: {} #ifdef CHECK_SPLAY check_splay(cmap->tree, cmap->ttop, 0); #endif #ifdef DUMP_SPLAY dump_splay(cmap->tree, cmap->ttop, 0, ""); #endif }
1,602
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int skcipher_accept_parent(void *private, struct sock *sk) { struct skcipher_ctx *ctx; struct alg_sock *ask = alg_sk(sk); unsigned int len = sizeof(*ctx) + crypto_skcipher_reqsize(private); ctx = sock_kmalloc(sk, len, GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->iv = sock_kmalloc(sk, crypto_skcipher_ivsize(private), GFP_KERNEL); if (!ctx->iv) { sock_kfree_s(sk, ctx, len); return -ENOMEM; } memset(ctx->iv, 0, crypto_skcipher_ivsize(private)); INIT_LIST_HEAD(&ctx->tsgl); ctx->len = len; ctx->used = 0; ctx->more = 0; ctx->merge = 0; ctx->enc = 0; atomic_set(&ctx->inflight, 0); af_alg_init_completion(&ctx->completion); ask->private = ctx; skcipher_request_set_tfm(&ctx->req, private); skcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG, af_alg_complete, &ctx->completion); sk->sk_destruct = skcipher_sock_destruct; return 0; } Commit Message: crypto: algif_skcipher - Require setkey before accept(2) Some cipher implementations will crash if you try to use them without calling setkey first. This patch adds a check so that the accept(2) call will fail with -ENOKEY if setkey hasn't been done on the socket yet. Cc: stable@vger.kernel.org Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> Tested-by: Dmitry Vyukov <dvyukov@google.com> CWE ID: CWE-476
static int skcipher_accept_parent(void *private, struct sock *sk) { struct skcipher_ctx *ctx; struct alg_sock *ask = alg_sk(sk); struct skcipher_tfm *tfm = private; struct crypto_skcipher *skcipher = tfm->skcipher; unsigned int len = sizeof(*ctx) + crypto_skcipher_reqsize(skcipher); if (!tfm->has_key) return -ENOKEY; ctx = sock_kmalloc(sk, len, GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->iv = sock_kmalloc(sk, crypto_skcipher_ivsize(skcipher), GFP_KERNEL); if (!ctx->iv) { sock_kfree_s(sk, ctx, len); return -ENOMEM; } memset(ctx->iv, 0, crypto_skcipher_ivsize(skcipher)); INIT_LIST_HEAD(&ctx->tsgl); ctx->len = len; ctx->used = 0; ctx->more = 0; ctx->merge = 0; ctx->enc = 0; atomic_set(&ctx->inflight, 0); af_alg_init_completion(&ctx->completion); ask->private = ctx; skcipher_request_set_tfm(&ctx->req, skcipher); skcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG, af_alg_complete, &ctx->completion); sk->sk_destruct = skcipher_sock_destruct; return 0; }
4,650
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port) { char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL; char url_address[256], port[6]; int url_len, port_len = 0; *sockaddr_url = url; url_begin = strstr(url, "//"); if (!url_begin) url_begin = url; else url_begin += 2; /* Look for numeric ipv6 entries */ ipv6_begin = strstr(url_begin, "["); ipv6_end = strstr(url_begin, "]"); if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) url_end = strstr(ipv6_end, ":"); else url_end = strstr(url_begin, ":"); if (url_end) { url_len = url_end - url_begin; port_len = strlen(url_begin) - url_len - 1; if (port_len < 1) return false; port_start = url_end + 1; } else url_len = strlen(url_begin); if (url_len < 1) return false; sprintf(url_address, "%.*s", url_len, url_begin); if (port_len) { char *slash; snprintf(port, 6, "%.*s", port_len, port_start); slash = strchr(port, '/'); if (slash) *slash = '\0'; } else strcpy(port, "80"); *sockaddr_port = strdup(port); *sockaddr_url = strdup(url_address); return true; } Commit Message: Do some random sanity checking for stratum message parsing CWE ID: CWE-119
bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port) { char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL; char url_address[256], port[6]; int url_len, port_len = 0; *sockaddr_url = url; url_begin = strstr(url, "//"); if (!url_begin) url_begin = url; else url_begin += 2; /* Look for numeric ipv6 entries */ ipv6_begin = strstr(url_begin, "["); ipv6_end = strstr(url_begin, "]"); if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) url_end = strstr(ipv6_end, ":"); else url_end = strstr(url_begin, ":"); if (url_end) { url_len = url_end - url_begin; port_len = strlen(url_begin) - url_len - 1; if (port_len < 1) return false; port_start = url_end + 1; } else url_len = strlen(url_begin); if (url_len < 1) return false; snprintf(url_address, 254, "%.*s", url_len, url_begin); if (port_len) { char *slash; snprintf(port, 6, "%.*s", port_len, port_start); slash = strchr(port, '/'); if (slash) *slash = '\0'; } else strcpy(port, "80"); *sockaddr_port = strdup(port); *sockaddr_url = strdup(url_address); return true; }
12,330
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void PrintPreviewUI::OnDidPreviewPage(int page_number, int preview_request_id) { DCHECK_GE(page_number, 0); base::FundamentalValue number(page_number); StringValue ui_identifier(preview_ui_addr_str_); base::FundamentalValue request_id(preview_request_id); web_ui()->CallJavascriptFunction( "onDidPreviewPage", number, ui_identifier, request_id); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnDidPreviewPage(int page_number, int preview_request_id) { DCHECK_GE(page_number, 0); base::FundamentalValue number(page_number); base::FundamentalValue ui_identifier(id_); base::FundamentalValue request_id(preview_request_id); web_ui()->CallJavascriptFunction( "onDidPreviewPage", number, ui_identifier, request_id); }
26,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq) { SCEnter(); uint8_t *orig_pkt = pkt; uint8_t nh = 0; /* careful, 0 is actually a real type */ uint16_t hdrextlen = 0; uint16_t plen; char dstopts = 0; char exthdr_fh_done = 0; int hh = 0; int rh = 0; int eh = 0; int ah = 0; nh = IPV6_GET_NH(p); plen = len; while(1) { /* No upper layer, but we do have data. Suspicious. */ if (nh == IPPROTO_NONE && plen > 0) { ENGINE_SET_EVENT(p, IPV6_DATA_AFTER_NONE_HEADER); SCReturn; } if (plen < 2) { /* minimal needed in a hdr */ SCReturn; } switch(nh) { case IPPROTO_TCP: IPV6_SET_L4PROTO(p,nh); DecodeTCP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_UDP: IPV6_SET_L4PROTO(p,nh); DecodeUDP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_ICMPV6: IPV6_SET_L4PROTO(p,nh); DecodeICMPV6(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_SCTP: IPV6_SET_L4PROTO(p,nh); DecodeSCTP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_ROUTING: IPV6_SET_L4PROTO(p,nh); hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */ SCLogDebug("hdrextlen %"PRIu8, hdrextlen); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } if (rh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_RH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } rh = 1; IPV6_EXTHDR_SET_RH(p); uint8_t ip6rh_type = *(pkt + 2); if (ip6rh_type == 0) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_RH_TYPE_0); } p->ip6eh.rh_type = ip6rh_type; nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; case IPPROTO_HOPOPTS: case IPPROTO_DSTOPTS: { IPV6OptHAO hao_s, *hao = &hao_s; IPV6OptRA ra_s, *ra = &ra_s; IPV6OptJumbo jumbo_s, *jumbo = &jumbo_s; uint16_t optslen = 0; IPV6_SET_L4PROTO(p,nh); hdrextlen = (*(pkt+1) + 1) << 3; if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } uint8_t *ptr = pkt + 2; /* +2 to go past nxthdr and len */ /* point the pointers to right structures * in Packet. */ if (nh == IPPROTO_HOPOPTS) { if (hh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_HH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } hh = 1; optslen = ((*(pkt + 1) + 1 ) << 3) - 2; } else if (nh == IPPROTO_DSTOPTS) { if (dstopts == 0) { optslen = ((*(pkt + 1) + 1 ) << 3) - 2; dstopts = 1; } else if (dstopts == 1) { optslen = ((*(pkt + 1) + 1 ) << 3) - 2; dstopts = 2; } else { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_DH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } } if (optslen > plen) { /* since the packet is long enough (we checked * plen against hdrlen, the optlen must be malformed. */ ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /** \todo move into own function to loaded on demand */ uint16_t padn_cnt = 0; uint16_t other_cnt = 0; uint16_t offset = 0; while(offset < optslen) { if (*ptr == IPV6OPT_PAD1) { padn_cnt++; offset++; ptr++; continue; } if (offset + 1 >= optslen) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } /* length field for each opt */ uint8_t ip6_optlen = *(ptr + 1); /* see if the optlen from the packet fits the total optslen */ if ((offset + 1 + ip6_optlen) > optslen) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } if (*ptr == IPV6OPT_PADN) /* PadN */ { padn_cnt++; /* a zero padN len would be weird */ if (ip6_optlen == 0) ENGINE_SET_EVENT(p, IPV6_EXTHDR_ZERO_LEN_PADN); } else if (*ptr == IPV6OPT_RA) /* RA */ { ra->ip6ra_type = *(ptr); ra->ip6ra_len = ip6_optlen; if (ip6_optlen < sizeof(ra->ip6ra_value)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&ra->ip6ra_value, (ptr + 2), sizeof(ra->ip6ra_value)); ra->ip6ra_value = SCNtohs(ra->ip6ra_value); other_cnt++; } else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */ { jumbo->ip6j_type = *(ptr); jumbo->ip6j_len = ip6_optlen; if (ip6_optlen < sizeof(jumbo->ip6j_payload_len)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&jumbo->ip6j_payload_len, (ptr+2), sizeof(jumbo->ip6j_payload_len)); jumbo->ip6j_payload_len = SCNtohl(jumbo->ip6j_payload_len); } else if (*ptr == IPV6OPT_HAO) /* HAO */ { hao->ip6hao_type = *(ptr); hao->ip6hao_len = ip6_optlen; if (ip6_optlen < sizeof(hao->ip6hao_hoa)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&hao->ip6hao_hoa, (ptr+2), sizeof(hao->ip6hao_hoa)); other_cnt++; } else { if (nh == IPPROTO_HOPOPTS) ENGINE_SET_EVENT(p, IPV6_HOPOPTS_UNKNOWN_OPT); else ENGINE_SET_EVENT(p, IPV6_DSTOPTS_UNKNOWN_OPT); other_cnt++; } uint16_t optlen = (*(ptr + 1) + 2); ptr += optlen; /* +2 for opt type and opt len fields */ offset += optlen; } /* flag packets that have only padding */ if (padn_cnt > 0 && other_cnt == 0) { if (nh == IPPROTO_HOPOPTS) ENGINE_SET_EVENT(p, IPV6_HOPOPTS_ONLY_PADDING); else ENGINE_SET_EVENT(p, IPV6_DSTOPTS_ONLY_PADDING); } nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_FRAGMENT: { IPV6_SET_L4PROTO(p,nh); /* store the offset of this extension into the packet * past the ipv6 header. We use it in defrag for creating * a defragmented packet without the frag header */ if (exthdr_fh_done == 0) { p->ip6eh.fh_offset = pkt - orig_pkt; exthdr_fh_done = 1; } uint16_t prev_hdrextlen = hdrextlen; hdrextlen = sizeof(IPV6FragHdr); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } /* for the frag header, the length field is reserved */ if (*(pkt + 1) != 0) { ENGINE_SET_EVENT(p, IPV6_FH_NON_ZERO_RES_FIELD); /* non fatal, lets try to continue */ } if (IPV6_EXTHDR_ISSET_FH(p)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_FH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /* set the header flag first */ IPV6_EXTHDR_SET_FH(p); /* parse the header and setup the vars */ DecodeIPV6FragHeader(p, pkt, hdrextlen, plen, prev_hdrextlen); /* if FH has offset 0 and no more fragments are coming, we * parse this packet further right away, no defrag will be * needed. It is a useless FH then though, so we do set an * decoder event. */ if (p->ip6eh.fh_more_frags_set == 0 && p->ip6eh.fh_offset == 0) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_USELESS_FH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /* the rest is parsed upon reassembly */ p->flags |= PKT_IS_FRAGMENT; SCReturn; } case IPPROTO_ESP: { IPV6_SET_L4PROTO(p,nh); hdrextlen = sizeof(IPV6EspHdr); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } if (eh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_EH); SCReturn; } eh = 1; nh = IPPROTO_NONE; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_AH: { IPV6_SET_L4PROTO(p,nh); /* we need the header as a minimum */ hdrextlen = sizeof(IPV6AuthHdr); /* the payload len field is the number of extra 4 byte fields, * IPV6AuthHdr already contains the first */ if (*(pkt+1) > 0) hdrextlen += ((*(pkt+1) - 1) * 4); SCLogDebug("hdrextlen %"PRIu8, hdrextlen); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } IPV6AuthHdr *ahhdr = (IPV6AuthHdr *)pkt; if (ahhdr->ip6ah_reserved != 0x0000) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_AH_RES_NOT_NULL); } if (ah) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_AH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } ah = 1; nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_IPIP: IPV6_SET_L4PROTO(p,nh); DecodeIPv4inIPv6(tv, dtv, p, pkt, plen, pq); SCReturn; /* none, last header */ case IPPROTO_NONE: IPV6_SET_L4PROTO(p,nh); SCReturn; case IPPROTO_ICMP: ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4); SCReturn; /* no parsing yet, just skip it */ case IPPROTO_MH: case IPPROTO_HIP: case IPPROTO_SHIM6: hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */ if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; default: ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER); IPV6_SET_L4PROTO(p,nh); SCReturn; } } SCReturn; } Commit Message: teredo: be stricter on what to consider valid teredo Invalid Teredo can lead to valid DNS traffic (or other UDP traffic) being misdetected as Teredo. This leads to false negatives in the UDP payload inspection. Make the teredo code only consider a packet teredo if the encapsulated data was decoded without any 'invalid' events being set. Bug #2736. CWE ID: CWE-20
DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq) { SCEnter(); uint8_t *orig_pkt = pkt; uint8_t nh = IPV6_GET_NH(p); /* careful, 0 is actually a real type */ uint16_t hdrextlen = 0; uint16_t plen = len; char dstopts = 0; char exthdr_fh_done = 0; int hh = 0; int rh = 0; int eh = 0; int ah = 0; while(1) { if (nh == IPPROTO_NONE) { if (plen > 0) { /* No upper layer, but we do have data. Suspicious. */ ENGINE_SET_EVENT(p, IPV6_DATA_AFTER_NONE_HEADER); } SCReturn; } if (plen < 2) { /* minimal needed in a hdr */ ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } switch(nh) { case IPPROTO_TCP: IPV6_SET_L4PROTO(p,nh); DecodeTCP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_UDP: IPV6_SET_L4PROTO(p,nh); DecodeUDP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_ICMPV6: IPV6_SET_L4PROTO(p,nh); DecodeICMPV6(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_SCTP: IPV6_SET_L4PROTO(p,nh); DecodeSCTP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_ROUTING: IPV6_SET_L4PROTO(p,nh); hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */ SCLogDebug("hdrextlen %"PRIu8, hdrextlen); if (hdrextlen > plen) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } if (rh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_RH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } rh = 1; IPV6_EXTHDR_SET_RH(p); uint8_t ip6rh_type = *(pkt + 2); if (ip6rh_type == 0) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_RH_TYPE_0); } p->ip6eh.rh_type = ip6rh_type; nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; case IPPROTO_HOPOPTS: case IPPROTO_DSTOPTS: { IPV6OptHAO hao_s, *hao = &hao_s; IPV6OptRA ra_s, *ra = &ra_s; IPV6OptJumbo jumbo_s, *jumbo = &jumbo_s; uint16_t optslen = 0; IPV6_SET_L4PROTO(p,nh); hdrextlen = (*(pkt+1) + 1) << 3; if (hdrextlen > plen) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } uint8_t *ptr = pkt + 2; /* +2 to go past nxthdr and len */ /* point the pointers to right structures * in Packet. */ if (nh == IPPROTO_HOPOPTS) { if (hh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_HH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } hh = 1; optslen = ((*(pkt + 1) + 1 ) << 3) - 2; } else if (nh == IPPROTO_DSTOPTS) { if (dstopts == 0) { optslen = ((*(pkt + 1) + 1 ) << 3) - 2; dstopts = 1; } else if (dstopts == 1) { optslen = ((*(pkt + 1) + 1 ) << 3) - 2; dstopts = 2; } else { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_DH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } } if (optslen > plen) { /* since the packet is long enough (we checked * plen against hdrlen, the optlen must be malformed. */ ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /** \todo move into own function to loaded on demand */ uint16_t padn_cnt = 0; uint16_t other_cnt = 0; uint16_t offset = 0; while(offset < optslen) { if (*ptr == IPV6OPT_PAD1) { padn_cnt++; offset++; ptr++; continue; } if (offset + 1 >= optslen) { ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } /* length field for each opt */ uint8_t ip6_optlen = *(ptr + 1); /* see if the optlen from the packet fits the total optslen */ if ((offset + 1 + ip6_optlen) > optslen) { ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } if (*ptr == IPV6OPT_PADN) /* PadN */ { padn_cnt++; /* a zero padN len would be weird */ if (ip6_optlen == 0) ENGINE_SET_EVENT(p, IPV6_EXTHDR_ZERO_LEN_PADN); } else if (*ptr == IPV6OPT_RA) /* RA */ { ra->ip6ra_type = *(ptr); ra->ip6ra_len = ip6_optlen; if (ip6_optlen < sizeof(ra->ip6ra_value)) { ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&ra->ip6ra_value, (ptr + 2), sizeof(ra->ip6ra_value)); ra->ip6ra_value = SCNtohs(ra->ip6ra_value); other_cnt++; } else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */ { jumbo->ip6j_type = *(ptr); jumbo->ip6j_len = ip6_optlen; if (ip6_optlen < sizeof(jumbo->ip6j_payload_len)) { ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&jumbo->ip6j_payload_len, (ptr+2), sizeof(jumbo->ip6j_payload_len)); jumbo->ip6j_payload_len = SCNtohl(jumbo->ip6j_payload_len); } else if (*ptr == IPV6OPT_HAO) /* HAO */ { hao->ip6hao_type = *(ptr); hao->ip6hao_len = ip6_optlen; if (ip6_optlen < sizeof(hao->ip6hao_hoa)) { ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&hao->ip6hao_hoa, (ptr+2), sizeof(hao->ip6hao_hoa)); other_cnt++; } else { if (nh == IPPROTO_HOPOPTS) ENGINE_SET_EVENT(p, IPV6_HOPOPTS_UNKNOWN_OPT); else ENGINE_SET_EVENT(p, IPV6_DSTOPTS_UNKNOWN_OPT); other_cnt++; } uint16_t optlen = (*(ptr + 1) + 2); ptr += optlen; /* +2 for opt type and opt len fields */ offset += optlen; } /* flag packets that have only padding */ if (padn_cnt > 0 && other_cnt == 0) { if (nh == IPPROTO_HOPOPTS) ENGINE_SET_EVENT(p, IPV6_HOPOPTS_ONLY_PADDING); else ENGINE_SET_EVENT(p, IPV6_DSTOPTS_ONLY_PADDING); } nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_FRAGMENT: { IPV6_SET_L4PROTO(p,nh); /* store the offset of this extension into the packet * past the ipv6 header. We use it in defrag for creating * a defragmented packet without the frag header */ if (exthdr_fh_done == 0) { p->ip6eh.fh_offset = pkt - orig_pkt; exthdr_fh_done = 1; } uint16_t prev_hdrextlen = hdrextlen; hdrextlen = sizeof(IPV6FragHdr); if (hdrextlen > plen) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } /* for the frag header, the length field is reserved */ if (*(pkt + 1) != 0) { ENGINE_SET_EVENT(p, IPV6_FH_NON_ZERO_RES_FIELD); /* non fatal, lets try to continue */ } if (IPV6_EXTHDR_ISSET_FH(p)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_FH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /* set the header flag first */ IPV6_EXTHDR_SET_FH(p); /* parse the header and setup the vars */ DecodeIPV6FragHeader(p, pkt, hdrextlen, plen, prev_hdrextlen); /* if FH has offset 0 and no more fragments are coming, we * parse this packet further right away, no defrag will be * needed. It is a useless FH then though, so we do set an * decoder event. */ if (p->ip6eh.fh_more_frags_set == 0 && p->ip6eh.fh_offset == 0) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_USELESS_FH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /* the rest is parsed upon reassembly */ p->flags |= PKT_IS_FRAGMENT; SCReturn; } case IPPROTO_ESP: { IPV6_SET_L4PROTO(p,nh); hdrextlen = sizeof(IPV6EspHdr); if (hdrextlen > plen) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } if (eh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_EH); SCReturn; } eh = 1; nh = IPPROTO_NONE; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_AH: { IPV6_SET_L4PROTO(p,nh); /* we need the header as a minimum */ hdrextlen = sizeof(IPV6AuthHdr); /* the payload len field is the number of extra 4 byte fields, * IPV6AuthHdr already contains the first */ if (*(pkt+1) > 0) hdrextlen += ((*(pkt+1) - 1) * 4); SCLogDebug("hdrextlen %"PRIu8, hdrextlen); if (hdrextlen > plen) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } IPV6AuthHdr *ahhdr = (IPV6AuthHdr *)pkt; if (ahhdr->ip6ah_reserved != 0x0000) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_AH_RES_NOT_NULL); } if (ah) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_AH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } ah = 1; nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_IPIP: IPV6_SET_L4PROTO(p,nh); DecodeIPv4inIPv6(tv, dtv, p, pkt, plen, pq); SCReturn; /* none, last header */ case IPPROTO_NONE: IPV6_SET_L4PROTO(p,nh); SCReturn; case IPPROTO_ICMP: ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4); SCReturn; /* no parsing yet, just skip it */ case IPPROTO_MH: case IPPROTO_HIP: case IPPROTO_SHIM6: hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */ if (hdrextlen > plen) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; default: ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER); IPV6_SET_L4PROTO(p,nh); SCReturn; } } SCReturn; }
29,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void perf_bp_event(struct perf_event *bp, void *data) { struct perf_sample_data sample; struct pt_regs *regs = data; perf_sample_data_init(&sample, bp->attr.bp_addr); if (!bp->hw.state && !perf_exclude_event(bp, regs)) perf_swevent_event(bp, 1, 1, &sample, regs); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <a.p.zijlstra@chello.nl> Cc: Michael Cree <mcree@orcon.net.nz> Cc: Will Deacon <will.deacon@arm.com> Cc: Deng-Cheng Zhu <dengcheng.zhu@gmail.com> Cc: Anton Blanchard <anton@samba.org> Cc: Eric B Munson <emunson@mgebm.net> Cc: Heiko Carstens <heiko.carstens@de.ibm.com> Cc: Paul Mundt <lethal@linux-sh.org> Cc: David S. Miller <davem@davemloft.net> Cc: Frederic Weisbecker <fweisbec@gmail.com> Cc: Jason Wessel <jason.wessel@windriver.com> Cc: Don Zickus <dzickus@redhat.com> Link: http://lkml.kernel.org/n/tip-agjev8eu666tvknpb3iaj0fg@git.kernel.org Signed-off-by: Ingo Molnar <mingo@elte.hu> CWE ID: CWE-399
void perf_bp_event(struct perf_event *bp, void *data) { struct perf_sample_data sample; struct pt_regs *regs = data; perf_sample_data_init(&sample, bp->attr.bp_addr); if (!bp->hw.state && !perf_exclude_event(bp, regs)) perf_swevent_event(bp, 1, &sample, regs); }
16,001
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: int snmp_helper(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { struct snmp_ctx *ctx = (struct snmp_ctx *)context; __be32 *pdata = (__be32 *)data; if (*pdata == ctx->from) { pr_debug("%s: %pI4 to %pI4\n", __func__, (void *)&ctx->from, (void *)&ctx->to); if (*ctx->check) fast_csum(ctx, (unsigned char *)data - ctx->begin); *pdata = ctx->to; } return 1; } Commit Message: netfilter: nf_nat_snmp_basic: add missing length checks in ASN.1 cbs The generic ASN.1 decoder infrastructure doesn't guarantee that callbacks will get as much data as they expect; callbacks have to check the `datalen` parameter before looking at `data`. Make sure that snmp_version() and snmp_helper() don't read/write beyond the end of the packet data. (Also move the assignment to `pdata` down below the check to make it clear that it isn't necessarily a pointer we can use before the `datalen` check.) Fixes: cc2d58634e0f ("netfilter: nf_nat_snmp_basic: use asn1 decoder library") Signed-off-by: Jann Horn <jannh@google.com> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-129
int snmp_helper(void *context, size_t hdrlen, unsigned char tag, const void *data, size_t datalen) { struct snmp_ctx *ctx = (struct snmp_ctx *)context; __be32 *pdata; if (datalen != 4) return -EINVAL; pdata = (__be32 *)data; if (*pdata == ctx->from) { pr_debug("%s: %pI4 to %pI4\n", __func__, (void *)&ctx->from, (void *)&ctx->to); if (*ctx->check) fast_csum(ctx, (unsigned char *)data - ctx->begin); *pdata = ctx->to; } return 1; }
22,434
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } Commit Message: Slightly different fix for #714 CWE ID: CWE-834
static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); }
2,406
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size) { unsigned int u = 0; LineContribType *res; int overflow_error = 0; res = (LineContribType *) gdMalloc(sizeof(LineContribType)); if (!res) { return NULL; } res->WindowSize = windows_size; res->LineLength = line_length; if (overflow2(line_length, sizeof(ContributionType))) { gdFree(res); return NULL; } res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType)); if (res->ContribRow == NULL) { gdFree(res); return NULL; } for (u = 0 ; u < line_length ; u++) { if (overflow2(windows_size, sizeof(double))) { overflow_error = 1; } else { res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double)); } if (overflow_error == 1 || res->ContribRow[u].Weights == NULL) { unsigned int i; u--; for (i=0;i<=u;i++) { gdFree(res->ContribRow[i].Weights); } gdFree(res->ContribRow); gdFree(res); return NULL; } } return res; } Commit Message: Fix potential unsigned underflow No need to decrease `u`, so we don't do it. While we're at it, we also factor out the overflow check of the loop, what improves performance and readability. This issue has been reported by Stefan Esser to security@libgd.org. CWE ID: CWE-191
static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size) { unsigned int u = 0; LineContribType *res; size_t weights_size; if (overflow2(windows_size, sizeof(double))) { return NULL; } else { weights_size = windows_size * sizeof(double); } res = (LineContribType *) gdMalloc(sizeof(LineContribType)); if (!res) { return NULL; } res->WindowSize = windows_size; res->LineLength = line_length; if (overflow2(line_length, sizeof(ContributionType))) { gdFree(res); return NULL; } res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType)); if (res->ContribRow == NULL) { gdFree(res); return NULL; } for (u = 0 ; u < line_length ; u++) { res->ContribRow[u].Weights = (double *) gdMalloc(weights_size); if (res->ContribRow[u].Weights == NULL) { unsigned int i; for (i=0;i<u;i++) { gdFree(res->ContribRow[i].Weights); } gdFree(res->ContribRow); gdFree(res); return NULL; } } return res; }
7,703
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: void CancelHandwriting(int n_strokes) { IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_cancel_hand_writing(context, n_strokes); g_object_unref(context); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CancelHandwriting(int n_strokes) { // IBusController override. virtual void CancelHandwriting(int n_strokes) { IBusInputContext* context = GetInputContext(input_context_path_, ibus_); if (!context) { return; } ibus_input_context_cancel_hand_writing(context, n_strokes); g_object_unref(context); }
5,395
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: std::string ExtensionTtsController::GetMatchingExtensionId( Utterance* utterance) { ExtensionService* service = utterance->profile()->GetExtensionService(); DCHECK(service); ExtensionEventRouter* event_router = utterance->profile()->GetExtensionEventRouter(); DCHECK(event_router); const ExtensionList* extensions = service->extensions(); ExtensionList::const_iterator iter; for (iter = extensions->begin(); iter != extensions->end(); ++iter) { const Extension* extension = *iter; if (!event_router->ExtensionHasEventListener( extension->id(), events::kOnSpeak) || !event_router->ExtensionHasEventListener( extension->id(), events::kOnStop)) { continue; } const std::vector<Extension::TtsVoice>& tts_voices = extension->tts_voices(); for (size_t i = 0; i < tts_voices.size(); ++i) { const Extension::TtsVoice& voice = tts_voices[i]; if (!voice.voice_name.empty() && !utterance->voice_name().empty() && voice.voice_name != utterance->voice_name()) { continue; } if (!voice.locale.empty() && !utterance->locale().empty() && voice.locale != utterance->locale()) { continue; } if (!voice.gender.empty() && !utterance->gender().empty() && voice.gender != utterance->gender()) { continue; } return extension->id(); } } return std::string(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
std::string ExtensionTtsController::GetMatchingExtensionId( double rate = 1.0; if (options->HasKey(constants::kRateKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetDouble(constants::kRateKey, &rate)); if (rate < 0.1 || rate > 10.0) { error_ = constants::kErrorInvalidRate; return false; }
15,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int cypress_generic_port_probe(struct usb_serial_port *port) { struct usb_serial *serial = port->serial; struct cypress_private *priv; priv = kzalloc(sizeof(struct cypress_private), GFP_KERNEL); if (!priv) return -ENOMEM; priv->comm_is_ok = !0; spin_lock_init(&priv->lock); if (kfifo_alloc(&priv->write_fifo, CYPRESS_BUF_SIZE, GFP_KERNEL)) { kfree(priv); return -ENOMEM; } /* Skip reset for FRWD device. It is a workaound: device hangs if it receives SET_CONFIGURE in Configured state. */ if (!is_frwd(serial->dev)) usb_reset_configuration(serial->dev); priv->cmd_ctrl = 0; priv->line_control = 0; priv->termios_initialized = 0; priv->rx_flags = 0; /* Default packet format setting is determined by packet size. Anything with a size larger then 9 must have a separate count field since the 3 bit count field is otherwise too small. Otherwise we can use the slightly more compact format. This is in accordance with the cypress_m8 serial converter app note. */ if (port->interrupt_out_size > 9) priv->pkt_fmt = packet_format_1; else priv->pkt_fmt = packet_format_2; if (interval > 0) { priv->write_urb_interval = interval; priv->read_urb_interval = interval; dev_dbg(&port->dev, "%s - read & write intervals forced to %d\n", __func__, interval); } else { priv->write_urb_interval = port->interrupt_out_urb->interval; priv->read_urb_interval = port->interrupt_in_urb->interval; dev_dbg(&port->dev, "%s - intervals: read=%d write=%d\n", __func__, priv->read_urb_interval, priv->write_urb_interval); } usb_set_serial_port_data(port, priv); port->port.drain_delay = 256; return 0; } Commit Message: USB: cypress_m8: add endpoint sanity check An attack using missing endpoints exists. CVE-2016-3137 Signed-off-by: Oliver Neukum <ONeukum@suse.com> CC: stable@vger.kernel.org Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID:
static int cypress_generic_port_probe(struct usb_serial_port *port) { struct usb_serial *serial = port->serial; struct cypress_private *priv; if (!port->interrupt_out_urb || !port->interrupt_in_urb) { dev_err(&port->dev, "required endpoint is missing\n"); return -ENODEV; } priv = kzalloc(sizeof(struct cypress_private), GFP_KERNEL); if (!priv) return -ENOMEM; priv->comm_is_ok = !0; spin_lock_init(&priv->lock); if (kfifo_alloc(&priv->write_fifo, CYPRESS_BUF_SIZE, GFP_KERNEL)) { kfree(priv); return -ENOMEM; } /* Skip reset for FRWD device. It is a workaound: device hangs if it receives SET_CONFIGURE in Configured state. */ if (!is_frwd(serial->dev)) usb_reset_configuration(serial->dev); priv->cmd_ctrl = 0; priv->line_control = 0; priv->termios_initialized = 0; priv->rx_flags = 0; /* Default packet format setting is determined by packet size. Anything with a size larger then 9 must have a separate count field since the 3 bit count field is otherwise too small. Otherwise we can use the slightly more compact format. This is in accordance with the cypress_m8 serial converter app note. */ if (port->interrupt_out_size > 9) priv->pkt_fmt = packet_format_1; else priv->pkt_fmt = packet_format_2; if (interval > 0) { priv->write_urb_interval = interval; priv->read_urb_interval = interval; dev_dbg(&port->dev, "%s - read & write intervals forced to %d\n", __func__, interval); } else { priv->write_urb_interval = port->interrupt_out_urb->interval; priv->read_urb_interval = port->interrupt_in_urb->interval; dev_dbg(&port->dev, "%s - intervals: read=%d write=%d\n", __func__, priv->read_urb_interval, priv->write_urb_interval); } usb_set_serial_port_data(port, priv); port->port.drain_delay = 256; return 0; }
8,821
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "givcipher"); snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s", alg->cra_ablkcipher.geniv ?: "<built-in>"); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize; rblkcipher.ivsize = alg->cra_ablkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Commit Message: crypto: user - fix info leaks in report API Three errors resulting in kernel memory disclosure: 1/ The structures used for the netlink based crypto algorithm report API are located on the stack. As snprintf() does not fill the remainder of the buffer with null bytes, those stack bytes will be disclosed to users of the API. Switch to strncpy() to fix this. 2/ crypto_report_one() does not initialize all field of struct crypto_user_alg. Fix this to fix the heap info leak. 3/ For the module name we should copy only as many bytes as module_name() returns -- not as much as the destination buffer could hold. But the current code does not and therefore copies random data from behind the end of the module name, as the module name is always shorter than CRYPTO_MAX_ALG_NAME. Also switch to use strncpy() to copy the algorithm's name and driver_name. They are strings, after all. Signed-off-by: Mathias Krause <minipli@googlemail.com> Cc: Steffen Klassert <steffen.klassert@secunet.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> CWE ID: CWE-310
static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; strncpy(rblkcipher.type, "givcipher", sizeof(rblkcipher.type)); strncpy(rblkcipher.geniv, alg->cra_ablkcipher.geniv ?: "<built-in>", sizeof(rblkcipher.geniv)); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize; rblkcipher.ivsize = alg->cra_ablkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; }
7,691
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info) { assert(memory_info != (MemoryInfo *) NULL); assert(memory_info->signature == MagickSignature); if (memory_info->blob != (void *) NULL) switch (memory_info->type) { case AlignedVirtualMemory: { memory_info->blob=RelinquishAlignedMemory(memory_info->blob); RelinquishMagickResource(MemoryResource,memory_info->length); break; } case MapVirtualMemory: { (void) UnmapBlob(memory_info->blob,memory_info->length); memory_info->blob=NULL; RelinquishMagickResource(MapResource,memory_info->length); if (*memory_info->filename != '\0') (void) RelinquishUniqueFileResource(memory_info->filename); break; } case UnalignedVirtualMemory: default: { memory_info->blob=RelinquishMagickMemory(memory_info->blob); break; } } memory_info->signature=(~MagickSignature); memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info); return(memory_info); } Commit Message: CWE ID: CWE-189
MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info) { assert(memory_info != (MemoryInfo *) NULL); assert(memory_info->signature == MagickSignature); if (memory_info->blob != (void *) NULL) switch (memory_info->type) { case AlignedVirtualMemory: { memory_info->blob=RelinquishAlignedMemory(memory_info->blob); RelinquishMagickResource(MemoryResource,memory_info->length); break; } case MapVirtualMemory: { (void) UnmapBlob(memory_info->blob,memory_info->length); memory_info->blob=NULL; RelinquishMagickResource(MapResource,memory_info->length); if (*memory_info->filename != '\0') { (void) RelinquishUniqueFileResource(memory_info->filename); RelinquishMagickResource(DiskResource,memory_info->length); } break; } case UnalignedVirtualMemory: default: { memory_info->blob=RelinquishMagickMemory(memory_info->blob); break; } } memory_info->signature=(~MagickSignature); memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info); return(memory_info); }
3,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only.
Code: Plugin::Plugin(PP_Instance pp_instance) : pp::InstancePrivate(pp_instance), scriptable_plugin_(NULL), argc_(-1), argn_(NULL), argv_(NULL), main_subprocess_("main subprocess", NULL, NULL), nacl_ready_state_(UNSENT), nexe_error_reported_(false), wrapper_factory_(NULL), last_error_string_(""), ppapi_proxy_(NULL), enable_dev_interfaces_(false), init_time_(0), ready_time_(0), nexe_size_(0), time_of_last_progress_event_(0), using_ipc_proxy_(false) { PLUGIN_PRINTF(("Plugin::Plugin (this=%p, pp_instance=%" NACL_PRId32")\n", static_cast<void*>(this), pp_instance)); callback_factory_.Initialize(this); nexe_downloader_.Initialize(this); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 TBR=bbudge@chromium.org Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
Plugin::Plugin(PP_Instance pp_instance) : pp::InstancePrivate(pp_instance), scriptable_plugin_(NULL), argc_(-1), argn_(NULL), argv_(NULL), main_subprocess_("main subprocess", NULL, NULL), nacl_ready_state_(UNSENT), nexe_error_reported_(false), wrapper_factory_(NULL), last_error_string_(""), ppapi_proxy_(NULL), enable_dev_interfaces_(false), init_time_(0), ready_time_(0), nexe_size_(0), time_of_last_progress_event_(0) { PLUGIN_PRINTF(("Plugin::Plugin (this=%p, pp_instance=%" NACL_PRId32")\n", static_cast<void*>(this), pp_instance)); callback_factory_.Initialize(this); nexe_downloader_.Initialize(this); }
29,752