text
stringlengths
478
483k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: glue(cirrus_bitblt_rop_fwd_, ROP_NAME)(CirrusVGAState *s, uint8_t *dst,const uint8_t *src, int dstpitch,int srcpitch, int bltwidth,int bltheight) { int x,y; dstpitch -= bltwidth; srcpitch -= bltwidth; for (y = 0; y < bltheight; y++) { for (x = 0; x < bltwidth; x++) { ROP_OP(*dst, *src); dst++; src++; } dst += dstpitch; src += srcpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX "bitblt" heap overflow I have just noticed that patch for CVE-2007-1320 has never been applied to the QEMU CVS. Please find it below. | Multiple heap-based buffer overflows in the cirrus_invalidate_region | function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and | possibly other products, might allow local users to execute arbitrary | code via unspecified vectors related to "attempting to mark | non-existent regions as dirty," aka the "bitblt" heap overflow. git-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void cirrus_mem_writeb_mode4and5_8bpp(CirrusVGAState * s, unsigned mode, unsigned offset, uint32_t mem_value) { int x; unsigned val = mem_value; uint8_t *dst; dst = s->vram_ptr + offset; for (x = 0; x < 8; x++) { if (val & 0x80) { *dst = s->cirrus_shadow_gr1; } else if (mode == 5) { *dst = s->cirrus_shadow_gr0; } val <<= 1; dst++; } cpu_physical_memory_set_dirty(s->vram_offset + offset); cpu_physical_memory_set_dirty(s->vram_offset + offset + 7); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX "bitblt" heap overflow I have just noticed that patch for CVE-2007-1320 has never been applied to the QEMU CVS. Please find it below. | Multiple heap-based buffer overflows in the cirrus_invalidate_region | function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and | possibly other products, might allow local users to execute arbitrary | code via unspecified vectors related to "attempting to mark | non-existent regions as dirty," aka the "bitblt" heap overflow. git-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void cirrus_invalidate_region(CirrusVGAState * s, int off_begin, int off_pitch, int bytesperline, int lines) { int y; int off_cur; int off_cur_end; for (y = 0; y < lines; y++) { off_cur = off_begin; off_cur_end = off_cur + bytesperline; off_cur &= TARGET_PAGE_MASK; while (off_cur < off_cur_end) { cpu_physical_memory_set_dirty(s->vram_offset + off_cur); off_cur += TARGET_PAGE_SIZE; } off_begin += off_pitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX "bitblt" heap overflow I have just noticed that patch for CVE-2007-1320 has never been applied to the QEMU CVS. Please find it below. | Multiple heap-based buffer overflows in the cirrus_invalidate_region | function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and | possibly other products, might allow local users to execute arbitrary | code via unspecified vectors related to "attempting to mark | non-existent regions as dirty," aka the "bitblt" heap overflow. git-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop) { cirrus_fill_t rop_func; rop_func = cirrus_fill[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1]; rop_func(s, s->vram_ptr + s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_bitblt_reset(s); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX "bitblt" heap overflow I have just noticed that patch for CVE-2007-1320 has never been applied to the QEMU CVS. Please find it below. | Multiple heap-based buffer overflows in the cirrus_invalidate_region | function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and | possibly other products, might allow local users to execute arbitrary | code via unspecified vectors related to "attempting to mark | non-existent regions as dirty," aka the "bitblt" heap overflow. git-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void cirrus_mem_writeb_mode4and5_16bpp(CirrusVGAState * s, unsigned mode, unsigned offset, uint32_t mem_value) { int x; unsigned val = mem_value; uint8_t *dst; dst = s->vram_ptr + offset; for (x = 0; x < 8; x++) { if (val & 0x80) { *dst = s->cirrus_shadow_gr1; *(dst + 1) = s->gr[0x11]; } else if (mode == 5) { *dst = s->cirrus_shadow_gr0; *(dst + 1) = s->gr[0x10]; } val <<= 1; dst += 2; } cpu_physical_memory_set_dirty(s->vram_offset + offset); cpu_physical_memory_set_dirty(s->vram_offset + offset + 15); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX "bitblt" heap overflow I have just noticed that patch for CVE-2007-1320 has never been applied to the QEMU CVS. Please find it below. | Multiple heap-based buffer overflows in the cirrus_invalidate_region | function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and | possibly other products, might allow local users to execute arbitrary | code via unspecified vectors related to "attempting to mark | non-existent regions as dirty," aka the "bitblt" heap overflow. git-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static unsigned long convert_eip_to_linear(struct task_struct *child, struct pt_regs *regs) { unsigned long addr, seg; addr = regs->eip; seg = regs->xcs & 0xffff; if (regs->eflags & VM_MASK) { addr = (addr & 0xffff) + (seg << 4); return addr; } /* * We'll assume that the code segments in the GDT * are all zero-based. That is largely true: the * TLS segments are used for data, and the PNPBIOS * and APM bios ones we just ignore here. */ if (seg & LDT_SEGMENT) { u32 *desc; unsigned long base; down(&child->mm->context.sem); desc = child->mm->context.ldt + (seg & ~7); base = (desc[0] >> 16) | ((desc[1] & 0xff) << 16) | (desc[1] & 0xff000000); /* 16-bit code segment? */ if (!((desc[1] >> 22) & 1)) addr &= 0xffff; addr += base; up(&child->mm->context.sem); } return addr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Handle bogus %cs selector in single-step instruction decoding The code for LDT segment selectors was not robust in the face of a bogus selector set in %cs via ptrace before the single-step was done. Signed-off-by: Roland McGrath <roland@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int pwc_video_close(struct inode *inode, struct file *file) { struct video_device *vdev = file->private_data; struct pwc_device *pdev; int i; PWC_DEBUG_OPEN(">> video_close called(vdev = 0x%p).\n", vdev); pdev = (struct pwc_device *)vdev->priv; if (pdev->vopen == 0) PWC_DEBUG_MODULE("video_close() called on closed device?\n"); /* Dump statistics, but only if a reasonable amount of frames were processed (to prevent endless log-entries in case of snap-shot programs) */ if (pdev->vframe_count > 20) PWC_DEBUG_MODULE("Closing video device: %d frames received, dumped %d frames, %d frames with errors.\n", pdev->vframe_count, pdev->vframes_dumped, pdev->vframes_error); if (DEVICE_USE_CODEC1(pdev->type)) pwc_dec1_exit(); else pwc_dec23_exit(); pwc_isoc_cleanup(pdev); pwc_free_buffers(pdev); /* Turn off LEDS and power down camera, but only when not unplugged */ if (pdev->error_status != EPIPE) { /* Turn LEDs off */ if (pwc_set_leds(pdev, 0, 0) < 0) PWC_DEBUG_MODULE("Failed to set LED on/off time.\n"); if (power_save) { i = pwc_camera_power(pdev, 0); if (i < 0) PWC_ERROR("Failed to power down camera (%d)\n", i); } } pdev->vopen--; PWC_DEBUG_OPEN("<< video_close() vopen=%d\n", pdev->vopen); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'USB: fix DoS in pwc USB video driver the pwc driver has a disconnect method that waits for user space to close the device. This opens up an opportunity for a DoS attack, blocking the USB subsystem and making khubd's task busy wait in kernel space. This patch shifts freeing resources to close if an opened device is disconnected. Signed-off-by: Oliver Neukum <oneukum@suse.de> CC: stable <stable@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int hash_page(unsigned long ea, unsigned long access, unsigned long trap) { void *pgdir; unsigned long vsid; struct mm_struct *mm; pte_t *ptep; cpumask_t tmp; int rc, user_region = 0, local = 0; int psize; DBG_LOW("hash_page(ea=%016lx, access=%lx, trap=%lx\n", ea, access, trap); if ((ea & ~REGION_MASK) >= PGTABLE_RANGE) { DBG_LOW(" out of pgtable range !\n"); return 1; } /* Get region & vsid */ switch (REGION_ID(ea)) { case USER_REGION_ID: user_region = 1; mm = current->mm; if (! mm) { DBG_LOW(" user region with no mm !\n"); return 1; } vsid = get_vsid(mm->context.id, ea); psize = mm->context.user_psize; break; case VMALLOC_REGION_ID: mm = &init_mm; vsid = get_kernel_vsid(ea); if (ea < VMALLOC_END) psize = mmu_vmalloc_psize; else psize = mmu_io_psize; break; default: /* Not a valid range * Send the problem up to do_page_fault */ return 1; } DBG_LOW(" mm=%p, mm->pgdir=%p, vsid=%016lx\n", mm, mm->pgd, vsid); /* Get pgdir */ pgdir = mm->pgd; if (pgdir == NULL) return 1; /* Check CPU locality */ tmp = cpumask_of_cpu(smp_processor_id()); if (user_region && cpus_equal(mm->cpu_vm_mask, tmp)) local = 1; /* Handle hugepage regions */ if (unlikely(in_hugepage_area(mm->context, ea))) { DBG_LOW(" -> huge page !\n"); return hash_huge_page(mm, access, ea, vsid, local, trap); } /* Get PTE and page size from page tables */ ptep = find_linux_pte(pgdir, ea); if (ptep == NULL || !pte_present(*ptep)) { DBG_LOW(" no PTE !\n"); return 1; } #ifndef CONFIG_PPC_64K_PAGES DBG_LOW(" i-pte: %016lx\n", pte_val(*ptep)); #else DBG_LOW(" i-pte: %016lx %016lx\n", pte_val(*ptep), pte_val(*(ptep + PTRS_PER_PTE))); #endif /* Pre-check access permissions (will be re-checked atomically * in __hash_page_XX but this pre-check is a fast path */ if (access & ~pte_val(*ptep)) { DBG_LOW(" no access !\n"); return 1; } /* Do actual hashing */ #ifndef CONFIG_PPC_64K_PAGES rc = __hash_page_4K(ea, access, vsid, ptep, trap, local); #else if (mmu_ci_restrictions) { /* If this PTE is non-cacheable, switch to 4k */ if (psize == MMU_PAGE_64K && (pte_val(*ptep) & _PAGE_NO_CACHE)) { if (user_region) { psize = MMU_PAGE_4K; mm->context.user_psize = MMU_PAGE_4K; mm->context.sllp = SLB_VSID_USER | mmu_psize_defs[MMU_PAGE_4K].sllp; } else if (ea < VMALLOC_END) { /* * some driver did a non-cacheable mapping * in vmalloc space, so switch vmalloc * to 4k pages */ printk(KERN_ALERT "Reducing vmalloc segment " "to 4kB pages because of " "non-cacheable mapping\n"); psize = mmu_vmalloc_psize = MMU_PAGE_4K; } #ifdef CONFIG_SPE_BASE spu_flush_all_slbs(mm); #endif } if (user_region) { if (psize != get_paca()->context.user_psize) { get_paca()->context = mm->context; slb_flush_and_rebolt(); } } else if (get_paca()->vmalloc_sllp != mmu_psize_defs[mmu_vmalloc_psize].sllp) { get_paca()->vmalloc_sllp = mmu_psize_defs[mmu_vmalloc_psize].sllp; slb_flush_and_rebolt(); } } if (psize == MMU_PAGE_64K) rc = __hash_page_64K(ea, access, vsid, ptep, trap, local); else rc = __hash_page_4K(ea, access, vsid, ptep, trap, local); #endif /* CONFIG_PPC_64K_PAGES */ #ifndef CONFIG_PPC_64K_PAGES DBG_LOW(" o-pte: %016lx\n", pte_val(*ptep)); #else DBG_LOW(" o-pte: %016lx %016lx\n", pte_val(*ptep), pte_val(*(ptep + PTRS_PER_PTE))); #endif DBG_LOW(" -> rc=%d\n", rc); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[POWERPC] Allow drivers to map individual 4k pages to userspace Some drivers have resources that they want to be able to map into userspace that are 4k in size. On a kernel configured with 64k pages we currently end up mapping the 4k we want plus another 60k of physical address space, which could contain anything. This can introduce security problems, for example in the case of an infiniband adaptor where the other 60k could contain registers that some other program is using for its communications. This patch adds a new function, remap_4k_pfn, which drivers can use to map a single 4k page to userspace regardless of whether the kernel is using a 4k or a 64k page size. Like remap_pfn_range, it would typically be called in a driver's mmap function. It only maps a single 4k page, which on a 64k page kernel appears replicated 16 times throughout a 64k page. On a 4k page kernel it reduces to a call to remap_pfn_range. The way this works on a 64k kernel is that a new bit, _PAGE_4K_PFN, gets set on the linux PTE. This alters the way that __hash_page_4K computes the real address to put in the HPTE. The RPN field of the linux PTE becomes the 4k RPN directly rather than being interpreted as a 64k RPN. Since the RPN field is 32 bits, this means that physical addresses being mapped with remap_4k_pfn have to be below 2^44, i.e. 0x100000000000. The patch also factors out the code in arch/powerpc/mm/hash_utils_64.c that deals with demoting a process to use 4k pages into one function that gets called in the various different places where we need to do that. There were some discrepancies between exactly what was done in the various places, such as a call to spu_flush_all_slbs in one case but not in others. Signed-off-by: Paul Mackerras <paulus@samba.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: isdn_net_setcfg(isdn_net_ioctl_cfg * cfg) { isdn_net_dev *p = isdn_net_findif(cfg->name); ulong features; int i; int drvidx; int chidx; char drvid[25]; if (p) { isdn_net_local *lp = p->local; /* See if any registered driver supports the features we want */ features = ((1 << cfg->l2_proto) << ISDN_FEATURE_L2_SHIFT) | ((1 << cfg->l3_proto) << ISDN_FEATURE_L3_SHIFT); for (i = 0; i < ISDN_MAX_DRIVERS; i++) if (dev->drv[i]) if ((dev->drv[i]->interface->features & features) == features) break; if (i == ISDN_MAX_DRIVERS) { printk(KERN_WARNING "isdn_net: No driver with selected features\n"); return -ENODEV; } if (lp->p_encap != cfg->p_encap){ #ifdef CONFIG_ISDN_X25 struct concap_proto * cprot = p -> cprot; #endif if (isdn_net_device_started(p)) { printk(KERN_WARNING "%s: cannot change encap when if is up\n", p->dev->name); return -EBUSY; } #ifdef CONFIG_ISDN_X25 if( cprot && cprot -> pops ) cprot -> pops -> proto_del ( cprot ); p -> cprot = NULL; lp -> dops = NULL; /* ... , prepare for configuration of new one ... */ switch ( cfg -> p_encap ){ case ISDN_NET_ENCAP_X25IFACE: lp -> dops = &isdn_concap_reliable_dl_dops; } /* ... and allocate new one ... */ p -> cprot = isdn_concap_new( cfg -> p_encap ); /* p -> cprot == NULL now if p_encap is not supported by means of the concap_proto mechanism */ /* the protocol is not configured yet; this will happen later when isdn_net_reset() is called */ #endif } switch ( cfg->p_encap ) { case ISDN_NET_ENCAP_SYNCPPP: #ifndef CONFIG_ISDN_PPP printk(KERN_WARNING "%s: SyncPPP support not configured\n", p->dev->name); return -EINVAL; #else p->dev->type = ARPHRD_PPP; /* change ARP type */ p->dev->addr_len = 0; p->dev->do_ioctl = isdn_ppp_dev_ioctl; #endif break; case ISDN_NET_ENCAP_X25IFACE: #ifndef CONFIG_ISDN_X25 printk(KERN_WARNING "%s: isdn-x25 support not configured\n", p->dev->name); return -EINVAL; #else p->dev->type = ARPHRD_X25; /* change ARP type */ p->dev->addr_len = 0; #endif break; case ISDN_NET_ENCAP_CISCOHDLCK: p->dev->do_ioctl = isdn_ciscohdlck_dev_ioctl; break; default: if( cfg->p_encap >= 0 && cfg->p_encap <= ISDN_NET_ENCAP_MAX_ENCAP ) break; printk(KERN_WARNING "%s: encapsulation protocol %d not supported\n", p->dev->name, cfg->p_encap); return -EINVAL; } if (strlen(cfg->drvid)) { /* A bind has been requested ... */ char *c, *e; drvidx = -1; chidx = -1; strcpy(drvid, cfg->drvid); if ((c = strchr(drvid, ','))) { /* The channel-number is appended to the driver-Id with a comma */ chidx = (int) simple_strtoul(c + 1, &e, 10); if (e == c) chidx = -1; *c = '\0'; } for (i = 0; i < ISDN_MAX_DRIVERS; i++) /* Lookup driver-Id in array */ if (!(strcmp(dev->drvid[i], drvid))) { drvidx = i; break; } if ((drvidx == -1) || (chidx == -1)) /* Either driver-Id or channel-number invalid */ return -ENODEV; } else { /* Parameters are valid, so get them */ drvidx = lp->pre_device; chidx = lp->pre_channel; } if (cfg->exclusive > 0) { unsigned long flags; /* If binding is exclusive, try to grab the channel */ spin_lock_irqsave(&dev->lock, flags); if ((i = isdn_get_free_channel(ISDN_USAGE_NET, lp->l2_proto, lp->l3_proto, drvidx, chidx, lp->msn)) < 0) { /* Grab failed, because desired channel is in use */ lp->exclusive = -1; spin_unlock_irqrestore(&dev->lock, flags); return -EBUSY; } /* All went ok, so update isdninfo */ dev->usage[i] = ISDN_USAGE_EXCLUSIVE; isdn_info_update(); spin_unlock_irqrestore(&dev->lock, flags); lp->exclusive = i; } else { /* Non-exclusive binding or unbind. */ lp->exclusive = -1; if ((lp->pre_device != -1) && (cfg->exclusive == -1)) { isdn_unexclusive_channel(lp->pre_device, lp->pre_channel); isdn_free_channel(lp->pre_device, lp->pre_channel, ISDN_USAGE_NET); drvidx = -1; chidx = -1; } } strcpy(lp->msn, cfg->eaz); lp->pre_device = drvidx; lp->pre_channel = chidx; lp->onhtime = cfg->onhtime; lp->charge = cfg->charge; lp->l2_proto = cfg->l2_proto; lp->l3_proto = cfg->l3_proto; lp->cbdelay = cfg->cbdelay; lp->dialmax = cfg->dialmax; lp->triggercps = cfg->triggercps; lp->slavedelay = cfg->slavedelay * HZ; lp->pppbind = cfg->pppbind; lp->dialtimeout = cfg->dialtimeout >= 0 ? cfg->dialtimeout * HZ : -1; lp->dialwait = cfg->dialwait * HZ; if (cfg->secure) lp->flags |= ISDN_NET_SECURE; else lp->flags &= ~ISDN_NET_SECURE; if (cfg->cbhup) lp->flags |= ISDN_NET_CBHUP; else lp->flags &= ~ISDN_NET_CBHUP; switch (cfg->callback) { case 0: lp->flags &= ~(ISDN_NET_CALLBACK | ISDN_NET_CBOUT); break; case 1: lp->flags |= ISDN_NET_CALLBACK; lp->flags &= ~ISDN_NET_CBOUT; break; case 2: lp->flags |= ISDN_NET_CBOUT; lp->flags &= ~ISDN_NET_CALLBACK; break; } lp->flags &= ~ISDN_NET_DIALMODE_MASK; /* first all bits off */ if (cfg->dialmode && !(cfg->dialmode & ISDN_NET_DIALMODE_MASK)) { /* old isdnctrl version, where only 0 or 1 is given */ printk(KERN_WARNING "Old isdnctrl version detected! Please update.\n"); lp->flags |= ISDN_NET_DM_OFF; /* turn on `off' bit */ } else { lp->flags |= cfg->dialmode; /* turn on selected bits */ } if (cfg->chargehup) lp->hupflags |= ISDN_CHARGEHUP; else lp->hupflags &= ~ISDN_CHARGEHUP; if (cfg->ihup) lp->hupflags |= ISDN_INHUP; else lp->hupflags &= ~ISDN_INHUP; if (cfg->chargeint > 10) { lp->hupflags |= ISDN_CHARGEHUP | ISDN_HAVECHARGE | ISDN_MANCHARGE; lp->chargeint = cfg->chargeint * HZ; } if (cfg->p_encap != lp->p_encap) { if (cfg->p_encap == ISDN_NET_ENCAP_RAWIP) { p->dev->header_ops = NULL; p->dev->flags = IFF_NOARP|IFF_POINTOPOINT; } else { p->dev->header_ops = &isdn_header_ops; if (cfg->p_encap == ISDN_NET_ENCAP_ETHER) p->dev->flags = IFF_BROADCAST | IFF_MULTICAST; else p->dev->flags = IFF_NOARP|IFF_POINTOPOINT; } } lp->p_encap = cfg->p_encap; return 0; } return -ENODEV; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings Addresses http://bugzilla.kernel.org/show_bug.cgi?id=9416 Signed-off-by: Karsten Keil <kkeil@suse.de> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: isdn_net_find_icall(int di, int ch, int idx, setup_parm *setup) { char *eaz; int si1; int si2; int ematch; int wret; int swapped; int sidx = 0; u_long flags; isdn_net_dev *p; isdn_net_phone *n; char nr[32]; char *my_eaz; /* Search name in netdev-chain */ if (!setup->phone[0]) { nr[0] = '0'; nr[1] = '\0'; printk(KERN_INFO "isdn_net: Incoming call without OAD, assuming '0'\n"); } else strcpy(nr, setup->phone); si1 = (int) setup->si1; si2 = (int) setup->si2; if (!setup->eazmsn[0]) { printk(KERN_WARNING "isdn_net: Incoming call without CPN, assuming '0'\n"); eaz = "0"; } else eaz = setup->eazmsn; if (dev->net_verbose > 1) printk(KERN_INFO "isdn_net: call from %s,%d,%d -> %s\n", nr, si1, si2, eaz); /* Accept DATA and VOICE calls at this stage * local eaz is checked later for allowed call types */ if ((si1 != 7) && (si1 != 1)) { if (dev->net_verbose > 1) printk(KERN_INFO "isdn_net: Service-Indicator not 1 or 7, ignored\n"); return 0; } n = (isdn_net_phone *) 0; p = dev->netdev; ematch = wret = swapped = 0; #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: di=%d ch=%d idx=%d usg=%d\n", di, ch, idx, dev->usage[idx]); #endif while (p) { int matchret; isdn_net_local *lp = p->local; /* If last check has triggered as binding-swap, revert it */ switch (swapped) { case 2: isdn_net_swap_usage(idx, sidx); /* fall through */ case 1: isdn_net_swapbind(di); break; } swapped = 0; /* check acceptable call types for DOV */ my_eaz = isdn_map_eaz2msn(lp->msn, di); if (si1 == 1) { /* it's a DOV call, check if we allow it */ if (*my_eaz == 'v' || *my_eaz == 'V' || *my_eaz == 'b' || *my_eaz == 'B') my_eaz++; /* skip to allow a match */ else my_eaz = NULL; /* force non match */ } else { /* it's a DATA call, check if we allow it */ if (*my_eaz == 'b' || *my_eaz == 'B') my_eaz++; /* skip to allow a match */ } if (my_eaz) matchret = isdn_msncmp(eaz, my_eaz); else matchret = 1; if (!matchret) ematch = 1; /* Remember if more numbers eventually can match */ if (matchret > wret) wret = matchret; #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: if='%s', l.msn=%s, l.flags=%d, l.dstate=%d\n", p->dev->name, lp->msn, lp->flags, lp->dialstate); #endif if ((!matchret) && /* EAZ is matching */ (((!(lp->flags & ISDN_NET_CONNECTED)) && /* but not connected */ (USG_NONE(dev->usage[idx]))) || /* and ch. unused or */ ((((lp->dialstate == 4) || (lp->dialstate == 12)) && /* if dialing */ (!(lp->flags & ISDN_NET_CALLBACK))) /* but no callback */ ))) { #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: match1, pdev=%d pch=%d\n", lp->pre_device, lp->pre_channel); #endif if (dev->usage[idx] & ISDN_USAGE_EXCLUSIVE) { if ((lp->pre_channel != ch) || (lp->pre_device != di)) { /* Here we got a problem: * If using an ICN-Card, an incoming call is always signaled on * on the first channel of the card, if both channels are * down. However this channel may be bound exclusive. If the * second channel is free, this call should be accepted. * The solution is horribly but it runs, so what: * We exchange the exclusive bindings of the two channels, the * corresponding variables in the interface-structs. */ if (ch == 0) { sidx = isdn_dc2minor(di, 1); #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: ch is 0\n"); #endif if (USG_NONE(dev->usage[sidx])) { /* Second Channel is free, now see if it is bound * exclusive too. */ if (dev->usage[sidx] & ISDN_USAGE_EXCLUSIVE) { #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: 2nd channel is down and bound\n"); #endif /* Yes, swap bindings only, if the original * binding is bound to channel 1 of this driver */ if ((lp->pre_device == di) && (lp->pre_channel == 1)) { isdn_net_swapbind(di); swapped = 1; } else { /* ... else iterate next device */ p = (isdn_net_dev *) p->next; continue; } } else { #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: 2nd channel is down and unbound\n"); #endif /* No, swap always and swap excl-usage also */ isdn_net_swap_usage(idx, sidx); isdn_net_swapbind(di); swapped = 2; } /* Now check for exclusive binding again */ #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: final check\n"); #endif if ((dev->usage[idx] & ISDN_USAGE_EXCLUSIVE) && ((lp->pre_channel != ch) || (lp->pre_device != di))) { #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: final check failed\n"); #endif p = (isdn_net_dev *) p->next; continue; } } } else { /* We are already on the second channel, so nothing to do */ #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: already on 2nd channel\n"); #endif } } } #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: match2\n"); #endif n = lp->phone[0]; if (lp->flags & ISDN_NET_SECURE) { while (n) { if (!isdn_msncmp(nr, n->num)) break; n = (isdn_net_phone *) n->next; } } if (n || (!(lp->flags & ISDN_NET_SECURE))) { #ifdef ISDN_DEBUG_NET_ICALL printk(KERN_DEBUG "n_fi: match3\n"); #endif /* matching interface found */ /* * Is the state STOPPED? * If so, no dialin is allowed, * so reject actively. * */ if (ISDN_NET_DIALMODE(*lp) == ISDN_NET_DM_OFF) { printk(KERN_INFO "incoming call, interface %s `stopped' -> rejected\n", p->dev->name); return 3; } /* * Is the interface up? * If not, reject the call actively. */ if (!isdn_net_device_started(p)) { printk(KERN_INFO "%s: incoming call, interface down -> rejected\n", p->dev->name); return 3; } /* Interface is up, now see if it's a slave. If so, see if * it's master and parent slave is online. If not, reject the call. */ if (lp->master) { isdn_net_local *mlp = (isdn_net_local *) lp->master->priv; printk(KERN_DEBUG "ICALLslv: %s\n", p->dev->name); printk(KERN_DEBUG "master=%s\n", lp->master->name); if (mlp->flags & ISDN_NET_CONNECTED) { printk(KERN_DEBUG "master online\n"); /* Master is online, find parent-slave (master if first slave) */ while (mlp->slave) { if ((isdn_net_local *) mlp->slave->priv == lp) break; mlp = (isdn_net_local *) mlp->slave->priv; } } else printk(KERN_DEBUG "master offline\n"); /* Found parent, if it's offline iterate next device */ printk(KERN_DEBUG "mlpf: %d\n", mlp->flags & ISDN_NET_CONNECTED); if (!(mlp->flags & ISDN_NET_CONNECTED)) { p = (isdn_net_dev *) p->next; continue; } } if (lp->flags & ISDN_NET_CALLBACK) { int chi; /* * Is the state MANUAL? * If so, no callback can be made, * so reject actively. * */ if (ISDN_NET_DIALMODE(*lp) == ISDN_NET_DM_OFF) { printk(KERN_INFO "incoming call for callback, interface %s `off' -> rejected\n", p->dev->name); return 3; } printk(KERN_DEBUG "%s: call from %s -> %s, start callback\n", p->dev->name, nr, eaz); if (lp->phone[1]) { /* Grab a free ISDN-Channel */ spin_lock_irqsave(&dev->lock, flags); if ((chi = isdn_get_free_channel( ISDN_USAGE_NET, lp->l2_proto, lp->l3_proto, lp->pre_device, lp->pre_channel, lp->msn) ) < 0) { printk(KERN_WARNING "isdn_net_find_icall: No channel for %s\n", p->dev->name); spin_unlock_irqrestore(&dev->lock, flags); return 0; } /* Setup dialstate. */ lp->dtimer = 0; lp->dialstate = 11; /* Connect interface with channel */ isdn_net_bind_channel(lp, chi); #ifdef CONFIG_ISDN_PPP if (lp->p_encap == ISDN_NET_ENCAP_SYNCPPP) if (isdn_ppp_bind(lp) < 0) { spin_unlock_irqrestore(&dev->lock, flags); isdn_net_unbind_channel(lp); return 0; } #endif spin_unlock_irqrestore(&dev->lock, flags); /* Initiate dialing by returning 2 or 4 */ return (lp->flags & ISDN_NET_CBHUP) ? 2 : 4; } else printk(KERN_WARNING "isdn_net: %s: No phone number\n", p->dev->name); return 0; } else { printk(KERN_DEBUG "%s: call from %s -> %s accepted\n", p->dev->name, nr, eaz); /* if this interface is dialing, it does it probably on a different device, so free this device */ if ((lp->dialstate == 4) || (lp->dialstate == 12)) { #ifdef CONFIG_ISDN_PPP if (lp->p_encap == ISDN_NET_ENCAP_SYNCPPP) isdn_ppp_free(lp); #endif isdn_net_lp_disconnected(lp); isdn_free_channel(lp->isdn_device, lp->isdn_channel, ISDN_USAGE_NET); } spin_lock_irqsave(&dev->lock, flags); dev->usage[idx] &= ISDN_USAGE_EXCLUSIVE; dev->usage[idx] |= ISDN_USAGE_NET; strcpy(dev->num[idx], nr); isdn_info_update(); dev->st_netdev[idx] = lp->netdev; lp->isdn_device = di; lp->isdn_channel = ch; lp->ppp_slot = -1; lp->flags |= ISDN_NET_CONNECTED; lp->dialstate = 7; lp->dtimer = 0; lp->outgoing = 0; lp->huptimer = 0; lp->hupflags |= ISDN_WAITCHARGE; lp->hupflags &= ~ISDN_HAVECHARGE; #ifdef CONFIG_ISDN_PPP if (lp->p_encap == ISDN_NET_ENCAP_SYNCPPP) { if (isdn_ppp_bind(lp) < 0) { isdn_net_unbind_channel(lp); spin_unlock_irqrestore(&dev->lock, flags); return 0; } } #endif spin_unlock_irqrestore(&dev->lock, flags); return 1; } } } p = (isdn_net_dev *) p->next; } /* If none of configured EAZ/MSN matched and not verbose, be silent */ if (!ematch || dev->net_verbose) printk(KERN_INFO "isdn_net: call from %s -> %d %s ignored\n", nr, di, eaz); return (wret == 2)?5:0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'isdn: avoid copying overly-long strings Addresses http://bugzilla.kernel.org/show_bug.cgi?id=9416 Signed-off-by: Karsten Keil <kkeil@suse.de> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int esp_input(struct xfrm_state *x, struct sk_buff *skb) { struct ip_esp_hdr *esph; struct esp_data *esp = x->data; struct crypto_aead *aead = esp->aead; struct aead_request *req; struct sk_buff *trailer; int elen = skb->len - sizeof(*esph) - crypto_aead_ivsize(aead); int nfrags; void *tmp; u8 *iv; struct scatterlist *sg; struct scatterlist *asg; int err = -EINVAL; if (!pskb_may_pull(skb, sizeof(*esph))) goto out; if (elen <= 0) goto out; if ((err = skb_cow_data(skb, 0, &trailer)) < 0) goto out; nfrags = err; err = -ENOMEM; tmp = esp_alloc_tmp(aead, nfrags + 1); if (!tmp) goto out; ESP_SKB_CB(skb)->tmp = tmp; iv = esp_tmp_iv(aead, tmp); req = esp_tmp_req(aead, iv); asg = esp_req_sg(aead, req); sg = asg + 1; skb->ip_summed = CHECKSUM_NONE; esph = (struct ip_esp_hdr *)skb->data; /* Get ivec. This can be wrong, check against another impls. */ iv = esph->enc_data; sg_init_table(sg, nfrags); skb_to_sgvec(skb, sg, sizeof(*esph) + crypto_aead_ivsize(aead), elen); sg_init_one(asg, esph, sizeof(*esph)); aead_request_set_callback(req, 0, esp_input_done, skb); aead_request_set_crypt(req, sg, sg, elen, iv); aead_request_set_assoc(req, asg, sizeof(*esph)); err = crypto_aead_decrypt(req); if (err == -EINPROGRESS) goto out; err = esp_input_done2(skb, err); out: return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-16'], 'message': '[ESP]: Ensure IV is in linear part of the skb to avoid BUG() due to OOB access ESP does not account for the IV size when calling pskb_may_pull() to ensure everything it accesses directly is within the linear part of a potential fragment. This results in a BUG() being triggered when the both the IPv4 and IPv6 ESP stack is fed with an skb where the first fragment ends between the end of the esp header and the end of the IV. This bug was found by Dirk Nehring <dnehring@gmx.net> . Signed-off-by: Thomas Graf <tgraf@suug.ch> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: shmem_alloc_page(gfp_t gfp,struct shmem_inode_info *info, unsigned long idx) { return alloc_page(gfp | __GFP_ZERO); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage tmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in which shmem_getpage receives the page from its caller instead of allocating. We must cover this case by clear_highpage before SetPageUptodate, as before. Signed-off-by: Hugh Dickins <hugh@veritas.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: shmem_alloc_page(gfp_t gfp, struct shmem_inode_info *info, unsigned long idx) { struct vm_area_struct pvma; struct page *page; memset(&pvma, 0, sizeof(struct vm_area_struct)); pvma.vm_policy = mpol_shared_policy_lookup(&info->policy, idx); pvma.vm_pgoff = idx; pvma.vm_end = PAGE_SIZE; page = alloc_page_vma(gfp | __GFP_ZERO, &pvma, 0); mpol_free(pvma.vm_policy); return page; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'tmpfs: restore missing clear_highpage tmpfs was misconverted to __GFP_ZERO in 2.6.11. There's an unusual case in which shmem_getpage receives the page from its caller instead of allocating. We must cover this case by clear_highpage before SetPageUptodate, as before. Signed-off-by: Hugh Dickins <hugh@veritas.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ProcPanoramiXShmCreatePixmap( register ClientPtr client) { ScreenPtr pScreen = NULL; PixmapPtr pMap = NULL; DrawablePtr pDraw; DepthPtr pDepth; int i, j, result, rc; ShmDescPtr shmdesc; REQUEST(xShmCreatePixmapReq); unsigned int width, height, depth; unsigned long size; PanoramiXRes *newPix; REQUEST_SIZE_MATCH(xShmCreatePixmapReq); client->errorValue = stuff->pid; if (!sharedPixmaps) return BadImplementation; LEGAL_NEW_RESOURCE(stuff->pid, client); rc = dixLookupDrawable(&pDraw, stuff->drawable, client, M_ANY, DixUnknownAccess); if (rc != Success) return rc; VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client); width = stuff->width; height = stuff->height; depth = stuff->depth; if (!width || !height || !depth) { client->errorValue = 0; return BadValue; } if (width > 32767 || height > 32767) return BadAlloc; if (stuff->depth != 1) { pDepth = pDraw->pScreen->allowedDepths; for (i=0; i<pDraw->pScreen->numDepths; i++, pDepth++) if (pDepth->depth == stuff->depth) goto CreatePmap; client->errorValue = stuff->depth; return BadValue; } CreatePmap: size = PixmapBytePad(width, depth) * height; if (sizeof(size) == 4 && BitsPerPixel(depth) > 8) { if (size < width * height) return BadAlloc; /* thankfully, offset is unsigned */ if (stuff->offset + size < size) return BadAlloc; } VERIFY_SHMSIZE(shmdesc, stuff->offset, size, client); if(!(newPix = (PanoramiXRes *) xalloc(sizeof(PanoramiXRes)))) return BadAlloc; newPix->type = XRT_PIXMAP; newPix->u.pix.shared = TRUE; newPix->info[0].id = stuff->pid; for(j = 1; j < PanoramiXNumScreens; j++) newPix->info[j].id = FakeClientID(client->index); result = (client->noClientException); FOR_NSCREENS(j) { pScreen = screenInfo.screens[j]; pMap = (*shmFuncs[j]->CreatePixmap)(pScreen, stuff->width, stuff->height, stuff->depth, shmdesc->addr + stuff->offset); if (pMap) { dixSetPrivate(&pMap->devPrivates, shmPixmapPrivate, shmdesc); shmdesc->refcnt++; pMap->drawable.serialNumber = NEXT_SERIAL_NUMBER; pMap->drawable.id = newPix->info[j].id; if (!AddResource(newPix->info[j].id, RT_PIXMAP, (pointer)pMap)) { (*pScreen->DestroyPixmap)(pMap); result = BadAlloc; break; } } else { result = BadAlloc; break; } } if(result == BadAlloc) { while(j--) { (*pScreen->DestroyPixmap)(pMap); FreeResource(newPix->info[j].id, RT_NONE); } xfree(newPix); } else AddResource(stuff->pid, XRT_PIXMAP, newPix); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'CVE-2007-6429: Always test for size+offset wrapping.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static long vmsplice_to_user(struct file *file, const struct iovec __user *iov, unsigned long nr_segs, unsigned int flags) { struct pipe_inode_info *pipe; struct splice_desc sd; ssize_t size; int error; long ret; pipe = pipe_info(file->f_path.dentry->d_inode); if (!pipe) return -EBADF; if (pipe->inode) mutex_lock(&pipe->inode->i_mutex); error = ret = 0; while (nr_segs) { void __user *base; size_t len; /* * Get user address base and length for this iovec. */ error = get_user(base, &iov->iov_base); if (unlikely(error)) break; error = get_user(len, &iov->iov_len); if (unlikely(error)) break; /* * Sanity check this iovec. 0 read succeeds. */ if (unlikely(!len)) break; if (unlikely(!base)) { error = -EFAULT; break; } sd.len = 0; sd.total_len = len; sd.flags = flags; sd.u.userptr = base; sd.pos = 0; size = __splice_from_pipe(pipe, &sd, pipe_to_user); if (size < 0) { if (!ret) ret = size; break; } ret += size; if (size < len) break; nr_segs--; iov++; } if (pipe->inode) mutex_unlock(&pipe->inode->i_mutex); if (!ret) ret = error; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'splice: missing user pointer access verification vmsplice_to_user() must always check the user pointer and length with access_ok() before copying. Likewise, for the slow path of copy_from_user_mmap_sem() we need to check that we may read from the user region. Signed-off-by: Jens Axboe <jens.axboe@oracle.com> Cc: Wojciech Purczynski <cliph@research.coseinc.com> Signed-off-by: Greg Kroah-Hartman <gregkh@suse.de> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: asmlinkage long sys_setrlimit(unsigned int resource, struct rlimit __user *rlim) { struct rlimit new_rlim, *old_rlim; unsigned long it_prof_secs; int retval; if (resource >= RLIM_NLIMITS) return -EINVAL; if (copy_from_user(&new_rlim, rlim, sizeof(*rlim))) return -EFAULT; if (new_rlim.rlim_cur > new_rlim.rlim_max) return -EINVAL; old_rlim = current->signal->rlim + resource; if ((new_rlim.rlim_max > old_rlim->rlim_max) && !capable(CAP_SYS_RESOURCE)) return -EPERM; if (resource == RLIMIT_NOFILE && new_rlim.rlim_max > NR_OPEN) return -EPERM; retval = security_task_setrlimit(resource, &new_rlim); if (retval) return retval; task_lock(current->group_leader); *old_rlim = new_rlim; task_unlock(current->group_leader); if (resource != RLIMIT_CPU) goto out; /* * RLIMIT_CPU handling. Note that the kernel fails to return an error * code if it rejected the user's attempt to set RLIMIT_CPU. This is a * very long-standing error, and fixing it now risks breakage of * applications, so we live with it */ if (new_rlim.rlim_cur == RLIM_INFINITY) goto out; it_prof_secs = cputime_to_secs(current->signal->it_prof_expires); if (it_prof_secs == 0 || new_rlim.rlim_cur <= it_prof_secs) { unsigned long rlim_cur = new_rlim.rlim_cur; cputime_t cputime; if (rlim_cur == 0) { /* * The caller is asking for an immediate RLIMIT_CPU * expiry. But we use the zero value to mean "it was * never set". So let's cheat and make it one second * instead */ rlim_cur = 1; } cputime = secs_to_cputime(rlim_cur); read_lock(&tasklist_lock); spin_lock_irq(&current->sighand->siglock); set_process_cpu_timer(current, CPUCLOCK_PROF, &cputime, NULL); spin_unlock_irq(&current->sighand->siglock); read_unlock(&tasklist_lock); } out: return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'CPU time limit patch / setrlimit(RLIMIT_CPU, 0) cheat fix As discovered here today, the change in Kernel 2.6.17 intended to inhibit users from setting RLIMIT_CPU to 0 (as that is equivalent to unlimited) by "cheating" and setting it to 1 in such a case, does not make a difference, as the check is done in the wrong place (too late), and only applies to the profiling code. On all systems I checked running kernels above 2.6.17, no matter what the hard and soft CPU time limits were before, a user could escape them by issuing in the shell (sh/bash/zsh) "ulimit -t 0", and then the user's process was not ever killed. Attached is a trivial patch to fix that. Simply moving the check to a slightly earlier location (specifically, before the line that actually assigns the limit - *old_rlim = new_rlim), does the trick. Do note that at least the zsh (but not ash, dash, or bash) shell has the problem of "caching" the limits set by the ulimit command, so when running zsh the fix will not immediately be evident - after entering "ulimit -t 0", "ulimit -a" will show "-t: cpu time (seconds) 0", even though the actual limit as returned by getrlimit(...) will be 1. It can be verified by opening a subshell (which will not have the values of the parent shell in cache) and checking in it, or just by running a CPU intensive command like "echo '65536^1048576' | bc" and verifying that it dumps core after one second. Regardless of whether that is a misfeature in the shell, perhaps it would be better to return -EINVAL from setrlimit in such a case instead of cheating and setting to 1, as that does not really reflect the actual state of the process anymore. I do not however know what the ground for that decision was in the original 2.6.17 change, and whether there would be any "backward" compatibility issues, so I preferred not to touch that right now. Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ia32_setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info, compat_sigset_t *set, struct pt_regs *regs) { struct rt_sigframe __user *frame; struct exec_domain *ed = current_thread_info()->exec_domain; void __user *restorer; int err = 0; /* __copy_to_user optimizes that into a single 8 byte store */ static const struct { u8 movl; u32 val; u16 int80; u16 pad; u8 pad2; } __attribute__((packed)) code = { 0xb8, __NR_ia32_rt_sigreturn, 0x80cd, 0, }; frame = get_sigframe(ka, regs, sizeof(*frame)); if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame))) goto give_sigsegv; err |= __put_user((ed && ed->signal_invmap && sig < 32 ? ed->signal_invmap[sig] : sig), &frame->sig); err |= __put_user(ptr_to_compat(&frame->info), &frame->pinfo); err |= __put_user(ptr_to_compat(&frame->uc), &frame->puc); err |= copy_siginfo_to_user32(&frame->info, info); if (err) goto give_sigsegv; /* Create the ucontext. */ err |= __put_user(0, &frame->uc.uc_flags); err |= __put_user(0, &frame->uc.uc_link); err |= __put_user(current->sas_ss_sp, &frame->uc.uc_stack.ss_sp); err |= __put_user(sas_ss_flags(regs->sp), &frame->uc.uc_stack.ss_flags); err |= __put_user(current->sas_ss_size, &frame->uc.uc_stack.ss_size); err |= ia32_setup_sigcontext(&frame->uc.uc_mcontext, &frame->fpstate, regs, set->sig[0]); err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set)); if (err) goto give_sigsegv; if (ka->sa.sa_flags & SA_RESTORER) restorer = ka->sa.sa_restorer; else restorer = VDSO32_SYMBOL(current->mm->context.vdso, rt_sigreturn); err |= __put_user(ptr_to_compat(restorer), &frame->pretcode); /* * Not actually used anymore, but left because some gdb * versions need it. */ err |= __copy_to_user(frame->retcode, &code, 8); if (err) goto give_sigsegv; /* Set up registers for signal handler */ regs->sp = (unsigned long) frame; regs->ip = (unsigned long) ka->sa.sa_handler; /* Make -mregparm=3 work */ regs->ax = sig; regs->dx = (unsigned long) &frame->info; regs->cx = (unsigned long) &frame->uc; /* Make -mregparm=3 work */ regs->ax = sig; regs->dx = (unsigned long) &frame->info; regs->cx = (unsigned long) &frame->uc; asm volatile("movl %0,%%ds" :: "r" (__USER32_DS)); asm volatile("movl %0,%%es" :: "r" (__USER32_DS)); regs->cs = __USER32_CS; regs->ss = __USER32_DS; set_fs(USER_DS); regs->flags &= ~X86_EFLAGS_TF; if (test_thread_flag(TIF_SINGLESTEP)) ptrace_notify(SIGTRAP); #if DEBUG_SIG printk(KERN_DEBUG "SIG deliver (%s:%d): sp=%p pc=%lx ra=%u\n", current->comm, current->pid, frame, regs->ip, frame->pretcode); #endif return 0; give_sigsegv: force_sigsegv(sig, current); return -EFAULT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'x86: clear DF before calling signal handler The Linux kernel currently does not clear the direction flag before calling a signal handler, whereas the x86/x86-64 ABI requires that. Linux had this behavior/bug forever, but this becomes a real problem with gcc version 4.3, which assumes that the direction flag is correctly cleared at the entry of a function. This patches changes the setup_frame() functions to clear the direction before entering the signal handler. Signed-off-by: Aurelien Jarno <aurelien@aurel32.net> Signed-off-by: Ingo Molnar <mingo@elte.hu> Acked-by: H. Peter Anvin <hpa@zytor.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int setup_frame(int sig, struct k_sigaction *ka, sigset_t *set, struct pt_regs * regs) { void __user *restorer; struct sigframe __user *frame; int err = 0; int usig; frame = get_sigframe(ka, regs, sizeof(*frame)); if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame))) goto give_sigsegv; usig = current_thread_info()->exec_domain && current_thread_info()->exec_domain->signal_invmap && sig < 32 ? current_thread_info()->exec_domain->signal_invmap[sig] : sig; err = __put_user(usig, &frame->sig); if (err) goto give_sigsegv; err = setup_sigcontext(&frame->sc, &frame->fpstate, regs, set->sig[0]); if (err) goto give_sigsegv; if (_NSIG_WORDS > 1) { err = __copy_to_user(&frame->extramask, &set->sig[1], sizeof(frame->extramask)); if (err) goto give_sigsegv; } if (current->binfmt->hasvdso) restorer = VDSO32_SYMBOL(current->mm->context.vdso, sigreturn); else restorer = &frame->retcode; if (ka->sa.sa_flags & SA_RESTORER) restorer = ka->sa.sa_restorer; /* Set up to return from userspace. */ err |= __put_user(restorer, &frame->pretcode); /* * This is popl %eax ; movl $,%eax ; int $0x80 * * WE DO NOT USE IT ANY MORE! It's only left here for historical * reasons and because gdb uses it as a signature to notice * signal handler stack frames. */ err |= __put_user(0xb858, (short __user *)(frame->retcode+0)); err |= __put_user(__NR_sigreturn, (int __user *)(frame->retcode+2)); err |= __put_user(0x80cd, (short __user *)(frame->retcode+6)); if (err) goto give_sigsegv; /* Set up registers for signal handler */ regs->sp = (unsigned long) frame; regs->ip = (unsigned long) ka->sa.sa_handler; regs->ax = (unsigned long) sig; regs->dx = (unsigned long) 0; regs->cx = (unsigned long) 0; regs->ds = __USER_DS; regs->es = __USER_DS; regs->ss = __USER_DS; regs->cs = __USER_CS; /* * Clear TF when entering the signal handler, but * notify any tracer that was single-stepping it. * The tracer may want to single-step inside the * handler too. */ regs->flags &= ~TF_MASK; if (test_thread_flag(TIF_SINGLESTEP)) ptrace_notify(SIGTRAP); #if DEBUG_SIG printk("SIG deliver (%s:%d): sp=%p pc=%p ra=%p\n", current->comm, current->pid, frame, regs->ip, frame->pretcode); #endif return 0; give_sigsegv: force_sigsegv(sig, current); return -EFAULT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'x86: clear DF before calling signal handler The Linux kernel currently does not clear the direction flag before calling a signal handler, whereas the x86/x86-64 ABI requires that. Linux had this behavior/bug forever, but this becomes a real problem with gcc version 4.3, which assumes that the direction flag is correctly cleared at the entry of a function. This patches changes the setup_frame() functions to clear the direction before entering the signal handler. Signed-off-by: Aurelien Jarno <aurelien@aurel32.net> Signed-off-by: Ingo Molnar <mingo@elte.hu> Acked-by: H. Peter Anvin <hpa@zytor.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static unsigned long __peek_user(struct task_struct *child, addr_t addr) { struct user *dummy = NULL; addr_t offset, tmp; if (addr < (addr_t) &dummy->regs.acrs) { /* * psw and gprs are stored on the stack */ tmp = *(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr); if (addr == (addr_t) &dummy->regs.psw.mask) /* Remove per bit from user psw. */ tmp &= ~PSW_MASK_PER; } else if (addr < (addr_t) &dummy->regs.orig_gpr2) { /* * access registers are stored in the thread structure */ offset = addr - (addr_t) &dummy->regs.acrs; #ifdef CONFIG_64BIT /* * Very special case: old & broken 64 bit gdb reading * from acrs[15]. Result is a 64 bit value. Read the * 32 bit acrs[15] value and shift it by 32. Sick... */ if (addr == (addr_t) &dummy->regs.acrs[15]) tmp = ((unsigned long) child->thread.acrs[15]) << 32; else #endif tmp = *(addr_t *)((addr_t) &child->thread.acrs + offset); } else if (addr == (addr_t) &dummy->regs.orig_gpr2) { /* * orig_gpr2 is stored on the kernel stack */ tmp = (addr_t) task_pt_regs(child)->orig_gpr2; } else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) { /* * floating point regs. are stored in the thread structure */ offset = addr - (addr_t) &dummy->regs.fp_regs; tmp = *(addr_t *)((addr_t) &child->thread.fp_regs + offset); if (addr == (addr_t) &dummy->regs.fp_regs.fpc) tmp &= (unsigned long) FPC_VALID_MASK << (BITS_PER_LONG - 32); } else if (addr < (addr_t) (&dummy->regs.per_info + 1)) { /* * per_info is found in the thread structure */ offset = addr - (addr_t) &dummy->regs.per_info; tmp = *(addr_t *)((addr_t) &child->thread.per_info + offset); } else tmp = 0; return tmp; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': '[S390] CVE-2008-1514: prevent ptrace padding area read/write in 31-bit mode When running a 31-bit ptrace, on either an s390 or s390x kernel, reads and writes into a padding area in struct user_regs_struct32 will result in a kernel panic. This is also known as CVE-2008-1514. Test case available here: http://sources.redhat.com/cgi-bin/cvsweb.cgi/~checkout~/tests/ptrace-tests/tests/user-area-padding.c?cvsroot=systemtap Steps to reproduce: 1) wget the above 2) gcc -o user-area-padding-31bit user-area-padding.c -Wall -ggdb2 -D_GNU_SOURCE -m31 3) ./user-area-padding-31bit <panic> Test status ----------- Without patch, both s390 and s390x kernels panic. With patch, the test case, as well as the gdb testsuite, pass without incident, padding area reads returning zero, writes ignored. Nb: original version returned -EINVAL on write attempts, which broke the gdb test and made the test case slightly unhappy, Jan Kratochvil suggested the change to return 0 on write attempts. Signed-off-by: Jarod Wilson <jarod@redhat.com> Tested-by: Jan Kratochvil <jan.kratochvil@redhat.com> Signed-off-by: Martin Schwidefsky <schwidefsky@de.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int __poke_user(struct task_struct *child, addr_t addr, addr_t data) { struct user *dummy = NULL; addr_t offset; if (addr < (addr_t) &dummy->regs.acrs) { /* * psw and gprs are stored on the stack */ if (addr == (addr_t) &dummy->regs.psw.mask && #ifdef CONFIG_COMPAT data != PSW_MASK_MERGE(psw_user32_bits, data) && #endif data != PSW_MASK_MERGE(psw_user_bits, data)) /* Invalid psw mask. */ return -EINVAL; #ifndef CONFIG_64BIT if (addr == (addr_t) &dummy->regs.psw.addr) /* I'd like to reject addresses without the high order bit but older gdb's rely on it */ data |= PSW_ADDR_AMODE; #endif *(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr) = data; } else if (addr < (addr_t) (&dummy->regs.orig_gpr2)) { /* * access registers are stored in the thread structure */ offset = addr - (addr_t) &dummy->regs.acrs; #ifdef CONFIG_64BIT /* * Very special case: old & broken 64 bit gdb writing * to acrs[15] with a 64 bit value. Ignore the lower * half of the value and write the upper 32 bit to * acrs[15]. Sick... */ if (addr == (addr_t) &dummy->regs.acrs[15]) child->thread.acrs[15] = (unsigned int) (data >> 32); else #endif *(addr_t *)((addr_t) &child->thread.acrs + offset) = data; } else if (addr == (addr_t) &dummy->regs.orig_gpr2) { /* * orig_gpr2 is stored on the kernel stack */ task_pt_regs(child)->orig_gpr2 = data; } else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) { /* * floating point regs. are stored in the thread structure */ if (addr == (addr_t) &dummy->regs.fp_regs.fpc && (data & ~((unsigned long) FPC_VALID_MASK << (BITS_PER_LONG - 32))) != 0) return -EINVAL; offset = addr - (addr_t) &dummy->regs.fp_regs; *(addr_t *)((addr_t) &child->thread.fp_regs + offset) = data; } else if (addr < (addr_t) (&dummy->regs.per_info + 1)) { /* * per_info is found in the thread structure */ offset = addr - (addr_t) &dummy->regs.per_info; *(addr_t *)((addr_t) &child->thread.per_info + offset) = data; } FixPerRegisters(child); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': '[S390] CVE-2008-1514: prevent ptrace padding area read/write in 31-bit mode When running a 31-bit ptrace, on either an s390 or s390x kernel, reads and writes into a padding area in struct user_regs_struct32 will result in a kernel panic. This is also known as CVE-2008-1514. Test case available here: http://sources.redhat.com/cgi-bin/cvsweb.cgi/~checkout~/tests/ptrace-tests/tests/user-area-padding.c?cvsroot=systemtap Steps to reproduce: 1) wget the above 2) gcc -o user-area-padding-31bit user-area-padding.c -Wall -ggdb2 -D_GNU_SOURCE -m31 3) ./user-area-padding-31bit <panic> Test status ----------- Without patch, both s390 and s390x kernels panic. With patch, the test case, as well as the gdb testsuite, pass without incident, padding area reads returning zero, writes ignored. Nb: original version returned -EINVAL on write attempts, which broke the gdb test and made the test case slightly unhappy, Jan Kratochvil suggested the change to return 0 on write attempts. Signed-off-by: Jarod Wilson <jarod@redhat.com> Tested-by: Jan Kratochvil <jan.kratochvil@redhat.com> Signed-off-by: Martin Schwidefsky <schwidefsky@de.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int fcntl_dirnotify(int fd, struct file *filp, unsigned long arg) { struct dnotify_struct *dn; struct dnotify_struct *odn; struct dnotify_struct **prev; struct inode *inode; fl_owner_t id = current->files; int error = 0; if ((arg & ~DN_MULTISHOT) == 0) { dnotify_flush(filp, id); return 0; } if (!dir_notify_enable) return -EINVAL; inode = filp->f_path.dentry->d_inode; if (!S_ISDIR(inode->i_mode)) return -ENOTDIR; dn = kmem_cache_alloc(dn_cache, GFP_KERNEL); if (dn == NULL) return -ENOMEM; spin_lock(&inode->i_lock); prev = &inode->i_dnotify; while ((odn = *prev) != NULL) { if ((odn->dn_owner == id) && (odn->dn_filp == filp)) { odn->dn_fd = fd; odn->dn_mask |= arg; inode->i_dnotify_mask |= arg & ~DN_MULTISHOT; goto out_free; } prev = &odn->dn_next; } error = __f_setown(filp, task_pid(current), PIDTYPE_PID, 0); if (error) goto out_free; dn->dn_mask = arg; dn->dn_fd = fd; dn->dn_filp = filp; dn->dn_owner = id; inode->i_dnotify_mask |= arg & ~DN_MULTISHOT; dn->dn_next = inode->i_dnotify; inode->i_dnotify = dn; spin_unlock(&inode->i_lock); if (filp->f_op && filp->f_op->dir_notify) return filp->f_op->dir_notify(filp, arg); return 0; out_free: spin_unlock(&inode->i_lock); kmem_cache_free(dn_cache, dn); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix dnotify/close race We have a race between fcntl() and close() that can lead to dnotify_struct inserted into inode's list *after* the last descriptor had been gone from current->files. Since that's the only point where dnotify_struct gets evicted, we are screwed - it will stick around indefinitely. Even after struct file in question is gone and freed. Worse, we can trigger send_sigio() on it at any later point, which allows to send an arbitrary signal to arbitrary process if we manage to apply enough memory pressure to get the page that used to host that struct file and fill it with the right pattern... Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CairoFont *CairoFont::create(GfxFont *gfxFont, XRef *xref, FT_Library lib, GBool useCIDs) { Ref embRef; Object refObj, strObj; GooString *tmpFileName, *fileName,*tmpFileName2; DisplayFontParam *dfp; FILE *tmpFile; int c, i, n; GfxFontType fontType; char **enc; char *name; FoFiTrueType *ff; FoFiType1C *ff1c; Ref ref; static cairo_user_data_key_t cairo_font_face_key; cairo_font_face_t *cairo_font_face; FT_Face face; Gushort *codeToGID; int codeToGIDLen; dfp = NULL; codeToGID = NULL; codeToGIDLen = 0; cairo_font_face = NULL; ref = *gfxFont->getID(); fontType = gfxFont->getType(); tmpFileName = NULL; if (gfxFont->getEmbeddedFontID(&embRef)) { if (!openTempFile(&tmpFileName, &tmpFile, "wb", NULL)) { error(-1, "Couldn't create temporary font file"); goto err2; } refObj.initRef(embRef.num, embRef.gen); refObj.fetch(xref, &strObj); refObj.free(); strObj.streamReset(); while ((c = strObj.streamGetChar()) != EOF) { fputc(c, tmpFile); } strObj.streamClose(); strObj.free(); fclose(tmpFile); fileName = tmpFileName; } else if (!(fileName = gfxFont->getExtFontFile())) { // look for a display font mapping or a substitute font dfp = NULL; if (gfxFont->getName()) { dfp = globalParams->getDisplayFont(gfxFont); } if (!dfp) { error(-1, "Couldn't find a font for '%s'", gfxFont->getName() ? gfxFont->getName()->getCString() : "(unnamed)"); goto err2; } switch (dfp->kind) { case displayFontT1: fileName = dfp->t1.fileName; fontType = gfxFont->isCIDFont() ? fontCIDType0 : fontType1; break; case displayFontTT: fileName = dfp->tt.fileName; fontType = gfxFont->isCIDFont() ? fontCIDType2 : fontTrueType; break; } } switch (fontType) { case fontType1: case fontType1C: if (FT_New_Face(lib, fileName->getCString(), 0, &face)) { error(-1, "could not create type1 face"); goto err2; } enc = ((Gfx8BitFont *)gfxFont)->getEncoding(); codeToGID = (Gushort *)gmallocn(256, sizeof(int)); codeToGIDLen = 256; for (i = 0; i < 256; ++i) { codeToGID[i] = 0; if ((name = enc[i])) { codeToGID[i] = (Gushort)FT_Get_Name_Index(face, name); } } break; case fontCIDType2: codeToGID = NULL; n = 0; if (((GfxCIDFont *)gfxFont)->getCIDToGID()) { n = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen(); if (n) { codeToGID = (Gushort *)gmallocn(n, sizeof(Gushort)); memcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(), n * sizeof(Gushort)); } } else { ff = FoFiTrueType::load(fileName->getCString()); if (! ff) goto err2; codeToGID = ((GfxCIDFont *)gfxFont)->getCodeToGIDMap(ff, &n); delete ff; } codeToGIDLen = n; /* Fall through */ case fontTrueType: if (!(ff = FoFiTrueType::load(fileName->getCString()))) { error(-1, "failed to load truetype font\n"); goto err2; } /* This might be set already for the CIDType2 case */ if (fontType == fontTrueType) { codeToGID = ((Gfx8BitFont *)gfxFont)->getCodeToGIDMap(ff); codeToGIDLen = 256; } if (!openTempFile(&tmpFileName2, &tmpFile, "wb", NULL)) { delete ff; error(-1, "failed to open truetype tempfile\n"); goto err2; } ff->writeTTF(&fileWrite, tmpFile); fclose(tmpFile); delete ff; if (FT_New_Face(lib, tmpFileName2->getCString(), 0, &face)) { error(-1, "could not create truetype face\n"); goto err2; } unlink (tmpFileName2->getCString()); delete tmpFileName2; break; case fontCIDType0: case fontCIDType0C: codeToGID = NULL; codeToGIDLen = 0; if (!useCIDs) { if ((ff1c = FoFiType1C::load(fileName->getCString()))) { codeToGID = ff1c->getCIDToGIDMap(&codeToGIDLen); delete ff1c; } } if (FT_New_Face(lib, fileName->getCString(), 0, &face)) { gfree(codeToGID); codeToGID = NULL; error(-1, "could not create cid face\n"); goto err2; } break; default: printf ("font type not handled\n"); goto err2; break; } // delete the (temporary) font file -- with Unix hard link // semantics, this will remove the last link; otherwise it will // return an error, leaving the file to be deleted later if (fileName == tmpFileName) { unlink (fileName->getCString()); delete tmpFileName; } cairo_font_face = cairo_ft_font_face_create_for_ft_face (face, FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP); if (cairo_font_face == NULL) { error(-1, "could not create cairo font\n"); goto err2; /* this doesn't do anything, but it looks like we're * handling the error */ } { CairoFont *ret = new CairoFont(ref, cairo_font_face, face, codeToGID, codeToGIDLen); cairo_font_face_set_user_data (cairo_font_face, &cairo_font_face_key, ret, cairo_font_face_destroy); return ret; } err2: /* hmm? */ printf ("some font thing failed\n"); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix a crash with invalid embedded fonts'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: asn1_oid_decode(struct asn1_ctx *ctx, unsigned char *eoc, unsigned long **oid, unsigned int *len) { unsigned long subid; unsigned int size; unsigned long *optr; size = eoc - ctx->pointer + 1; *oid = kmalloc(size * sizeof(unsigned long), GFP_ATOMIC); if (*oid == NULL) return 0; optr = *oid; if (!asn1_subid_decode(ctx, &subid)) { kfree(*oid); *oid = NULL; return 0; } if (subid < 40) { optr[0] = 0; optr[1] = subid; } else if (subid < 80) { optr[0] = 1; optr[1] = subid - 40; } else { optr[0] = 2; optr[1] = subid - 80; } *len = 2; optr += 2; while (ctx->pointer < eoc) { if (++(*len) > size) { ctx->error = ASN1_ERR_DEC_BADVALUE; kfree(*oid); *oid = NULL; return 0; } if (!asn1_subid_decode(ctx, optr++)) { kfree(*oid); *oid = NULL; return 0; } } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'asn1: additional sanity checking during BER decoding - Don't trust a length which is greater than the working buffer. An invalid length could cause overflow when calculating buffer size for decoding oid. - An oid length of zero is invalid and allows for an off-by-one error when decoding oid because the first subid actually encodes first 2 subids. - A primitive encoding may not have an indefinite length. Thanks to Wei Wang from McAfee for report. Cc: Steven French <sfrench@us.ibm.com> Cc: stable@kernel.org Acked-by: Patrick McHardy <kaber@trash.net> Signed-off-by: Chris Wright <chrisw@sous-sol.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static unsigned char asn1_header_decode(struct asn1_ctx *ctx, unsigned char **eoc, unsigned int *cls, unsigned int *con, unsigned int *tag) { unsigned int def, len; if (!asn1_id_decode(ctx, cls, con, tag)) return 0; def = len = 0; if (!asn1_length_decode(ctx, &def, &len)) return 0; if (def) *eoc = ctx->pointer + len; else *eoc = NULL; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'asn1: additional sanity checking during BER decoding - Don't trust a length which is greater than the working buffer. An invalid length could cause overflow when calculating buffer size for decoding oid. - An oid length of zero is invalid and allows for an off-by-one error when decoding oid because the first subid actually encodes first 2 subids. - A primitive encoding may not have an indefinite length. Thanks to Wei Wang from McAfee for report. Cc: Steven French <sfrench@us.ibm.com> Cc: stable@kernel.org Acked-by: Patrick McHardy <kaber@trash.net> Signed-off-by: Chris Wright <chrisw@sous-sol.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: asn1_length_decode(struct asn1_ctx *ctx, unsigned int *def, unsigned int *len) { unsigned char ch, cnt; if (!asn1_octet_decode(ctx, &ch)) return 0; if (ch == 0x80) *def = 0; else { *def = 1; if (ch < 0x80) *len = ch; else { cnt = (unsigned char) (ch & 0x7F); *len = 0; while (cnt > 0) { if (!asn1_octet_decode(ctx, &ch)) return 0; *len <<= 8; *len |= ch; cnt--; } } } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'asn1: additional sanity checking during BER decoding - Don't trust a length which is greater than the working buffer. An invalid length could cause overflow when calculating buffer size for decoding oid. - An oid length of zero is invalid and allows for an off-by-one error when decoding oid because the first subid actually encodes first 2 subids. - A primitive encoding may not have an indefinite length. Thanks to Wei Wang from McAfee for report. Cc: Steven French <sfrench@us.ibm.com> Cc: stable@kernel.org Acked-by: Patrick McHardy <kaber@trash.net> Signed-off-by: Chris Wright <chrisw@sous-sol.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _gnutls_server_name_recv_params (gnutls_session_t session, const opaque * data, size_t _data_size) { int i; const unsigned char *p; uint16_t len, type; ssize_t data_size = _data_size; int server_names = 0; if (session->security_parameters.entity == GNUTLS_SERVER) { DECR_LENGTH_RET (data_size, 2, 0); len = _gnutls_read_uint16 (data); if (len != data_size) { /* This is unexpected packet length, but * just ignore it, for now. */ gnutls_assert (); return 0; } p = data + 2; /* Count all server_names in the packet. */ while (data_size > 0) { DECR_LENGTH_RET (data_size, 1, 0); p++; DECR_LEN (data_size, 2); len = _gnutls_read_uint16 (p); p += 2; DECR_LENGTH_RET (data_size, len, 0); server_names++; p += len; } session->security_parameters.extensions.server_names_size = server_names; if (server_names == 0) return 0; /* no names found */ /* we cannot accept more server names. */ if (server_names > MAX_SERVER_NAME_EXTENSIONS) server_names = MAX_SERVER_NAME_EXTENSIONS; p = data + 2; for (i = 0; i < server_names; i++) { type = *p; p++; len = _gnutls_read_uint16 (p); p += 2; switch (type) { case 0: /* NAME_DNS */ if (len <= MAX_SERVER_NAME_SIZE) { memcpy (session->security_parameters.extensions. server_names[i].name, p, len); session->security_parameters.extensions. server_names[i].name_length = len; session->security_parameters.extensions. server_names[i].type = GNUTLS_NAME_DNS; break; } } /* move to next record */ p += len; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix GNUTLS-SA-2008-1 security vulnerabilities. See http://www.gnu.org/software/gnutls/security.html for updates.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _gnutls_recv_handshake_header (gnutls_session_t session, gnutls_handshake_description_t type, gnutls_handshake_description_t * recv_type) { int ret; uint32_t length32 = 0; uint8_t *dataptr = NULL; /* for realloc */ size_t handshake_header_size = HANDSHAKE_HEADER_SIZE; /* if we have data into the buffer then return them, do not read the next packet. * In order to return we need a full TLS handshake header, or in case of a version 2 * packet, then we return the first byte. */ if (session->internals.handshake_header_buffer.header_size == handshake_header_size || (session->internals.v2_hello != 0 && type == GNUTLS_HANDSHAKE_CLIENT_HELLO && session->internals. handshake_header_buffer.packet_length > 0)) { *recv_type = session->internals.handshake_header_buffer.recv_type; return session->internals.handshake_header_buffer.packet_length; } /* Note: SSL2_HEADERS == 1 */ dataptr = session->internals.handshake_header_buffer.header; /* If we haven't already read the handshake headers. */ if (session->internals.handshake_header_buffer.header_size < SSL2_HEADERS) { ret = _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE, type, dataptr, SSL2_HEADERS); if (ret < 0) { gnutls_assert (); return ret; } /* The case ret==0 is caught here. */ if (ret != SSL2_HEADERS) { gnutls_assert (); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } session->internals.handshake_header_buffer.header_size = SSL2_HEADERS; } if (session->internals.v2_hello == 0 || type != GNUTLS_HANDSHAKE_CLIENT_HELLO) { ret = _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE, type, &dataptr[session-> internals. handshake_header_buffer. header_size], HANDSHAKE_HEADER_SIZE - session->internals. handshake_header_buffer.header_size); if (ret <= 0) { gnutls_assert (); return (ret < 0) ? ret : GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } if ((size_t) ret != HANDSHAKE_HEADER_SIZE - session->internals.handshake_header_buffer.header_size) { gnutls_assert (); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } *recv_type = dataptr[0]; /* we do not use DECR_LEN because we know * that the packet has enough data. */ length32 = _gnutls_read_uint24 (&dataptr[1]); handshake_header_size = HANDSHAKE_HEADER_SIZE; _gnutls_handshake_log ("HSK[%x]: %s was received [%ld bytes]\n", session, _gnutls_handshake2str (dataptr[0]), length32 + HANDSHAKE_HEADER_SIZE); } else { /* v2 hello */ length32 = session->internals.v2_hello - SSL2_HEADERS; /* we've read the first byte */ handshake_header_size = SSL2_HEADERS; /* we've already read one byte */ *recv_type = dataptr[0]; _gnutls_handshake_log ("HSK[%x]: %s(v2) was received [%ld bytes]\n", session, _gnutls_handshake2str (*recv_type), length32 + handshake_header_size); if (*recv_type != GNUTLS_HANDSHAKE_CLIENT_HELLO) { /* it should be one or nothing */ gnutls_assert (); return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET; } } /* put the packet into the buffer */ session->internals.handshake_header_buffer.header_size = handshake_header_size; session->internals.handshake_header_buffer.packet_length = length32; session->internals.handshake_header_buffer.recv_type = *recv_type; if (*recv_type != type) { gnutls_assert (); return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET; } return length32; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix GNUTLS-SA-2008-1 security vulnerabilities. See http://www.gnu.org/software/gnutls/security.html for updates.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, int len, int write, int force, struct page **pages, struct vm_area_struct **vmas) { int i; unsigned int vm_flags; if (len <= 0) return 0; /* * Require read or write permissions. * If 'force' is set, we only require the "MAY" flags. */ vm_flags = write ? (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD); vm_flags &= force ? (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE); i = 0; do { struct vm_area_struct *vma; unsigned int foll_flags; vma = find_extend_vma(mm, start); if (!vma && in_gate_area(tsk, start)) { unsigned long pg = start & PAGE_MASK; struct vm_area_struct *gate_vma = get_gate_vma(tsk); pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; if (write) /* user gate pages are read-only */ return i ? : -EFAULT; if (pg > TASK_SIZE) pgd = pgd_offset_k(pg); else pgd = pgd_offset_gate(mm, pg); BUG_ON(pgd_none(*pgd)); pud = pud_offset(pgd, pg); BUG_ON(pud_none(*pud)); pmd = pmd_offset(pud, pg); if (pmd_none(*pmd)) return i ? : -EFAULT; pte = pte_offset_map(pmd, pg); if (pte_none(*pte)) { pte_unmap(pte); return i ? : -EFAULT; } if (pages) { struct page *page = vm_normal_page(gate_vma, start, *pte); pages[i] = page; if (page) get_page(page); } pte_unmap(pte); if (vmas) vmas[i] = gate_vma; i++; start += PAGE_SIZE; len--; continue; } if (!vma || (vma->vm_flags & (VM_IO | VM_PFNMAP)) || !(vm_flags & vma->vm_flags)) return i ? : -EFAULT; if (is_vm_hugetlb_page(vma)) { i = follow_hugetlb_page(mm, vma, pages, vmas, &start, &len, i, write); continue; } foll_flags = FOLL_TOUCH; if (pages) foll_flags |= FOLL_GET; if (!write && !(vma->vm_flags & VM_LOCKED) && (!vma->vm_ops || !vma->vm_ops->fault)) foll_flags |= FOLL_ANON; do { struct page *page; /* * If tsk is ooming, cut off its access to large memory * allocations. It has a pending SIGKILL, but it can't * be processed until returning to user space. */ if (unlikely(test_tsk_thread_flag(tsk, TIF_MEMDIE))) return -ENOMEM; if (write) foll_flags |= FOLL_WRITE; cond_resched(); while (!(page = follow_page(vma, start, foll_flags))) { int ret; ret = handle_mm_fault(mm, vma, start, foll_flags & FOLL_WRITE); if (ret & VM_FAULT_ERROR) { if (ret & VM_FAULT_OOM) return i ? i : -ENOMEM; else if (ret & VM_FAULT_SIGBUS) return i ? i : -EFAULT; BUG(); } if (ret & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; /* * The VM_FAULT_WRITE bit tells us that * do_wp_page has broken COW when necessary, * even if maybe_mkwrite decided not to set * pte_write. We can thus safely do subsequent * page lookups as if they were reads. */ if (ret & VM_FAULT_WRITE) foll_flags &= ~FOLL_WRITE; cond_resched(); } if (pages) { pages[i] = page; flush_anon_page(vma, page, start); flush_dcache_page(page); } if (vmas) vmas[i] = vma; i++; start += PAGE_SIZE; len--; } while (len && start < vma->vm_end); } while (len); return i; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Reinstate ZERO_PAGE optimization in 'get_user_pages()' and fix XIP KAMEZAWA Hiroyuki and Oleg Nesterov point out that since the commit 557ed1fa2620dc119adb86b34c614e152a629a80 ("remove ZERO_PAGE") removed the ZERO_PAGE from the VM mappings, any users of get_user_pages() will generally now populate the VM with real empty pages needlessly. We used to get the ZERO_PAGE when we did the "handle_mm_fault()", but since fault handling no longer uses ZERO_PAGE for new anonymous pages, we now need to handle that special case in follow_page() instead. In particular, the removal of ZERO_PAGE effectively removed the core file writing optimization where we would skip writing pages that had not been populated at all, and increased memory pressure a lot by allocating all those useless newly zeroed pages. This reinstates the optimization by making the unmapped PTE case the same as for a non-existent page table, which already did this correctly. While at it, this also fixes the XIP case for follow_page(), where the caller could not differentiate between the case of a page that simply could not be used (because it had no "struct page" associated with it) and a page that just wasn't mapped. We do that by simply returning an error pointer for pages that could not be turned into a "struct page *". The error is arbitrarily picked to be EFAULT, since that was what get_user_pages() already used for the equivalent IO-mapped page case. [ Also removed an impossible test for pte_offset_map_lock() failing: that's not how that function works ] Acked-by: Oleg Nesterov <oleg@tv-sign.ru> Acked-by: Nick Piggin <npiggin@suse.de> Cc: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com> Cc: Hugh Dickins <hugh@veritas.com> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Ingo Molnar <mingo@elte.hu> Cc: Roland McGrath <roland@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int do_move_pages(struct mm_struct *mm, struct page_to_node *pm, int migrate_all) { int err; struct page_to_node *pp; LIST_HEAD(pagelist); down_read(&mm->mmap_sem); /* * Build a list of pages to migrate */ migrate_prep(); for (pp = pm; pp->node != MAX_NUMNODES; pp++) { struct vm_area_struct *vma; struct page *page; /* * A valid page pointer that will not match any of the * pages that will be moved. */ pp->page = ZERO_PAGE(0); err = -EFAULT; vma = find_vma(mm, pp->addr); if (!vma || !vma_migratable(vma)) goto set_status; page = follow_page(vma, pp->addr, FOLL_GET); err = -ENOENT; if (!page) goto set_status; if (PageReserved(page)) /* Check for zero page */ goto put_and_set; pp->page = page; err = page_to_nid(page); if (err == pp->node) /* * Node already in the right place */ goto put_and_set; err = -EACCES; if (page_mapcount(page) > 1 && !migrate_all) goto put_and_set; err = isolate_lru_page(page, &pagelist); put_and_set: /* * Either remove the duplicate refcount from * isolate_lru_page() or drop the page ref if it was * not isolated. */ put_page(page); set_status: pp->status = err; } if (!list_empty(&pagelist)) err = migrate_pages(&pagelist, new_page_node, (unsigned long)pm); else err = -ENOENT; up_read(&mm->mmap_sem); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Reinstate ZERO_PAGE optimization in 'get_user_pages()' and fix XIP KAMEZAWA Hiroyuki and Oleg Nesterov point out that since the commit 557ed1fa2620dc119adb86b34c614e152a629a80 ("remove ZERO_PAGE") removed the ZERO_PAGE from the VM mappings, any users of get_user_pages() will generally now populate the VM with real empty pages needlessly. We used to get the ZERO_PAGE when we did the "handle_mm_fault()", but since fault handling no longer uses ZERO_PAGE for new anonymous pages, we now need to handle that special case in follow_page() instead. In particular, the removal of ZERO_PAGE effectively removed the core file writing optimization where we would skip writing pages that had not been populated at all, and increased memory pressure a lot by allocating all those useless newly zeroed pages. This reinstates the optimization by making the unmapped PTE case the same as for a non-existent page table, which already did this correctly. While at it, this also fixes the XIP case for follow_page(), where the caller could not differentiate between the case of a page that simply could not be used (because it had no "struct page" associated with it) and a page that just wasn't mapped. We do that by simply returning an error pointer for pages that could not be turned into a "struct page *". The error is arbitrarily picked to be EFAULT, since that was what get_user_pages() already used for the equivalent IO-mapped page case. [ Also removed an impossible test for pte_offset_map_lock() failing: that's not how that function works ] Acked-by: Oleg Nesterov <oleg@tv-sign.ru> Acked-by: Nick Piggin <npiggin@suse.de> Cc: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com> Cc: Hugh Dickins <hugh@veritas.com> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Ingo Molnar <mingo@elte.hu> Cc: Roland McGrath <roland@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct page *follow_page(struct vm_area_struct *vma, unsigned long address, unsigned int flags) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *ptep, pte; spinlock_t *ptl; struct page *page; struct mm_struct *mm = vma->vm_mm; page = follow_huge_addr(mm, address, flags & FOLL_WRITE); if (!IS_ERR(page)) { BUG_ON(flags & FOLL_GET); goto out; } page = NULL; pgd = pgd_offset(mm, address); if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd))) goto no_page_table; pud = pud_offset(pgd, address); if (pud_none(*pud) || unlikely(pud_bad(*pud))) goto no_page_table; pmd = pmd_offset(pud, address); if (pmd_none(*pmd)) goto no_page_table; if (pmd_huge(*pmd)) { BUG_ON(flags & FOLL_GET); page = follow_huge_pmd(mm, address, pmd, flags & FOLL_WRITE); goto out; } if (unlikely(pmd_bad(*pmd))) goto no_page_table; ptep = pte_offset_map_lock(mm, pmd, address, &ptl); if (!ptep) goto out; pte = *ptep; if (!pte_present(pte)) goto unlock; if ((flags & FOLL_WRITE) && !pte_write(pte)) goto unlock; page = vm_normal_page(vma, address, pte); if (unlikely(!page)) goto unlock; if (flags & FOLL_GET) get_page(page); if (flags & FOLL_TOUCH) { if ((flags & FOLL_WRITE) && !pte_dirty(pte) && !PageDirty(page)) set_page_dirty(page); mark_page_accessed(page); } unlock: pte_unmap_unlock(ptep, ptl); out: return page; no_page_table: /* * When core dumping an enormous anonymous area that nobody * has touched so far, we don't want to allocate page tables. */ if (flags & FOLL_ANON) { page = ZERO_PAGE(0); if (flags & FOLL_GET) get_page(page); BUG_ON(flags & FOLL_WRITE); } return page; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Reinstate ZERO_PAGE optimization in 'get_user_pages()' and fix XIP KAMEZAWA Hiroyuki and Oleg Nesterov point out that since the commit 557ed1fa2620dc119adb86b34c614e152a629a80 ("remove ZERO_PAGE") removed the ZERO_PAGE from the VM mappings, any users of get_user_pages() will generally now populate the VM with real empty pages needlessly. We used to get the ZERO_PAGE when we did the "handle_mm_fault()", but since fault handling no longer uses ZERO_PAGE for new anonymous pages, we now need to handle that special case in follow_page() instead. In particular, the removal of ZERO_PAGE effectively removed the core file writing optimization where we would skip writing pages that had not been populated at all, and increased memory pressure a lot by allocating all those useless newly zeroed pages. This reinstates the optimization by making the unmapped PTE case the same as for a non-existent page table, which already did this correctly. While at it, this also fixes the XIP case for follow_page(), where the caller could not differentiate between the case of a page that simply could not be used (because it had no "struct page" associated with it) and a page that just wasn't mapped. We do that by simply returning an error pointer for pages that could not be turned into a "struct page *". The error is arbitrarily picked to be EFAULT, since that was what get_user_pages() already used for the equivalent IO-mapped page case. [ Also removed an impossible test for pte_offset_map_lock() failing: that's not how that function works ] Acked-by: Oleg Nesterov <oleg@tv-sign.ru> Acked-by: Nick Piggin <npiggin@suse.de> Cc: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com> Cc: Hugh Dickins <hugh@veritas.com> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: Ingo Molnar <mingo@elte.hu> Cc: Roland McGrath <roland@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int do_change_type(struct nameidata *nd, int flag) { struct vfsmount *m, *mnt = nd->mnt; int recurse = flag & MS_REC; int type = flag & ~MS_REC; if (nd->dentry != nd->mnt->mnt_root) return -EINVAL; down_write(&namespace_sem); spin_lock(&vfsmount_lock); for (m = mnt; m; m = (recurse ? next_mnt(m, mnt) : NULL)) change_mnt_propagation(m, type); spin_unlock(&vfsmount_lock); up_write(&namespace_sem); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'check privileges before setting mount propagation There's a missing check for CAP_SYS_ADMIN in do_change_type(). Signed-off-by: Miklos Szeredi <mszeredi@suse.cz> Cc: Al Viro <viro@zeniv.linux.org.uk> Cc: Christoph Hellwig <hch@lst.de> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: shmem_get_inode(struct super_block *sb, int mode, dev_t dev) { struct inode *inode; struct shmem_inode_info *info; struct shmem_sb_info *sbinfo = SHMEM_SB(sb); if (shmem_reserve_inode(sb)) return NULL; inode = new_inode(sb); if (inode) { inode->i_mode = mode; inode->i_uid = current->fsuid; inode->i_gid = current->fsgid; inode->i_blocks = 0; inode->i_mapping->a_ops = &shmem_aops; inode->i_mapping->backing_dev_info = &shmem_backing_dev_info; inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME; inode->i_generation = get_seconds(); info = SHMEM_I(inode); memset(info, 0, (char *)inode - (char *)info); spin_lock_init(&info->lock); INIT_LIST_HEAD(&info->swaplist); switch (mode & S_IFMT) { default: inode->i_op = &shmem_special_inode_operations; init_special_inode(inode, mode, dev); break; case S_IFREG: inode->i_op = &shmem_inode_operations; inode->i_fop = &shmem_file_operations; mpol_shared_policy_init(&info->policy, shmem_get_sbmpol(sbinfo)); break; case S_IFDIR: inc_nlink(inode); /* Some things misbehave if size == 0 on a directory */ inode->i_size = 2 * BOGO_DIRENT_SIZE; inode->i_op = &shmem_dir_inode_operations; inode->i_fop = &simple_dir_operations; break; case S_IFLNK: /* * Must not load anything in the rbtree, * mpol_free_shared_policy will not be called. */ mpol_shared_policy_init(&info->policy, NULL); break; } } else shmem_free_inode(sb); return inode; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'tmpfs: fix kernel BUG in shmem_delete_inode SuSE's insserve initscript ordering program hits kernel BUG at mm/shmem.c:814 on 2.6.26. It's using posix_fadvise on directories, and the shmem_readpage method added in 2.6.23 is letting POSIX_FADV_WILLNEED allocate useless pages to a tmpfs directory, incrementing i_blocks count but never decrementing it. Fix this by assigning shmem_aops (pointing to readpage and writepage and set_page_dirty) only when it's needed, on a regular file or a long symlink. Many thanks to Kel for outstanding bugreport and steps to reproduce it. Reported-by: Kel Modderman <kel@otaku42.de> Tested-by: Kel Modderman <kel@otaku42.de> Signed-off-by: Hugh Dickins <hugh@veritas.com> Cc: <stable@kernel.org> [2.6.25.x, 2.6.26.x] Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void iov_iter_advance(struct iov_iter *i, size_t bytes) { BUG_ON(i->count < bytes); if (likely(i->nr_segs == 1)) { i->iov_offset += bytes; i->count -= bytes; } else { const struct iovec *iov = i->iov; size_t base = i->iov_offset; /* * The !iov->iov_len check ensures we skip over unlikely * zero-length segments (without overruning the iovec). */ while (bytes || unlikely(!iov->iov_len && i->count)) { int copy; copy = min(bytes, iov->iov_len - base); BUG_ON(!i->count || i->count < copy); i->count -= copy; bytes -= copy; base += copy; if (iov->iov_len == base) { iov++; base = 0; } } i->iov = iov; i->iov_offset = base; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-193'], 'message': 'Fix off-by-one error in iov_iter_advance() The iov_iter_advance() function would look at the iov->iov_len entry even though it might have iterated over the whole array, and iov was pointing past the end. This would cause DEBUG_PAGEALLOC to trigger a kernel page fault if the allocation was at the end of a page, and the next page was unallocated. The quick fix is to just change the order of the tests: check that there is any iovec data left before we check the iov entry itself. Thanks to Alexey Dobriyan for finding this case, and testing the fix. Reported-and-tested-by: Alexey Dobriyan <adobriyan@gmail.com> Cc: Nick Piggin <npiggin@suse.de> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: <stable@kernel.org> [2.6.25.x, 2.6.26.x] Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct dentry * real_lookup(struct dentry * parent, struct qstr * name, struct nameidata *nd) { struct dentry * result; struct inode *dir = parent->d_inode; mutex_lock(&dir->i_mutex); /* * First re-do the cached lookup just in case it was created * while we waited for the directory semaphore.. * * FIXME! This could use version numbering or similar to * avoid unnecessary cache lookups. * * The "dcache_lock" is purely to protect the RCU list walker * from concurrent renames at this point (we mustn't get false * negatives from the RCU list walk here, unlike the optimistic * fast walk). * * so doing d_lookup() (with seqlock), instead of lockfree __d_lookup */ result = d_lookup(parent, name); if (!result) { struct dentry * dentry = d_alloc(parent, name); result = ERR_PTR(-ENOMEM); if (dentry) { result = dir->i_op->lookup(dir, dentry, nd); if (result) dput(dentry); else result = dentry; } mutex_unlock(&dir->i_mutex); return result; } /* * Uhhuh! Nasty case: the cache was re-populated while * we waited on the semaphore. Need to revalidate. */ mutex_unlock(&dir->i_mutex); if (result->d_op && result->d_op->d_revalidate) { result = do_revalidate(result, nd); if (!result) result = ERR_PTR(-ENOENT); } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': '[patch] vfs: fix lookup on deleted directory Lookup can install a child dentry for a deleted directory. This keeps the directory dentry alive, and the inode pinned in the cache and on disk, even after all external references have gone away. This isn't a big problem normally, since memory pressure or umount will clear out the directory dentry and its children, releasing the inode. But for UBIFS this causes problems because its orphan area can overflow. Fix this by returning ENOENT for all lookups on a S_DEAD directory before creating a child dentry. Thanks to Zoltan Sogor for noticing this while testing UBIFS, and Artem for the excellent analysis of the problem and testing. Reported-by: Artem Bityutskiy <Artem.Bityutskiy@nokia.com> Tested-by: Artem Bityutskiy <Artem.Bityutskiy@nokia.com> Signed-off-by: Miklos Szeredi <mszeredi@suse.cz> Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: snd_seq_oss_synth_make_info(struct seq_oss_devinfo *dp, int dev, struct synth_info *inf) { struct seq_oss_synth *rec; if (dp->synths[dev].is_midi) { struct midi_info minf; snd_seq_oss_midi_make_info(dp, dp->synths[dev].midi_mapped, &minf); inf->synth_type = SYNTH_TYPE_MIDI; inf->synth_subtype = 0; inf->nr_voices = 16; inf->device = dev; strlcpy(inf->name, minf.name, sizeof(inf->name)); } else { if ((rec = get_synthdev(dp, dev)) == NULL) return -ENXIO; inf->synth_type = rec->synth_type; inf->synth_subtype = rec->synth_subtype; inf->nr_voices = rec->nr_voices; inf->device = dev; strlcpy(inf->name, rec->name, sizeof(inf->name)); snd_use_lock_free(&rec->use_lock); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'sound: ensure device number is valid in snd_seq_oss_synth_make_info snd_seq_oss_synth_make_info() incorrectly reports information to userspace without first checking for the validity of the device number, leading to possible information leak (CVE-2008-3272). Reported-By: Tobias Klein <tk@trapkit.de> Acked-and-tested-by: Takashi Iwai <tiwai@suse.de> Cc: stable@kernel.org Signed-off-by: Willy Tarreau <w@1wt.eu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int show_modified(struct oneway_unpack_data *cbdata, struct cache_entry *old, struct cache_entry *new, int report_missing, int cached, int match_missing) { unsigned int mode, oldmode; const unsigned char *sha1; struct rev_info *revs = cbdata->revs; if (get_stat_data(new, &sha1, &mode, cached, match_missing, cbdata) < 0) { if (report_missing) diff_index_show_file(revs, "-", old, old->sha1, old->ce_mode); return -1; } if (revs->combine_merges && !cached && (hashcmp(sha1, old->sha1) || hashcmp(old->sha1, new->sha1))) { struct combine_diff_path *p; int pathlen = ce_namelen(new); p = xmalloc(combine_diff_path_size(2, pathlen)); p->path = (char *) &p->parent[2]; p->next = NULL; p->len = pathlen; memcpy(p->path, new->name, pathlen); p->path[pathlen] = 0; p->mode = mode; hashclr(p->sha1); memset(p->parent, 0, 2 * sizeof(struct combine_diff_parent)); p->parent[0].status = DIFF_STATUS_MODIFIED; p->parent[0].mode = new->ce_mode; hashcpy(p->parent[0].sha1, new->sha1); p->parent[1].status = DIFF_STATUS_MODIFIED; p->parent[1].mode = old->ce_mode; hashcpy(p->parent[1].sha1, old->sha1); show_combined_diff(p, 2, revs->dense_combined_merges, revs); free(p); return 0; } oldmode = old->ce_mode; if (mode == oldmode && !hashcmp(sha1, old->sha1) && !DIFF_OPT_TST(&revs->diffopt, FIND_COPIES_HARDER)) return 0; diff_change(&revs->diffopt, oldmode, mode, old->sha1, sha1, old->name, NULL); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix buffer overflow in git diff If PATH_MAX on your system is smaller than a path stored, it may cause buffer overflow and stack corruption in diff_addremove() and diff_change() functions when running git-diff Signed-off-by: Dmitry Potapov <dpotapov@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void diff_index_show_file(struct rev_info *revs, const char *prefix, struct cache_entry *ce, const unsigned char *sha1, unsigned int mode) { diff_addremove(&revs->diffopt, prefix[0], mode, sha1, ce->name, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix buffer overflow in git diff If PATH_MAX on your system is smaller than a path stored, it may cause buffer overflow and stack corruption in diff_addremove() and diff_change() functions when running git-diff Signed-off-by: Dmitry Potapov <dpotapov@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void show_entry(struct diff_options *opt, const char *prefix, struct tree_desc *desc, const char *base, int baselen) { unsigned mode; const char *path; const unsigned char *sha1 = tree_entry_extract(desc, &path, &mode); if (DIFF_OPT_TST(opt, RECURSIVE) && S_ISDIR(mode)) { enum object_type type; int pathlen = tree_entry_len(path, sha1); char *newbase = malloc_base(base, baselen, path, pathlen); struct tree_desc inner; void *tree; unsigned long size; tree = read_sha1_file(sha1, &type, &size); if (!tree || type != OBJ_TREE) die("corrupt tree sha %s", sha1_to_hex(sha1)); init_tree_desc(&inner, tree, size); show_tree(opt, prefix, &inner, newbase, baselen + 1 + pathlen); free(tree); free(newbase); } else { opt->add_remove(opt, prefix[0], mode, sha1, base, path); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix buffer overflow in git diff If PATH_MAX on your system is smaller than a path stored, it may cause buffer overflow and stack corruption in diff_addremove() and diff_change() functions when running git-diff Signed-off-by: Dmitry Potapov <dpotapov@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void file_change(struct diff_options *options, unsigned old_mode, unsigned new_mode, const unsigned char *old_sha1, const unsigned char *new_sha1, const char *base, const char *path) { tree_difference = REV_TREE_DIFFERENT; DIFF_OPT_SET(options, HAS_CHANGES); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix buffer overflow in git diff If PATH_MAX on your system is smaller than a path stored, it may cause buffer overflow and stack corruption in diff_addremove() and diff_change() functions when running git-diff Signed-off-by: Dmitry Potapov <dpotapov@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int dccp_setsockopt_change(struct sock *sk, int type, struct dccp_so_feat __user *optval) { struct dccp_so_feat opt; u8 *val; int rc; if (copy_from_user(&opt, optval, sizeof(opt))) return -EFAULT; val = kmalloc(opt.dccpsf_len, GFP_KERNEL); if (!val) return -ENOMEM; if (copy_from_user(val, opt.dccpsf_val, opt.dccpsf_len)) { rc = -EFAULT; goto out_free_val; } rc = dccp_feat_change(dccp_msk(sk), type, opt.dccpsf_feat, val, opt.dccpsf_len, GFP_KERNEL); if (rc) goto out_free_val; out: return rc; out_free_val: kfree(val); goto out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'dccp: change L/R must have at least one byte in the dccpsf_val field Thanks to Eugene Teo for reporting this problem. Signed-off-by: Eugene Teo <eugenete@kernel.sg> Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Signed-off-by: Gerrit Renker <gerrit@erg.abdn.ac.uk> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct sctp_auth_bytes *sctp_auth_create_key(__u32 key_len, gfp_t gfp) { struct sctp_auth_bytes *key; /* Allocate the shared key */ key = kmalloc(sizeof(struct sctp_auth_bytes) + key_len, gfp); if (!key) return NULL; key->len = key_len; atomic_set(&key->refcnt, 1); SCTP_DBG_OBJCNT_INC(keys); return key; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'sctp: add verification checks to SCTP_AUTH_KEY option The structure used for SCTP_AUTH_KEY option contains a length that needs to be verfied to prevent buffer overflow conditions. Spoted by Eugene Teo <eteo@redhat.com>. Signed-off-by: Vlad Yasevich <vladislav.yasevich@hp.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int __init sysenter_setup(void) { syscall_page = (void *)get_zeroed_page(GFP_ATOMIC); #ifdef CONFIG_COMPAT_VDSO __set_fixmap(FIX_VDSO, __pa(syscall_page), PAGE_READONLY); printk("Compat vDSO mapped to %08lx.\n", __fix_to_virt(FIX_VDSO)); #endif if (!boot_cpu_has(X86_FEATURE_SEP)) { memcpy(syscall_page, &vsyscall_int80_start, &vsyscall_int80_end - &vsyscall_int80_start); return 0; } memcpy(syscall_page, &vsyscall_sysenter_start, &vsyscall_sysenter_end - &vsyscall_sysenter_start); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': '[PATCH] i386 vDSO: use install_special_mapping This patch uses install_special_mapping for the i386 vDSO setup, consolidating duplicated code. Signed-off-by: Roland McGrath <roland@redhat.com> Cc: Ingo Molnar <mingo@elte.hu> Cc: Paul Mackerras <paulus@samba.org> Cc: Benjamin Herrenschmidt <benh@kernel.crashing.org> Cc: Andi Kleen <ak@suse.de> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct page *syscall_nopage(struct vm_area_struct *vma, unsigned long adr, int *type) { struct page *p = virt_to_page(adr - vma->vm_start + syscall_page); get_page(p); return p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': '[PATCH] i386 vDSO: use install_special_mapping This patch uses install_special_mapping for the i386 vDSO setup, consolidating duplicated code. Signed-off-by: Roland McGrath <roland@redhat.com> Cc: Ingo Molnar <mingo@elte.hu> Cc: Paul Mackerras <paulus@samba.org> Cc: Benjamin Herrenschmidt <benh@kernel.crashing.org> Cc: Andi Kleen <ak@suse.de> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sbni_ioctl( struct net_device *dev, struct ifreq *ifr, int cmd ) { struct net_local *nl = (struct net_local *) dev->priv; struct sbni_flags flags; int error = 0; #ifdef CONFIG_SBNI_MULTILINE struct net_device *slave_dev; char slave_name[ 8 ]; #endif switch( cmd ) { case SIOCDEVGETINSTATS : if (copy_to_user( ifr->ifr_data, &nl->in_stats, sizeof(struct sbni_in_stats) )) error = -EFAULT; break; case SIOCDEVRESINSTATS : if( current->euid != 0 ) /* root only */ return -EPERM; memset( &nl->in_stats, 0, sizeof(struct sbni_in_stats) ); break; case SIOCDEVGHWSTATE : flags.mac_addr = *(u32 *)(dev->dev_addr + 3); flags.rate = nl->csr1.rate; flags.slow_mode = (nl->state & FL_SLOW_MODE) != 0; flags.rxl = nl->cur_rxl_index; flags.fixed_rxl = nl->delta_rxl == 0; if (copy_to_user( ifr->ifr_data, &flags, sizeof flags )) error = -EFAULT; break; case SIOCDEVSHWSTATE : if( current->euid != 0 ) /* root only */ return -EPERM; spin_lock( &nl->lock ); flags = *(struct sbni_flags*) &ifr->ifr_ifru; if( flags.fixed_rxl ) nl->delta_rxl = 0, nl->cur_rxl_index = flags.rxl; else nl->delta_rxl = DEF_RXL_DELTA, nl->cur_rxl_index = DEF_RXL; nl->csr1.rxl = rxl_tab[ nl->cur_rxl_index ]; nl->csr1.rate = flags.rate; outb( *(u8 *)&nl->csr1 | PR_RES, dev->base_addr + CSR1 ); spin_unlock( &nl->lock ); break; #ifdef CONFIG_SBNI_MULTILINE case SIOCDEVENSLAVE : if( current->euid != 0 ) /* root only */ return -EPERM; if (copy_from_user( slave_name, ifr->ifr_data, sizeof slave_name )) return -EFAULT; slave_dev = dev_get_by_name(&init_net, slave_name ); if( !slave_dev || !(slave_dev->flags & IFF_UP) ) { printk( KERN_ERR "%s: trying to enslave non-active " "device %s\n", dev->name, slave_name ); return -EPERM; } return enslave( dev, slave_dev ); case SIOCDEVEMANSIPATE : if( current->euid != 0 ) /* root only */ return -EPERM; return emancipate( dev ); #endif /* CONFIG_SBNI_MULTILINE */ default : return -EOPNOTSUPP; } return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'wan: Missing capability checks in sbni_ioctl() There are missing capability checks in the following code: 1300 static int 1301 sbni_ioctl( struct net_device *dev, struct ifreq *ifr, int cmd) 1302 { [...] 1319 case SIOCDEVRESINSTATS : 1320 if( current->euid != 0 ) /* root only */ 1321 return -EPERM; [...] 1336 case SIOCDEVSHWSTATE : 1337 if( current->euid != 0 ) /* root only */ 1338 return -EPERM; [...] 1357 case SIOCDEVENSLAVE : 1358 if( current->euid != 0 ) /* root only */ 1359 return -EPERM; [...] 1372 case SIOCDEVEMANSIPATE : 1373 if( current->euid != 0 ) /* root only */ 1374 return -EPERM; Here's my proposed fix: Missing capability checks. Signed-off-by: Eugene Teo <eugeneteo@kernel.sg> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt) { int n; int c; jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc; txtdesc->ascdata = 0; txtdesc->ucdata = 0; if (jas_iccgetuint32(in, &txtdesc->asclen)) goto error; if (!(txtdesc->ascdata = jas_malloc(txtdesc->asclen))) goto error; if (jas_stream_read(in, txtdesc->ascdata, txtdesc->asclen) != JAS_CAST(int, txtdesc->asclen)) goto error; txtdesc->ascdata[txtdesc->asclen - 1] = '\0'; if (jas_iccgetuint32(in, &txtdesc->uclangcode) || jas_iccgetuint32(in, &txtdesc->uclen)) goto error; if (!(txtdesc->ucdata = jas_malloc(txtdesc->uclen * 2))) goto error; if (jas_stream_read(in, txtdesc->ucdata, txtdesc->uclen * 2) != JAS_CAST(int, txtdesc->uclen * 2)) goto error; if (jas_iccgetuint16(in, &txtdesc->sccode)) goto error; if ((c = jas_stream_getc(in)) == EOF) goto error; txtdesc->maclen = c; if (jas_stream_read(in, txtdesc->macdata, 67) != 67) goto error; txtdesc->asclen = strlen(txtdesc->ascdata) + 1; #define WORKAROUND_BAD_PROFILES #ifdef WORKAROUND_BAD_PROFILES n = txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67; if (n > cnt) { return -1; } if (n < cnt) { if (jas_stream_gobble(in, cnt - n) != cnt - n) goto error; } #else if (txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67 != cnt) return -1; #endif return 0; error: jas_icctxtdesc_destroy(attrval); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jas_image_growcmpts(jas_image_t *image, int maxcmpts) { jas_image_cmpt_t **newcmpts; int cmptno; newcmpts = (!image->cmpts_) ? jas_malloc(maxcmpts * sizeof(jas_image_cmpt_t *)) : jas_realloc(image->cmpts_, maxcmpts * sizeof(jas_image_cmpt_t *)); if (!newcmpts) { return -1; } image->cmpts_ = newcmpts; image->maxcmpts_ = maxcmpts; for (cmptno = image->numcmpts_; cmptno < image->maxcmpts_; ++cmptno) { image->cmpts_[cmptno] = 0; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jp2_cmap_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cmap_t *cmap = &box->data.cmap; jp2_cmapent_t *ent; unsigned int i; cmap->numchans = (box->datalen) / 4; if (!(cmap->ents = jas_malloc(cmap->numchans * sizeof(jp2_cmapent_t)))) { return -1; } for (i = 0; i < cmap->numchans; ++i) { ent = &cmap->ents[i]; if (jp2_getuint16(in, &ent->cmptno) || jp2_getuint8(in, &ent->map) || jp2_getuint8(in, &ent->pcol)) { return -1; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bmp_info_t *bmp_getinfo(jas_stream_t *in) { bmp_info_t *info; int i; bmp_palent_t *palent; if (!(info = bmp_info_create())) { return 0; } if (bmp_getint32(in, &info->len) || info->len != 40 || bmp_getint32(in, &info->width) || bmp_getint32(in, &info->height) || bmp_getint16(in, &info->numplanes) || bmp_getint16(in, &info->depth) || bmp_getint32(in, &info->enctype) || bmp_getint32(in, &info->siz) || bmp_getint32(in, &info->hres) || bmp_getint32(in, &info->vres) || bmp_getint32(in, &info->numcolors) || bmp_getint32(in, &info->mincolors)) { bmp_info_destroy(info); return 0; } if (info->height < 0) { info->topdown = 1; info->height = -info->height; } else { info->topdown = 0; } if (info->width <= 0 || info->height <= 0 || info->numplanes <= 0 || info->depth <= 0 || info->numcolors < 0 || info->mincolors < 0) { bmp_info_destroy(info); return 0; } if (info->enctype != BMP_ENC_RGB) { jas_eprintf("unsupported BMP encoding\n"); bmp_info_destroy(info); return 0; } if (info->numcolors > 0) { if (!(info->palents = jas_malloc(info->numcolors * sizeof(bmp_palent_t)))) { bmp_info_destroy(info); return 0; } } else { info->palents = 0; } for (i = 0; i < info->numcolors; ++i) { palent = &info->palents[i]; if ((palent->blu = jas_stream_getc(in)) == EOF || (palent->grn = jas_stream_getc(in)) == EOF || (palent->red = jas_stream_getc(in)) == EOF || (palent->res = jas_stream_getc(in)) == EOF) { bmp_info_destroy(info); return 0; } } return info; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt) { int i; int j; int clutsize; jas_icclut8_t *lut8 = &attrval->data.lut8; lut8->clut = 0; lut8->intabs = 0; lut8->intabsbuf = 0; lut8->outtabs = 0; lut8->outtabsbuf = 0; if (jas_iccgetuint8(in, &lut8->numinchans) || jas_iccgetuint8(in, &lut8->numoutchans) || jas_iccgetuint8(in, &lut8->clutlen) || jas_stream_getc(in) == EOF) goto error; for (i = 0; i < 3; ++i) { for (j = 0; j < 3; ++j) { if (jas_iccgetsint32(in, &lut8->e[i][j])) goto error; } } if (jas_iccgetuint16(in, &lut8->numintabents) || jas_iccgetuint16(in, &lut8->numouttabents)) goto error; clutsize = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans; if (!(lut8->clut = jas_malloc(clutsize * sizeof(jas_iccuint8_t))) || !(lut8->intabsbuf = jas_malloc(lut8->numinchans * lut8->numintabents * sizeof(jas_iccuint8_t))) || !(lut8->intabs = jas_malloc(lut8->numinchans * sizeof(jas_iccuint8_t *)))) goto error; for (i = 0; i < lut8->numinchans; ++i) lut8->intabs[i] = &lut8->intabsbuf[i * lut8->numintabents]; if (!(lut8->outtabsbuf = jas_malloc(lut8->numoutchans * lut8->numouttabents * sizeof(jas_iccuint8_t))) || !(lut8->outtabs = jas_malloc(lut8->numoutchans * sizeof(jas_iccuint8_t *)))) goto error; for (i = 0; i < lut8->numoutchans; ++i) lut8->outtabs[i] = &lut8->outtabsbuf[i * lut8->numouttabents]; for (i = 0; i < lut8->numinchans; ++i) { for (j = 0; j < JAS_CAST(int, lut8->numintabents); ++j) { if (jas_iccgetuint8(in, &lut8->intabs[i][j])) goto error; } } for (i = 0; i < lut8->numoutchans; ++i) { for (j = 0; j < JAS_CAST(int, lut8->numouttabents); ++j) { if (jas_iccgetuint8(in, &lut8->outtabs[i][j])) goto error; } } for (i = 0; i < clutsize; ++i) { if (jas_iccgetuint8(in, &lut8->clut[i])) goto error; } if (JAS_CAST(int, 44 + lut8->numinchans * lut8->numintabents + lut8->numoutchans * lut8->numouttabents + jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans) != cnt) goto error; return 0; error: jas_icclut8_destroy(attrval); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int jas_iccprof_save(jas_iccprof_t *prof, jas_stream_t *out) { long curoff; long reloff; long newoff; int i; int j; jas_icctagtabent_t *tagtabent; jas_icctagtabent_t *sharedtagtabent; jas_icctagtabent_t *tmptagtabent; jas_iccuint32_t attrname; jas_iccattrval_t *attrval; jas_icctagtab_t *tagtab; tagtab = &prof->tagtab; if (!(tagtab->ents = jas_malloc(prof->attrtab->numattrs * sizeof(jas_icctagtabent_t)))) goto error; tagtab->numents = prof->attrtab->numattrs; curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents; for (i = 0; i < JAS_CAST(int, tagtab->numents); ++i) { tagtabent = &tagtab->ents[i]; if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval)) goto error; assert(attrval->ops->output); tagtabent->tag = attrname; tagtabent->data = &attrval->data; sharedtagtabent = 0; for (j = 0; j < i; ++j) { tmptagtabent = &tagtab->ents[j]; if (tagtabent->data == tmptagtabent->data) { sharedtagtabent = tmptagtabent; break; } } if (sharedtagtabent) { tagtabent->off = sharedtagtabent->off; tagtabent->len = sharedtagtabent->len; tagtabent->first = sharedtagtabent; } else { tagtabent->off = curoff; tagtabent->len = (*attrval->ops->getsize)(attrval) + 8; tagtabent->first = 0; if (i < JAS_CAST(int, tagtab->numents - 1)) { curoff = jas_iccpadtomult(curoff + tagtabent->len, 4); } else { curoff += tagtabent->len; } } jas_iccattrval_destroy(attrval); } prof->hdr.size = curoff; if (jas_iccprof_writehdr(out, &prof->hdr)) goto error; if (jas_iccprof_puttagtab(out, &prof->tagtab)) goto error; curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents; for (i = 0; i < JAS_CAST(int, tagtab->numents);) { tagtabent = &tagtab->ents[i]; assert(curoff == JAS_CAST(long, tagtabent->off)); if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval)) goto error; if (jas_iccputuint32(out, attrval->type) || jas_stream_pad(out, 4, 0) != 4) goto error; if ((*attrval->ops->output)(attrval, out)) goto error; jas_iccattrval_destroy(attrval); curoff += tagtabent->len; ++i; while (i < JAS_CAST(int, tagtab->numents) && tagtab->ents[i].first) ++i; newoff = (i < JAS_CAST(int, tagtab->numents)) ? tagtab->ents[i].off : prof->hdr.size; reloff = newoff - curoff; assert(reloff >= 0); if (reloff > 0) { if (jas_stream_pad(out, reloff, 0) != reloff) goto error; curoff += reloff; } } return 0; error: /* XXX - need to free some resources here */ return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jas_cmshapmatlut_set(jas_cmshapmatlut_t *lut, jas_icccurv_t *curv) { jas_cmreal_t gamma; int i; gamma = 0; jas_cmshapmatlut_cleanup(lut); if (curv->numents == 0) { lut->size = 2; if (!(lut->data = jas_malloc(lut->size * sizeof(jas_cmreal_t)))) goto error; lut->data[0] = 0.0; lut->data[1] = 1.0; } else if (curv->numents == 1) { lut->size = 256; if (!(lut->data = jas_malloc(lut->size * sizeof(jas_cmreal_t)))) goto error; gamma = curv->ents[0] / 256.0; for (i = 0; i < lut->size; ++i) { lut->data[i] = gammafn(i / (double) (lut->size - 1), gamma); } } else { lut->size = curv->numents; if (!(lut->data = jas_malloc(lut->size * sizeof(jas_cmreal_t)))) goto error; for (i = 0; i < lut->size; ++i) { lut->data[i] = curv->ents[i] / 65535.0; } } return 0; error: return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jp2_colr_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_colr_t *colr = &box->data.colr; colr->csid = 0; colr->iccp = 0; colr->iccplen = 0; if (jp2_getuint8(in, &colr->method) || jp2_getuint8(in, &colr->pri) || jp2_getuint8(in, &colr->approx)) { return -1; } switch (colr->method) { case JP2_COLR_ENUM: if (jp2_getuint32(in, &colr->csid)) { return -1; } break; case JP2_COLR_ICC: colr->iccplen = box->datalen - 3; if (!(colr->iccp = jas_malloc(colr->iccplen * sizeof(uint_fast8_t)))) { return -1; } if (jas_stream_read(in, colr->iccp, colr->iccplen) != colr->iccplen) { return -1; } break; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp, jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos) { uint_fast16_t rlvlno; uint_fast32_t tlprctlx; uint_fast32_t tlprctly; uint_fast32_t brprcbrx; uint_fast32_t brprcbry; uint_fast16_t bandno; jpc_enc_band_t *band; /* Deduce the resolution level. */ rlvlno = rlvl - tcmpt->rlvls; /* Initialize members required for error recovery. */ rlvl->bands = 0; rlvl->tcmpt = tcmpt; /* Compute the coordinates of the top-left and bottom-right corners of the tile-component at this resolution. */ rlvl->tlx = JPC_CEILDIVPOW2(jas_seq2d_xstart(tcmpt->data), tcmpt->numrlvls - 1 - rlvlno); rlvl->tly = JPC_CEILDIVPOW2(jas_seq2d_ystart(tcmpt->data), tcmpt->numrlvls - 1 - rlvlno); rlvl->brx = JPC_CEILDIVPOW2(jas_seq2d_xend(tcmpt->data), tcmpt->numrlvls - 1 - rlvlno); rlvl->bry = JPC_CEILDIVPOW2(jas_seq2d_yend(tcmpt->data), tcmpt->numrlvls - 1 - rlvlno); if (rlvl->tlx >= rlvl->brx || rlvl->tly >= rlvl->bry) { rlvl->numhprcs = 0; rlvl->numvprcs = 0; rlvl->numprcs = 0; return rlvl; } rlvl->numbands = (!rlvlno) ? 1 : 3; rlvl->prcwidthexpn = cp->tccp.prcwidthexpns[rlvlno]; rlvl->prcheightexpn = cp->tccp.prcheightexpns[rlvlno]; if (!rlvlno) { rlvl->cbgwidthexpn = rlvl->prcwidthexpn; rlvl->cbgheightexpn = rlvl->prcheightexpn; } else { rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; } rlvl->cblkwidthexpn = JAS_MIN(cp->tccp.cblkwidthexpn, rlvl->cbgwidthexpn); rlvl->cblkheightexpn = JAS_MIN(cp->tccp.cblkheightexpn, rlvl->cbgheightexpn); /* Compute the number of precincts. */ tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn); tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn); brprcbrx = JPC_CEILTOMULTPOW2(rlvl->brx, rlvl->prcwidthexpn); brprcbry = JPC_CEILTOMULTPOW2(rlvl->bry, rlvl->prcheightexpn); rlvl->numhprcs = JPC_FLOORDIVPOW2(brprcbrx - tlprctlx, rlvl->prcwidthexpn); rlvl->numvprcs = JPC_FLOORDIVPOW2(brprcbry - tlprctly, rlvl->prcheightexpn); rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; if (!(rlvl->bands = jas_malloc(rlvl->numbands * sizeof(jpc_enc_band_t)))) { goto error; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { band->prcs = 0; band->data = 0; band->rlvl = rlvl; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { if (!band_create(band, cp, rlvl, bandinfos)) { goto error; } } return rlvl; error: rlvl_destroy(rlvl); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jpc_pi_t *jpc_enc_pi_create(jpc_enc_cp_t *cp, jpc_enc_tile_t *tile) { jpc_pi_t *pi; int compno; jpc_picomp_t *picomp; jpc_pirlvl_t *pirlvl; jpc_enc_tcmpt_t *tcomp; int rlvlno; jpc_enc_rlvl_t *rlvl; int prcno; int *prclyrno; if (!(pi = jpc_pi_create0())) { return 0; } pi->pktno = -1; pi->numcomps = cp->numcmpts; if (!(pi->picomps = jas_malloc(pi->numcomps * sizeof(jpc_picomp_t)))) { jpc_pi_destroy(pi); return 0; } for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { picomp->pirlvls = 0; } for (compno = 0, tcomp = tile->tcmpts, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++tcomp, ++picomp) { picomp->numrlvls = tcomp->numrlvls; if (!(picomp->pirlvls = jas_malloc(picomp->numrlvls * sizeof(jpc_pirlvl_t)))) { jpc_pi_destroy(pi); return 0; } for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { pirlvl->prclyrnos = 0; } for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) { /* XXX sizeof(long) should be sizeof different type */ pirlvl->numprcs = rlvl->numprcs; if (rlvl->numprcs) { if (!(pirlvl->prclyrnos = jas_malloc(pirlvl->numprcs * sizeof(long)))) { jpc_pi_destroy(pi); return 0; } } else { pirlvl->prclyrnos = 0; } } } pi->maxrlvls = 0; for (compno = 0, tcomp = tile->tcmpts, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++tcomp, ++picomp) { picomp->hsamp = cp->ccps[compno].sampgrdstepx; picomp->vsamp = cp->ccps[compno].sampgrdstepy; for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) { pirlvl->prcwidthexpn = rlvl->prcwidthexpn; pirlvl->prcheightexpn = rlvl->prcheightexpn; for (prcno = 0, prclyrno = pirlvl->prclyrnos; prcno < pirlvl->numprcs; ++prcno, ++prclyrno) { *prclyrno = 0; } pirlvl->numhprcs = rlvl->numhprcs; } if (pi->maxrlvls < tcomp->numrlvls) { pi->maxrlvls = tcomp->numrlvls; } } pi->numlyrs = tile->numlyrs; pi->xstart = tile->tlx; pi->ystart = tile->tly; pi->xend = tile->brx; pi->yend = tile->bry; pi->picomp = 0; pi->pirlvl = 0; pi->x = 0; pi->y = 0; pi->compno = 0; pi->rlvlno = 0; pi->prcno = 0; pi->lyrno = 0; pi->xstep = 0; pi->ystep = 0; pi->pchgno = -1; pi->defaultpchg.prgord = tile->prg; pi->defaultpchg.compnostart = 0; pi->defaultpchg.compnoend = pi->numcomps; pi->defaultpchg.rlvlnostart = 0; pi->defaultpchg.rlvlnoend = pi->maxrlvls; pi->defaultpchg.lyrnoend = pi->numlyrs; pi->pchg = 0; pi->valid = 0; return pi; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void jpc_qmfb_join_colres(jpc_fix_t *a, int numrows, int numcols, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = joinbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int hstartcol; /* Allocate memory for the join buffer from the heap. */ if (bufsize > QMFB_JOINBUFSIZE) { if (!(buf = jas_malloc(bufsize * numcols * sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide. */ abort(); } } hstartcol = (numrows + 1 - parity) >> 1; /* Save the samples from the lowpass channel. */ n = hstartcol; srcptr = &a[0]; dstptr = buf; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < numcols; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } srcptr += stride; dstptr += numcols; } /* Copy the samples from the highpass channel into place. */ srcptr = &a[hstartcol * stride]; dstptr = &a[(1 - parity) * stride]; n = numrows - hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < numcols; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += stride; } /* Copy the samples from the lowpass channel into place. */ srcptr = buf; dstptr = &a[parity * stride]; n = hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < numcols; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += numcols; } /* If the join buffer was allocated on the heap, free this memory. */ if (buf != joinbuf) { jas_free(buf); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in, int cnt) { jas_icccurv_t *curv = &attrval->data.curv; unsigned int i; curv->numents = 0; curv->ents = 0; if (jas_iccgetuint32(in, &curv->numents)) goto error; if (!(curv->ents = jas_malloc(curv->numents * sizeof(jas_iccuint16_t)))) goto error; for (i = 0; i < curv->numents; ++i) { if (jas_iccgetuint16(in, &curv->ents[i])) goto error; } if (JAS_CAST(int, 4 + 2 * curv->numents) != cnt) goto error; return 0; error: jas_icccurv_destroy(attrval); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate, jas_stream_t *in, uint_fast16_t len) { uint_fast8_t tmp; int n; int i; /* Eliminate compiler warning about unused variables. */ cstate = 0; n = 0; if (jpc_getuint8(in, &tmp)) { return -1; } ++n; compparms->qntsty = tmp & 0x1f; compparms->numguard = (tmp >> 5) & 7; switch (compparms->qntsty) { case JPC_QCX_SIQNT: compparms->numstepsizes = 1; break; case JPC_QCX_NOQNT: compparms->numstepsizes = (len - n); break; case JPC_QCX_SEQNT: /* XXX - this is a hack */ compparms->numstepsizes = (len - n) / 2; break; } if (compparms->numstepsizes > 0) { compparms->stepsizes = jas_malloc(compparms->numstepsizes * sizeof(uint_fast16_t)); assert(compparms->stepsizes); for (i = 0; i < compparms->numstepsizes; ++i) { if (compparms->qntsty == JPC_QCX_NOQNT) { if (jpc_getuint8(in, &tmp)) { return -1; } compparms->stepsizes[i] = JPC_QCX_EXPN(tmp >> 3); } else { if (jpc_getuint16(in, &compparms->stepsizes[i])) { return -1; } } } } else { compparms->stepsizes = 0; } if (jas_stream_error(in) || jas_stream_eof(in)) { jpc_qcx_destroycompparms(compparms); return -1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0, int c0, int r1, int c1) { int i; if (mat0->data_) { if (!(mat0->flags_ & JAS_MATRIX_REF)) { jas_free(mat0->data_); } mat0->data_ = 0; mat0->datasize_ = 0; } if (mat0->rows_) { jas_free(mat0->rows_); mat0->rows_ = 0; } mat0->flags_ |= JAS_MATRIX_REF; mat0->numrows_ = r1 - r0 + 1; mat0->numcols_ = c1 - c0 + 1; mat0->maxrows_ = mat0->numrows_; mat0->rows_ = jas_malloc(mat0->maxrows_ * sizeof(jas_seqent_t *)); for (i = 0; i < mat0->numrows_; ++i) { mat0->rows_[i] = mat1->rows_[r0 + i] + c0; } mat0->xstart_ = mat1->xstart_ + c0; mat0->ystart_ = mat1->ystart_ + r0; mat0->xend_ = mat0->xstart_ + mat0->numcols_; mat0->yend_ = mat0->ystart_ + mat0->numrows_; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_ppt_t *ppt = &ms->parms.ppt; /* Eliminate compiler warning about unused variables. */ cstate = 0; ppt->data = 0; if (ms->len < 1) { goto error; } if (jpc_getuint8(in, &ppt->ind)) { goto error; } ppt->len = ms->len - 1; if (ppt->len > 0) { if (!(ppt->data = jas_malloc(ppt->len * sizeof(unsigned char)))) { goto error; } if (jas_stream_read(in, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) { goto error; } } else { ppt->data = 0; } return 0; error: jpc_ppt_destroyparms(ms); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_ppm_t *ppm = &ms->parms.ppm; /* Eliminate compiler warning about unused variables. */ cstate = 0; ppm->data = 0; if (ms->len < 1) { goto error; } if (jpc_getuint8(in, &ppm->ind)) { goto error; } ppm->len = ms->len - 1; if (ppm->len > 0) { if (!(ppm->data = jas_malloc(ppm->len * sizeof(unsigned char)))) { goto error; } if (JAS_CAST(uint, jas_stream_read(in, ppm->data, ppm->len)) != ppm->len) { goto error; } } else { ppm->data = 0; } return 0; error: jpc_ppm_destroyparms(ms); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jpc_streamlist_t *jpc_streamlist_create() { jpc_streamlist_t *streamlist; int i; if (!(streamlist = jas_malloc(sizeof(jpc_streamlist_t)))) { return 0; } streamlist->numstreams = 0; streamlist->maxstreams = 100; if (!(streamlist->streams = jas_malloc(streamlist->maxstreams * sizeof(jas_stream_t *)))) { jas_free(streamlist); return 0; } for (i = 0; i < streamlist->maxstreams; ++i) { streamlist->streams[i] = 0; } return streamlist; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jas_image_t *jp2_decode(jas_stream_t *in, char *optstr) { jp2_box_t *box; int found; jas_image_t *image; jp2_dec_t *dec; bool samedtype; int dtype; unsigned int i; jp2_cmap_t *cmapd; jp2_pclr_t *pclrd; jp2_cdef_t *cdefd; unsigned int channo; int newcmptno; int_fast32_t *lutents; #if 0 jp2_cdefchan_t *cdefent; int cmptno; #endif jp2_cmapent_t *cmapent; jas_icchdr_t icchdr; jas_iccprof_t *iccprof; dec = 0; box = 0; image = 0; if (!(dec = jp2_dec_create())) { goto error; } /* Get the first box. This should be a JP box. */ if (!(box = jp2_box_get(in))) { jas_eprintf("error: cannot get box\n"); goto error; } if (box->type != JP2_BOX_JP) { jas_eprintf("error: expecting signature box\n"); goto error; } if (box->data.jp.magic != JP2_JP_MAGIC) { jas_eprintf("incorrect magic number\n"); goto error; } jp2_box_destroy(box); box = 0; /* Get the second box. This should be a FTYP box. */ if (!(box = jp2_box_get(in))) { goto error; } if (box->type != JP2_BOX_FTYP) { jas_eprintf("expecting file type box\n"); goto error; } jp2_box_destroy(box); box = 0; /* Get more boxes... */ found = 0; while ((box = jp2_box_get(in))) { if (jas_getdbglevel() >= 1) { jas_eprintf("box type %s\n", box->info->name); } switch (box->type) { case JP2_BOX_JP2C: found = 1; break; case JP2_BOX_IHDR: if (!dec->ihdr) { dec->ihdr = box; box = 0; } break; case JP2_BOX_BPCC: if (!dec->bpcc) { dec->bpcc = box; box = 0; } break; case JP2_BOX_CDEF: if (!dec->cdef) { dec->cdef = box; box = 0; } break; case JP2_BOX_PCLR: if (!dec->pclr) { dec->pclr = box; box = 0; } break; case JP2_BOX_CMAP: if (!dec->cmap) { dec->cmap = box; box = 0; } break; case JP2_BOX_COLR: if (!dec->colr) { dec->colr = box; box = 0; } break; } if (box) { jp2_box_destroy(box); box = 0; } if (found) { break; } } if (!found) { jas_eprintf("error: no code stream found\n"); goto error; } if (!(dec->image = jpc_decode(in, optstr))) { jas_eprintf("error: cannot decode code stream\n"); goto error; } /* An IHDR box must be present. */ if (!dec->ihdr) { jas_eprintf("error: missing IHDR box\n"); goto error; } /* Does the number of components indicated in the IHDR box match the value specified in the code stream? */ if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(uint, jas_image_numcmpts(dec->image))) { jas_eprintf("warning: number of components mismatch\n"); } /* At least one component must be present. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf("error: no components\n"); goto error; } /* Determine if all components have the same data type. */ samedtype = true; dtype = jas_image_cmptdtype(dec->image, 0); for (i = 1; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != dtype) { samedtype = false; break; } } /* Is the component data type indicated in the IHDR box consistent with the data in the code stream? */ if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) || (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) { jas_eprintf("warning: component data type mismatch\n"); } /* Is the compression type supported? */ if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) { jas_eprintf("error: unsupported compression type\n"); goto error; } if (dec->bpcc) { /* Is the number of components indicated in the BPCC box consistent with the code stream data? */ if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(uint, jas_image_numcmpts( dec->image))) { jas_eprintf("warning: number of components mismatch\n"); } /* Is the component data type information indicated in the BPCC box consistent with the code stream data? */ if (!samedtype) { for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) { if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) { jas_eprintf("warning: component data type mismatch\n"); } } } else { jas_eprintf("warning: superfluous BPCC box\n"); } } /* A COLR box must be present. */ if (!dec->colr) { jas_eprintf("error: no COLR box\n"); goto error; } switch (dec->colr->data.colr.method) { case JP2_COLR_ENUM: jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr)); break; case JP2_COLR_ICC: iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp, dec->colr->data.colr.iccplen); if (!iccprof) { jas_eprintf("error: failed to parse ICC profile\n"); goto error; } jas_iccprof_gethdr(iccprof, &icchdr); jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc); jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc)); dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof); assert(dec->image->cmprof_); jas_iccprof_destroy(iccprof); break; } /* If a CMAP box is present, a PCLR box must also be present. */ if (dec->cmap && !dec->pclr) { jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n"); jp2_box_destroy(dec->cmap); dec->cmap = 0; } /* If a CMAP box is not present, a PCLR box must not be present. */ if (!dec->cmap && dec->pclr) { jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n"); jp2_box_destroy(dec->pclr); dec->pclr = 0; } /* Determine the number of channels (which is essentially the number of components after any palette mappings have been applied). */ dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(uint, jas_image_numcmpts(dec->image)); /* Perform a basic sanity check on the CMAP box if present. */ if (dec->cmap) { for (i = 0; i < dec->numchans; ++i) { /* Is the component number reasonable? */ if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(uint, jas_image_numcmpts(dec->image))) { jas_eprintf("error: invalid component number in CMAP box\n"); goto error; } /* Is the LUT index reasonable? */ if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) { jas_eprintf("error: invalid CMAP LUT index\n"); goto error; } } } /* Allocate space for the channel-number to component-number LUT. */ if (!(dec->chantocmptlut = jas_malloc(dec->numchans * sizeof(uint_fast16_t)))) { jas_eprintf("error: no memory\n"); goto error; } if (!dec->cmap) { for (i = 0; i < dec->numchans; ++i) { dec->chantocmptlut[i] = i; } } else { cmapd = &dec->cmap->data.cmap; pclrd = &dec->pclr->data.pclr; cdefd = &dec->cdef->data.cdef; for (channo = 0; channo < cmapd->numchans; ++channo) { cmapent = &cmapd->ents[channo]; if (cmapent->map == JP2_CMAP_DIRECT) { dec->chantocmptlut[channo] = channo; } else if (cmapent->map == JP2_CMAP_PALETTE) { lutents = jas_malloc(pclrd->numlutents * sizeof(int_fast32_t)); for (i = 0; i < pclrd->numlutents; ++i) { lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans]; } newcmptno = jas_image_numcmpts(dec->image); jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno); dec->chantocmptlut[channo] = newcmptno; jas_free(lutents); #if 0 if (dec->cdef) { cdefent = jp2_cdef_lookup(cdefd, channo); if (!cdefent) { abort(); } jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc)); } else { jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1)); } #endif } } } /* Mark all components as being of unknown type. */ for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) { jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN); } /* Determine the type of each component. */ if (dec->cdef) { for (i = 0; i < dec->numchans; ++i) { /* Is the channel number reasonable? */ if (dec->cdef->data.cdef.ents[i].channo >= dec->numchans) { jas_eprintf("error: invalid channel number in CDEF box\n"); goto error; } jas_image_setcmpttype(dec->image, dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo], jp2_getct(jas_image_clrspc(dec->image), dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc)); } } else { for (i = 0; i < dec->numchans; ++i) { jas_image_setcmpttype(dec->image, dec->chantocmptlut[i], jp2_getct(jas_image_clrspc(dec->image), 0, i + 1)); } } /* Delete any components that are not of interest. */ for (i = jas_image_numcmpts(dec->image); i > 0; --i) { if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) { jas_image_delcmpt(dec->image, i - 1); } } /* Ensure that some components survived. */ if (!jas_image_numcmpts(dec->image)) { jas_eprintf("error: no components\n"); goto error; } #if 0 jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image)); #endif /* Prevent the image from being destroyed later. */ image = dec->image; dec->image = 0; jp2_dec_destroy(dec); return image; error: if (box) { jp2_box_destroy(box); } if (dec) { jp2_dec_destroy(dec); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_crg_t *crg = &ms->parms.crg; jpc_crgcomp_t *comp; uint_fast16_t compno; crg->numcomps = cstate->numcomps; if (!(crg->comps = jas_malloc(cstate->numcomps * sizeof(uint_fast16_t)))) { return -1; } for (compno = 0, comp = crg->comps; compno < cstate->numcomps; ++compno, ++comp) { if (jpc_getuint16(in, &comp->hoff) || jpc_getuint16(in, &comp->voff)) { jpc_crg_destroyparms(ms); return -1; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void jpc_qmfb_join_row(jpc_fix_t *a, int numcols, int parity) { int bufsize = JPC_CEILDIVPOW2(numcols, 1); jpc_fix_t joinbuf[QMFB_JOINBUFSIZE]; jpc_fix_t *buf = joinbuf; register jpc_fix_t *srcptr; register jpc_fix_t *dstptr; register int n; int hstartcol; /* Allocate memory for the join buffer from the heap. */ if (bufsize > QMFB_JOINBUFSIZE) { if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide. */ abort(); } } hstartcol = (numcols + 1 - parity) >> 1; /* Save the samples from the lowpass channel. */ n = hstartcol; srcptr = &a[0]; dstptr = buf; while (n-- > 0) { *dstptr = *srcptr; ++srcptr; ++dstptr; } /* Copy the samples from the highpass channel into place. */ srcptr = &a[hstartcol]; dstptr = &a[1 - parity]; n = numcols - hstartcol; while (n-- > 0) { *dstptr = *srcptr; dstptr += 2; ++srcptr; } /* Copy the samples from the lowpass channel into place. */ srcptr = buf; dstptr = &a[parity]; n = hstartcol; while (n-- > 0) { *dstptr = *srcptr; dstptr += 2; ++srcptr; } /* If the join buffer was allocated on the heap, free this memory. */ if (buf != joinbuf) { jas_free(buf); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno) { jpc_enc_tile_t *tile; uint_fast32_t htileno; uint_fast32_t vtileno; uint_fast16_t lyrno; uint_fast16_t cmptno; jpc_enc_tcmpt_t *tcmpt; if (!(tile = jas_malloc(sizeof(jpc_enc_tile_t)))) { goto error; } /* Initialize a few members used in error recovery. */ tile->tcmpts = 0; tile->lyrsizes = 0; tile->numtcmpts = cp->numcmpts; tile->pi = 0; tile->tileno = tileno; htileno = tileno % cp->numhtiles; vtileno = tileno / cp->numhtiles; /* Calculate the coordinates of the top-left and bottom-right corners of the tile. */ tile->tlx = JAS_MAX(cp->tilegrdoffx + htileno * cp->tilewidth, cp->imgareatlx); tile->tly = JAS_MAX(cp->tilegrdoffy + vtileno * cp->tileheight, cp->imgareatly); tile->brx = JAS_MIN(cp->tilegrdoffx + (htileno + 1) * cp->tilewidth, cp->refgrdwidth); tile->bry = JAS_MIN(cp->tilegrdoffy + (vtileno + 1) * cp->tileheight, cp->refgrdheight); /* Initialize some tile coding parameters. */ tile->intmode = cp->tcp.intmode; tile->csty = cp->tcp.csty; tile->prg = cp->tcp.prg; tile->mctid = cp->tcp.mctid; tile->numlyrs = cp->tcp.numlyrs; if (!(tile->lyrsizes = jas_malloc(tile->numlyrs * sizeof(uint_fast32_t)))) { goto error; } for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) { tile->lyrsizes[lyrno] = 0; } /* Allocate an array for the per-tile-component information. */ if (!(tile->tcmpts = jas_malloc(cp->numcmpts * sizeof(jpc_enc_tcmpt_t)))) { goto error; } /* Initialize a few members critical for error recovery. */ for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts; ++cmptno, ++tcmpt) { tcmpt->rlvls = 0; tcmpt->tsfb = 0; tcmpt->data = 0; } /* Initialize the per-tile-component information. */ for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts; ++cmptno, ++tcmpt) { if (!tcmpt_create(tcmpt, cp, image, tile)) { goto error; } } /* Initialize the synthesis weights for the MCT. */ switch (tile->mctid) { case JPC_MCT_RCT: tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0)); tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(0.6875)); tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(0.6875)); break; case JPC_MCT_ICT: tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0000)); tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(3.2584)); tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(2.4755)); break; default: case JPC_MCT_NONE: for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts; ++cmptno, ++tcmpt) { tcmpt->synweight = JPC_FIX_ONE; } break; } if (!(tile->pi = jpc_enc_pi_create(cp, tile))) { goto error; } return tile; error: if (tile) { jpc_enc_tile_destroy(tile); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static jpc_dec_cp_t *jpc_dec_cp_create(uint_fast16_t numcomps) { jpc_dec_cp_t *cp; jpc_dec_ccp_t *ccp; int compno; if (!(cp = jas_malloc(sizeof(jpc_dec_cp_t)))) { return 0; } cp->flags = 0; cp->numcomps = numcomps; cp->prgord = 0; cp->numlyrs = 0; cp->mctid = 0; cp->csty = 0; if (!(cp->ccps = jas_malloc(cp->numcomps * sizeof(jpc_dec_ccp_t)))) { return 0; } if (!(cp->pchglist = jpc_pchglist_create())) { jas_free(cp->ccps); return 0; } for (compno = 0, ccp = cp->ccps; compno < cp->numcomps; ++compno, ++ccp) { ccp->flags = 0; ccp->numrlvls = 0; ccp->cblkwidthexpn = 0; ccp->cblkheightexpn = 0; ccp->qmfbid = 0; ccp->numstepsizes = 0; ccp->numguardbits = 0; ccp->roishift = 0; ccp->cblkctx = 0; } return cp; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_unk_t *unk = &ms->parms.unk; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (ms->len > 0) { if (!(unk->data = jas_malloc(ms->len * sizeof(unsigned char)))) { return -1; } if (jas_stream_read(in, (char *) unk->data, ms->len) != JAS_CAST(int, ms->len)) { jas_free(unk->data); return -1; } unk->len = ms->len; } else { unk->data = 0; unk->len = 0; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image) { jpc_enc_cp_t *cp; jas_tvparser_t *tvp; int ret; int numilyrrates; double *ilyrrates; int i; int tagid; jpc_enc_tcp_t *tcp; jpc_enc_tccp_t *tccp; jpc_enc_ccp_t *ccp; int cmptno; uint_fast16_t rlvlno; uint_fast16_t prcwidthexpn; uint_fast16_t prcheightexpn; bool enablemct; uint_fast32_t jp2overhead; uint_fast16_t lyrno; uint_fast32_t hsteplcm; uint_fast32_t vsteplcm; bool mctvalid; tvp = 0; cp = 0; ilyrrates = 0; numilyrrates = 0; if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) { goto error; } prcwidthexpn = 15; prcheightexpn = 15; enablemct = true; jp2overhead = 0; cp->ccps = 0; cp->debug = 0; cp->imgareatlx = UINT_FAST32_MAX; cp->imgareatly = UINT_FAST32_MAX; cp->refgrdwidth = 0; cp->refgrdheight = 0; cp->tilegrdoffx = UINT_FAST32_MAX; cp->tilegrdoffy = UINT_FAST32_MAX; cp->tilewidth = 0; cp->tileheight = 0; cp->numcmpts = jas_image_numcmpts(image); hsteplcm = 1; vsteplcm = 1; for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <= jas_image_brx(image) || jas_image_cmptbry(image, cmptno) + jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) { jas_eprintf("unsupported image type\n"); goto error; } /* Note: We ought to be calculating the LCMs here. Fix some day. */ hsteplcm *= jas_image_cmpthstep(image, cmptno); vsteplcm *= jas_image_cmptvstep(image, cmptno); } if (!(cp->ccps = jas_malloc(cp->numcmpts * sizeof(jpc_enc_ccp_t)))) { goto error; } for (cmptno = 0, ccp = cp->ccps; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno, ++ccp) { ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno); ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno); /* XXX - this isn't quite correct for more general image */ ccp->sampgrdsubstepx = 0; ccp->sampgrdsubstepx = 0; ccp->prec = jas_image_cmptprec(image, cmptno); ccp->sgnd = jas_image_cmptsgnd(image, cmptno); ccp->numstepsizes = 0; memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes)); } cp->rawsize = jas_image_rawsize(image); cp->totalsize = UINT_FAST32_MAX; tcp = &cp->tcp; tcp->csty = 0; tcp->intmode = true; tcp->prg = JPC_COD_LRCPPRG; tcp->numlyrs = 1; tcp->ilyrrates = 0; tccp = &cp->tccp; tccp->csty = 0; tccp->maxrlvls = 6; tccp->cblkwidthexpn = 6; tccp->cblkheightexpn = 6; tccp->cblksty = 0; tccp->numgbits = 2; if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) { goto error; } while (!(ret = jas_tvparser_next(tvp))) { switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts, jas_tvparser_gettag(tvp)))->id) { case OPT_DEBUG: cp->debug = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFX: cp->imgareatlx = atoi(jas_tvparser_getval(tvp)); break; case OPT_IMGAREAOFFY: cp->imgareatly = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFX: cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEGRDOFFY: cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEWIDTH: cp->tilewidth = atoi(jas_tvparser_getval(tvp)); break; case OPT_TILEHEIGHT: cp->tileheight = atoi(jas_tvparser_getval(tvp)); break; case OPT_PRCWIDTH: prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_PRCHEIGHT: prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKWIDTH: tccp->cblkwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_CBLKHEIGHT: tccp->cblkheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp))); break; case OPT_MODE: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid mode %s\n", jas_tvparser_getval(tvp)); } else { tcp->intmode = (tagid == MODE_INT); } break; case OPT_PRG: if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab, jas_tvparser_getval(tvp)))->id) < 0) { jas_eprintf("ignoring invalid progression order %s\n", jas_tvparser_getval(tvp)); } else { tcp->prg = tagid; } break; case OPT_NOMCT: enablemct = false; break; case OPT_MAXRLVLS: tccp->maxrlvls = atoi(jas_tvparser_getval(tvp)); break; case OPT_SOP: cp->tcp.csty |= JPC_COD_SOP; break; case OPT_EPH: cp->tcp.csty |= JPC_COD_EPH; break; case OPT_LAZY: tccp->cblksty |= JPC_COX_LAZY; break; case OPT_TERMALL: tccp->cblksty |= JPC_COX_TERMALL; break; case OPT_SEGSYM: tccp->cblksty |= JPC_COX_SEGSYM; break; case OPT_VCAUSAL: tccp->cblksty |= JPC_COX_VSC; break; case OPT_RESET: tccp->cblksty |= JPC_COX_RESET; break; case OPT_PTERM: tccp->cblksty |= JPC_COX_PTERM; break; case OPT_NUMGBITS: cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp)); break; case OPT_RATE: if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize, &cp->totalsize)) { jas_eprintf("ignoring bad rate specifier %s\n", jas_tvparser_getval(tvp)); } break; case OPT_ILYRRATES: if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates, &ilyrrates)) { jas_eprintf("warning: invalid intermediate layer rates specifier ignored (%s)\n", jas_tvparser_getval(tvp)); } break; case OPT_JP2OVERHEAD: jp2overhead = atoi(jas_tvparser_getval(tvp)); break; default: jas_eprintf("warning: ignoring invalid option %s\n", jas_tvparser_gettag(tvp)); break; } } jas_tvparser_destroy(tvp); tvp = 0; if (cp->totalsize != UINT_FAST32_MAX) { cp->totalsize = (cp->totalsize > jp2overhead) ? (cp->totalsize - jp2overhead) : 0; } if (cp->imgareatlx == UINT_FAST32_MAX) { cp->imgareatlx = 0; } else { if (hsteplcm != 1) { jas_eprintf("warning: overriding imgareatlx value\n"); } cp->imgareatlx *= hsteplcm; } if (cp->imgareatly == UINT_FAST32_MAX) { cp->imgareatly = 0; } else { if (vsteplcm != 1) { jas_eprintf("warning: overriding imgareatly value\n"); } cp->imgareatly *= vsteplcm; } cp->refgrdwidth = cp->imgareatlx + jas_image_width(image); cp->refgrdheight = cp->imgareatly + jas_image_height(image); if (cp->tilegrdoffx == UINT_FAST32_MAX) { cp->tilegrdoffx = cp->imgareatlx; } if (cp->tilegrdoffy == UINT_FAST32_MAX) { cp->tilegrdoffy = cp->imgareatly; } if (!cp->tilewidth) { cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx; } if (!cp->tileheight) { cp->tileheight = cp->refgrdheight - cp->tilegrdoffy; } if (cp->numcmpts == 3) { mctvalid = true; for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) { if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) || jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) || jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) || jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) { mctvalid = false; } } } else { mctvalid = false; } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) { jas_eprintf("warning: color space apparently not RGB\n"); } if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) { tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT); } else { tcp->mctid = JPC_MCT_NONE; } tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS); for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { tccp->prcwidthexpns[rlvlno] = prcwidthexpn; tccp->prcheightexpns[rlvlno] = prcheightexpn; } if (prcwidthexpn != 15 || prcheightexpn != 15) { tccp->csty |= JPC_COX_PRT; } /* Ensure that the tile width and height is valid. */ if (!cp->tilewidth) { jas_eprintf("invalid tile width %lu\n", (unsigned long) cp->tilewidth); goto error; } if (!cp->tileheight) { jas_eprintf("invalid tile height %lu\n", (unsigned long) cp->tileheight); goto error; } /* Ensure that the tile grid offset is valid. */ if (cp->tilegrdoffx > cp->imgareatlx || cp->tilegrdoffy > cp->imgareatly || cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx || cp->tilegrdoffy + cp->tileheight < cp->imgareatly) { jas_eprintf("invalid tile grid offset (%lu, %lu)\n", (unsigned long) cp->tilegrdoffx, (unsigned long) cp->tilegrdoffy); goto error; } cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx, cp->tilewidth); cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy, cp->tileheight); cp->numtiles = cp->numhtiles * cp->numvtiles; if (ilyrrates && numilyrrates > 0) { tcp->numlyrs = numilyrrates + 1; if (!(tcp->ilyrrates = jas_malloc((tcp->numlyrs - 1) * sizeof(jpc_fix_t)))) { goto error; } for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) { tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]); } } /* Ensure that the integer mode is used in the case of lossless coding. */ if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) { jas_eprintf("cannot use real mode for lossless coding\n"); goto error; } /* Ensure that the precinct width is valid. */ if (prcwidthexpn > 15) { jas_eprintf("invalid precinct width\n"); goto error; } /* Ensure that the precinct height is valid. */ if (prcheightexpn > 15) { jas_eprintf("invalid precinct height\n"); goto error; } /* Ensure that the code block width is valid. */ if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) { jas_eprintf("invalid code block width %d\n", JPC_POW2(cp->tccp.cblkwidthexpn)); goto error; } /* Ensure that the code block height is valid. */ if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) { jas_eprintf("invalid code block height %d\n", JPC_POW2(cp->tccp.cblkheightexpn)); goto error; } /* Ensure that the code block size is not too large. */ if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) { jas_eprintf("code block size too large\n"); goto error; } /* Ensure that the number of layers is valid. */ if (cp->tcp.numlyrs > 16384) { jas_eprintf("too many layers\n"); goto error; } /* There must be at least one resolution level. */ if (cp->tccp.maxrlvls < 1) { jas_eprintf("must be at least one resolution level\n"); goto error; } /* Ensure that the number of guard bits is valid. */ if (cp->tccp.numgbits > 8) { jas_eprintf("invalid number of guard bits\n"); goto error; } /* Ensure that the rate is within the legal range. */ if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) { jas_eprintf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize); } /* Ensure that the intermediate layer rates are valid. */ if (tcp->numlyrs > 1) { /* The intermediate layers rates must increase monotonically. */ for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) { if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) { jas_eprintf("intermediate layer rates must increase monotonically\n"); goto error; } } /* The intermediate layer rates must be less than the overall rate. */ if (cp->totalsize != UINT_FAST32_MAX) { for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) { if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize) / cp->rawsize) { jas_eprintf("warning: intermediate layer rates must be less than overall rate\n"); goto error; } } } } if (ilyrrates) { jas_free(ilyrrates); } return cp; error: if (ilyrrates) { jas_free(ilyrrates); } if (tvp) { jas_tvparser_destroy(tvp); } if (cp) { jpc_enc_cp_destroy(cp); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cdef_t *cdef = &box->data.cdef; jp2_cdefchan_t *chan; unsigned int channo; if (jp2_getuint16(in, &cdef->numchans)) { return -1; } if (!(cdef->ents = jas_malloc(cdef->numchans * sizeof(jp2_cdefchan_t)))) { return -1; } for (channo = 0; channo < cdef->numchans; ++channo) { chan = &cdef->ents[channo]; if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) || jp2_getuint16(in, &chan->assoc)) { return -1; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_dec_tile_t *tile; jpc_sot_t *sot = &ms->parms.sot; jas_image_cmptparm_t *compinfos; jas_image_cmptparm_t *compinfo; jpc_dec_cmpt_t *cmpt; int cmptno; if (dec->state == JPC_MH) { compinfos = jas_malloc(dec->numcomps * sizeof(jas_image_cmptparm_t)); assert(compinfos); for (cmptno = 0, cmpt = dec->cmpts, compinfo = compinfos; cmptno < dec->numcomps; ++cmptno, ++cmpt, ++compinfo) { compinfo->tlx = 0; compinfo->tly = 0; compinfo->prec = cmpt->prec; compinfo->sgnd = cmpt->sgnd; compinfo->width = cmpt->width; compinfo->height = cmpt->height; compinfo->hstep = cmpt->hstep; compinfo->vstep = cmpt->vstep; } if (!(dec->image = jas_image_create(dec->numcomps, compinfos, JAS_CLRSPC_UNKNOWN))) { return -1; } jas_free(compinfos); /* Is the packet header information stored in PPM marker segments in the main header? */ if (dec->ppmstab) { /* Convert the PPM marker segment data into a collection of streams (one stream per tile-part). */ if (!(dec->pkthdrstreams = jpc_ppmstabtostreams(dec->ppmstab))) { abort(); } jpc_ppxstab_destroy(dec->ppmstab); dec->ppmstab = 0; } } if (sot->len > 0) { dec->curtileendoff = jas_stream_getrwcount(dec->in) - ms->len - 4 + sot->len; } else { dec->curtileendoff = 0; } if (JAS_CAST(int, sot->tileno) >= dec->numtiles) { jas_eprintf("invalid tile number in SOT marker segment\n"); return -1; } /* Set the current tile. */ dec->curtile = &dec->tiles[sot->tileno]; tile = dec->curtile; /* Ensure that this is the expected part number. */ if (sot->partno != tile->partno) { return -1; } if (tile->numparts > 0 && sot->partno >= tile->numparts) { return -1; } if (!tile->numparts && sot->numparts > 0) { tile->numparts = sot->numparts; } tile->pptstab = 0; switch (tile->state) { case JPC_TILE_INIT: /* This is the first tile-part for this tile. */ tile->state = JPC_TILE_ACTIVE; assert(!tile->cp); if (!(tile->cp = jpc_dec_cp_copy(dec->cp))) { return -1; } jpc_dec_cp_resetflags(dec->cp); break; default: if (sot->numparts == sot->partno - 1) { tile->state = JPC_TILE_ACTIVELAST; } break; } /* Note: We do not increment the expected tile-part number until all processing for this tile-part is complete. */ /* We should expect to encounter other tile-part header marker segments next. */ dec->state = JPC_TPH; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jas_matrix_t *jas_matrix_create(int numrows, int numcols) { jas_matrix_t *matrix; int i; if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) { return 0; } matrix->flags_ = 0; matrix->numrows_ = numrows; matrix->numcols_ = numcols; matrix->rows_ = 0; matrix->maxrows_ = numrows; matrix->data_ = 0; matrix->datasize_ = numrows * numcols; if (matrix->maxrows_ > 0) { if (!(matrix->rows_ = jas_malloc(matrix->maxrows_ * sizeof(jas_seqent_t *)))) { jas_matrix_destroy(matrix); return 0; } } if (matrix->datasize_ > 0) { if (!(matrix->data_ = jas_malloc(matrix->datasize_ * sizeof(jas_seqent_t)))) { jas_matrix_destroy(matrix); return 0; } } for (i = 0; i < numrows; ++i) { matrix->rows_[i] = &matrix->data_[i * matrix->numcols_]; } for (i = 0; i < matrix->datasize_; ++i) { matrix->data_[i] = 0; } matrix->xstart_ = 0; matrix->ystart_ = 0; matrix->xend_ = matrix->numcols_; matrix->yend_ = matrix->numrows_; return matrix; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char *jas_strdup(const char *s) { int n; char *p; n = strlen(s) + 1; if (!(p = jas_malloc(n * sizeof(char)))) { return 0; } strcpy(p, s); return p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void jpc_qmfb_join_col(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t joinbuf[QMFB_JOINBUFSIZE]; jpc_fix_t *buf = joinbuf; register jpc_fix_t *srcptr; register jpc_fix_t *dstptr; register int n; int hstartcol; /* Allocate memory for the join buffer from the heap. */ if (bufsize > QMFB_JOINBUFSIZE) { if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide. */ abort(); } } hstartcol = (numrows + 1 - parity) >> 1; /* Save the samples from the lowpass channel. */ n = hstartcol; srcptr = &a[0]; dstptr = buf; while (n-- > 0) { *dstptr = *srcptr; srcptr += stride; ++dstptr; } /* Copy the samples from the highpass channel into place. */ srcptr = &a[hstartcol * stride]; dstptr = &a[(1 - parity) * stride]; n = numrows - hstartcol; while (n-- > 0) { *dstptr = *srcptr; dstptr += 2 * stride; srcptr += stride; } /* Copy the samples from the lowpass channel into place. */ srcptr = buf; dstptr = &a[parity * stride]; n = hstartcol; while (n-- > 0) { *dstptr = *srcptr; dstptr += 2 * stride; ++srcptr; } /* If the join buffer was allocated on the heap, free this memory. */ if (buf != joinbuf) { jas_free(buf); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp, jpc_enc_band_t *band) { uint_fast32_t prcno; uint_fast32_t prcxind; uint_fast32_t prcyind; uint_fast32_t cbgtlx; uint_fast32_t cbgtly; uint_fast32_t tlprctlx; uint_fast32_t tlprctly; uint_fast32_t tlcbgtlx; uint_fast32_t tlcbgtly; uint_fast16_t rlvlno; jpc_enc_rlvl_t *rlvl; uint_fast32_t tlcblktlx; uint_fast32_t tlcblktly; uint_fast32_t brcblkbrx; uint_fast32_t brcblkbry; uint_fast32_t cblkno; jpc_enc_cblk_t *cblk; jpc_enc_tcmpt_t *tcmpt; prc->cblks = 0; prc->incltree = 0; prc->savincltree = 0; prc->nlibtree = 0; prc->savnlibtree = 0; rlvl = band->rlvl; tcmpt = rlvl->tcmpt; rlvlno = rlvl - tcmpt->rlvls; prcno = prc - band->prcs; prcxind = prcno % rlvl->numhprcs; prcyind = prcno / rlvl->numhprcs; prc->band = band; tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn); tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn); if (!rlvlno) { tlcbgtlx = tlprctlx; tlcbgtly = tlprctly; } else { tlcbgtlx = JPC_CEILDIVPOW2(tlprctlx, 1); tlcbgtly = JPC_CEILDIVPOW2(tlprctly, 1); } /* Compute the coordinates of the top-left and bottom-right corners of the precinct. */ cbgtlx = tlcbgtlx + (prcxind << rlvl->cbgwidthexpn); cbgtly = tlcbgtly + (prcyind << rlvl->cbgheightexpn); prc->tlx = JAS_MAX(jas_seq2d_xstart(band->data), cbgtlx); prc->tly = JAS_MAX(jas_seq2d_ystart(band->data), cbgtly); prc->brx = JAS_MIN(jas_seq2d_xend(band->data), cbgtlx + (1 << rlvl->cbgwidthexpn)); prc->bry = JAS_MIN(jas_seq2d_yend(band->data), cbgtly + (1 << rlvl->cbgheightexpn)); if (prc->tlx < prc->brx && prc->tly < prc->bry) { /* The precinct contains at least one code block. */ tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn); tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn); brcblkbrx = JPC_CEILTOMULTPOW2(prc->brx, rlvl->cblkwidthexpn); brcblkbry = JPC_CEILTOMULTPOW2(prc->bry, rlvl->cblkheightexpn); prc->numhcblks = JPC_FLOORDIVPOW2(brcblkbrx - tlcblktlx, rlvl->cblkwidthexpn); prc->numvcblks = JPC_FLOORDIVPOW2(brcblkbry - tlcblktly, rlvl->cblkheightexpn); prc->numcblks = prc->numhcblks * prc->numvcblks; if (!(prc->incltree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { goto error; } if (!(prc->nlibtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { goto error; } if (!(prc->savincltree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { goto error; } if (!(prc->savnlibtree = jpc_tagtree_create(prc->numhcblks, prc->numvcblks))) { goto error; } if (!(prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_enc_cblk_t)))) { goto error; } for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { cblk->passes = 0; cblk->stream = 0; cblk->mqenc = 0; cblk->data = 0; cblk->flags = 0; cblk->prc = prc; } for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { if (!cblk_create(cblk, cp, prc)) { goto error; } } } else { /* The precinct does not contain any code blocks. */ prc->tlx = prc->brx; prc->tly = prc->bry; prc->numcblks = 0; prc->numhcblks = 0; prc->numvcblks = 0; prc->cblks = 0; prc->incltree = 0; prc->nlibtree = 0; prc->savincltree = 0; prc->savnlibtree = 0; } return prc; error: prc_destroy(prc); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jpc_pi_t *jpc_dec_pi_create(jpc_dec_t *dec, jpc_dec_tile_t *tile) { jpc_pi_t *pi; int compno; jpc_picomp_t *picomp; jpc_pirlvl_t *pirlvl; jpc_dec_tcomp_t *tcomp; int rlvlno; jpc_dec_rlvl_t *rlvl; int prcno; int *prclyrno; jpc_dec_cmpt_t *cmpt; if (!(pi = jpc_pi_create0())) { return 0; } pi->numcomps = dec->numcomps; if (!(pi->picomps = jas_malloc(pi->numcomps * sizeof(jpc_picomp_t)))) { jpc_pi_destroy(pi); return 0; } for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { picomp->pirlvls = 0; } for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++tcomp, ++picomp) { picomp->numrlvls = tcomp->numrlvls; if (!(picomp->pirlvls = jas_malloc(picomp->numrlvls * sizeof(jpc_pirlvl_t)))) { jpc_pi_destroy(pi); return 0; } for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { pirlvl->prclyrnos = 0; } for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) { /* XXX sizeof(long) should be sizeof different type */ pirlvl->numprcs = rlvl->numprcs; if (!(pirlvl->prclyrnos = jas_malloc(pirlvl->numprcs * sizeof(long)))) { jpc_pi_destroy(pi); return 0; } } } pi->maxrlvls = 0; for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps, cmpt = dec->cmpts; compno < pi->numcomps; ++compno, ++tcomp, ++picomp, ++cmpt) { picomp->hsamp = cmpt->hstep; picomp->vsamp = cmpt->vstep; for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) { pirlvl->prcwidthexpn = rlvl->prcwidthexpn; pirlvl->prcheightexpn = rlvl->prcheightexpn; for (prcno = 0, prclyrno = pirlvl->prclyrnos; prcno < pirlvl->numprcs; ++prcno, ++prclyrno) { *prclyrno = 0; } pirlvl->numhprcs = rlvl->numhprcs; } if (pi->maxrlvls < tcomp->numrlvls) { pi->maxrlvls = tcomp->numrlvls; } } pi->numlyrs = tile->cp->numlyrs; pi->xstart = tile->xstart; pi->ystart = tile->ystart; pi->xend = tile->xend; pi->yend = tile->yend; pi->picomp = 0; pi->pirlvl = 0; pi->x = 0; pi->y = 0; pi->compno = 0; pi->rlvlno = 0; pi->prcno = 0; pi->lyrno = 0; pi->xstep = 0; pi->ystep = 0; pi->pchgno = -1; pi->defaultpchg.prgord = tile->cp->prgord; pi->defaultpchg.compnostart = 0; pi->defaultpchg.compnoend = pi->numcomps; pi->defaultpchg.rlvlnostart = 0; pi->defaultpchg.rlvlnoend = pi->maxrlvls; pi->defaultpchg.lyrnoend = pi->numlyrs; pi->pchg = 0; pi->valid = 0; return pi; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp, jas_image_t *image, jpc_enc_tile_t *tile) { uint_fast16_t cmptno; uint_fast16_t rlvlno; jpc_enc_rlvl_t *rlvl; uint_fast32_t tlx; uint_fast32_t tly; uint_fast32_t brx; uint_fast32_t bry; uint_fast32_t cmpttlx; uint_fast32_t cmpttly; jpc_enc_ccp_t *ccp; jpc_tsfb_band_t bandinfos[JPC_MAXBANDS]; tcmpt->tile = tile; tcmpt->tsfb = 0; tcmpt->data = 0; tcmpt->rlvls = 0; /* Deduce the component number. */ cmptno = tcmpt - tile->tcmpts; ccp = &cp->ccps[cmptno]; /* Compute the coordinates of the top-left and bottom-right corners of this tile-component. */ tlx = JPC_CEILDIV(tile->tlx, ccp->sampgrdstepx); tly = JPC_CEILDIV(tile->tly, ccp->sampgrdstepy); brx = JPC_CEILDIV(tile->brx, ccp->sampgrdstepx); bry = JPC_CEILDIV(tile->bry, ccp->sampgrdstepy); /* Create a sequence to hold the tile-component sample data. */ if (!(tcmpt->data = jas_seq2d_create(tlx, tly, brx, bry))) { goto error; } /* Get the image data associated with this tile-component. */ cmpttlx = JPC_CEILDIV(cp->imgareatlx, ccp->sampgrdstepx); cmpttly = JPC_CEILDIV(cp->imgareatly, ccp->sampgrdstepy); if (jas_image_readcmpt(image, cmptno, tlx - cmpttlx, tly - cmpttly, brx - tlx, bry - tly, tcmpt->data)) { goto error; } tcmpt->synweight = 0; tcmpt->qmfbid = cp->tccp.qmfbid; tcmpt->numrlvls = cp->tccp.maxrlvls; tcmpt->numbands = 3 * tcmpt->numrlvls - 2; if (!(tcmpt->tsfb = jpc_cod_gettsfb(tcmpt->qmfbid, tcmpt->numrlvls - 1))) { goto error; } for (rlvlno = 0; rlvlno < tcmpt->numrlvls; ++rlvlno) { tcmpt->prcwidthexpns[rlvlno] = cp->tccp.prcwidthexpns[rlvlno]; tcmpt->prcheightexpns[rlvlno] = cp->tccp.prcheightexpns[rlvlno]; } tcmpt->cblkwidthexpn = cp->tccp.cblkwidthexpn; tcmpt->cblkheightexpn = cp->tccp.cblkheightexpn; tcmpt->cblksty = cp->tccp.cblksty; tcmpt->csty = cp->tccp.csty; tcmpt->numstepsizes = tcmpt->numbands; assert(tcmpt->numstepsizes <= JPC_MAXBANDS); memset(tcmpt->stepsizes, 0, tcmpt->numstepsizes * sizeof(uint_fast16_t)); /* Retrieve information about the various bands. */ jpc_tsfb_getbands(tcmpt->tsfb, jas_seq2d_xstart(tcmpt->data), jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data), jas_seq2d_yend(tcmpt->data), bandinfos); if (!(tcmpt->rlvls = jas_malloc(tcmpt->numrlvls * sizeof(jpc_enc_rlvl_t)))) { goto error; } for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls; ++rlvlno, ++rlvl) { rlvl->bands = 0; rlvl->tcmpt = tcmpt; } for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls; ++rlvlno, ++rlvl) { if (!rlvl_create(rlvl, cp, tcmpt, bandinfos)) { goto error; } } return tcmpt; error: tcmpt_destroy(tcmpt); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = splitbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int m; int hstartcol; /* Get a buffer. */ if (bufsize > QMFB_SPLITBUFSIZE) { if (!(buf = jas_malloc(bufsize * sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide in this case. */ abort(); } } if (numrows >= 2) { hstartcol = (numrows + 1 - parity) >> 1; m = (parity) ? hstartcol : (numrows - hstartcol); /* Save the samples destined for the highpass channel. */ n = m; dstptr = buf; srcptr = &a[(1 - parity) * stride]; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < numcols; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += numcols; srcptr += stride << 1; } /* Copy the appropriate samples into the lowpass channel. */ dstptr = &a[(1 - parity) * stride]; srcptr = &a[(2 - parity) * stride]; n = numrows - m - (!parity); while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < numcols; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += stride << 1; } /* Copy the saved samples into the highpass channel. */ dstptr = &a[hstartcol * stride]; srcptr = buf; n = m; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < numcols; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += numcols; } } /* If the split buffer was allocated on the heap, free this memory. */ if (buf != splitbuf) { jas_free(buf); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'At many places in the code, jas_malloc or jas_recalloc was being invoked with the size argument being computed in a manner that would not allow integer overflow to be detected. Now, these places in the code have been modified to use special-purpose memory allocation functions (e.g., jas_alloc2, jas_alloc3, jas_realloc2) that check for overflow. This should fix many security problems.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int jas_stream_printf(jas_stream_t *stream, const char *fmt, ...) { va_list ap; char buf[4096]; int ret; va_start(ap, fmt); ret = vsprintf(buf, fmt, ap); jas_stream_puts(stream, buf); va_end(ap); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'CVE-2008-3522'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int pipe_to_file(struct pipe_inode_info *pipe, struct pipe_buffer *buf, struct splice_desc *sd) { struct file *file = sd->u.file; struct address_space *mapping = file->f_mapping; unsigned int offset, this_len; struct page *page; pgoff_t index; int ret; /* * make sure the data in this buffer is uptodate */ ret = buf->ops->confirm(pipe, buf); if (unlikely(ret)) return ret; index = sd->pos >> PAGE_CACHE_SHIFT; offset = sd->pos & ~PAGE_CACHE_MASK; this_len = sd->len; if (this_len + offset > PAGE_CACHE_SIZE) this_len = PAGE_CACHE_SIZE - offset; find_page: page = find_lock_page(mapping, index); if (!page) { ret = -ENOMEM; page = page_cache_alloc_cold(mapping); if (unlikely(!page)) goto out_ret; /* * This will also lock the page */ ret = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL); if (unlikely(ret)) goto out; } ret = mapping->a_ops->prepare_write(file, page, offset, offset+this_len); if (unlikely(ret)) { loff_t isize = i_size_read(mapping->host); if (ret != AOP_TRUNCATED_PAGE) unlock_page(page); page_cache_release(page); if (ret == AOP_TRUNCATED_PAGE) goto find_page; /* * prepare_write() may have instantiated a few blocks * outside i_size. Trim these off again. */ if (sd->pos + this_len > isize) vmtruncate(mapping->host, isize); goto out_ret; } if (buf->page != page) { /* * Careful, ->map() uses KM_USER0! */ char *src = buf->ops->map(pipe, buf, 1); char *dst = kmap_atomic(page, KM_USER1); memcpy(dst + offset, src + buf->offset, this_len); flush_dcache_page(page); kunmap_atomic(dst, KM_USER1); buf->ops->unmap(pipe, buf, src); } ret = mapping->a_ops->commit_write(file, page, offset, offset+this_len); if (ret) { if (ret == AOP_TRUNCATED_PAGE) { page_cache_release(page); goto find_page; } if (ret < 0) goto out; /* * Partial write has happened, so 'ret' already initialized by * number of bytes written, Where is nothing we have to do here. */ } else ret = this_len; /* * Return the number of bytes written and mark page as * accessed, we are now done! */ mark_page_accessed(page); out: page_cache_release(page); unlock_page(page); out_ret: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'splice: fix bad unlock_page() in error case If add_to_page_cache_lru() fails, the page will not be locked. But splice jumps to an error path that does a page release and unlock, causing a BUG() in unlock_page(). Fix this by adding one more label that just releases the page. This bug was actually triggered on EL5 by gurudas pai <gurudas.pai@oracle.com> using fio. Signed-off-by: Jens Axboe <jens.axboe@oracle.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int sctp_auth_ep_set_hmacs(struct sctp_endpoint *ep, struct sctp_hmacalgo *hmacs) { int has_sha1 = 0; __u16 id; int i; /* Scan the list looking for unsupported id. Also make sure that * SHA1 is specified. */ for (i = 0; i < hmacs->shmac_num_idents; i++) { id = hmacs->shmac_idents[i]; if (SCTP_AUTH_HMAC_ID_SHA1 == id) has_sha1 = 1; if (!sctp_hmac_list[id].hmac_name) return -EOPNOTSUPP; } if (!has_sha1) return -EINVAL; memcpy(ep->auth_hmacs_list->hmac_ids, &hmacs->shmac_idents[0], hmacs->shmac_num_idents * sizeof(__u16)); ep->auth_hmacs_list->param_hdr.length = htons(sizeof(sctp_paramhdr_t) + hmacs->shmac_num_idents * sizeof(__u16)); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'sctp: fix random memory dereference with SCTP_HMAC_IDENT option. The number of identifiers needs to be checked against the option length. Also, the identifier index provided needs to be verified to make sure that it doesn't exceed the bounds of the array. Signed-off-by: Vlad Yasevich <vladislav.yasevich@hp.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: generic_file_splice_write(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags) { struct address_space *mapping = out->f_mapping; ssize_t ret; ret = splice_from_pipe(pipe, out, ppos, len, flags, pipe_to_file); if (ret > 0) { struct inode *inode = mapping->host; *ppos += ret; /* * If file or inode is SYNC and we actually wrote some data, * sync it. */ if (unlikely((out->f_flags & O_SYNC) || IS_SYNC(inode))) { int err; mutex_lock(&inode->i_mutex); err = generic_osync_inode(inode, mapping, OSYNC_METADATA|OSYNC_DATA); mutex_unlock(&inode->i_mutex); if (err) ret = err; } } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': '[PATCH] Remove SUID when splicing into an inode Originally from Mark Fasheh <mark.fasheh@oracle.com> generic_file_splice_write() does not remove S_ISUID or S_ISGID. This is inconsistent with the way we generally write to files. Signed-off-by: Mark Fasheh <mark.fasheh@oracle.com> Signed-off-by: Jens Axboe <jens.axboe@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _dbus_validate_signature_with_reason (const DBusString *type_str, int type_pos, int len) { const unsigned char *p; const unsigned char *end; int last; int struct_depth; int array_depth; int dict_entry_depth; DBusValidity result; int element_count; DBusList *element_count_stack; result = DBUS_VALID; element_count_stack = NULL; if (!_dbus_list_append (&element_count_stack, _DBUS_INT_TO_POINTER (0))) { result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR; goto out; } _dbus_assert (type_str != NULL); _dbus_assert (type_pos < _DBUS_INT32_MAX - len); _dbus_assert (len >= 0); _dbus_assert (type_pos >= 0); if (len > DBUS_MAXIMUM_SIGNATURE_LENGTH) { result = DBUS_INVALID_SIGNATURE_TOO_LONG; goto out; } p = _dbus_string_get_const_data_len (type_str, type_pos, 0); end = _dbus_string_get_const_data_len (type_str, type_pos + len, 0); struct_depth = 0; array_depth = 0; dict_entry_depth = 0; last = DBUS_TYPE_INVALID; while (p != end) { switch (*p) { case DBUS_TYPE_BYTE: case DBUS_TYPE_BOOLEAN: case DBUS_TYPE_INT16: case DBUS_TYPE_UINT16: case DBUS_TYPE_INT32: case DBUS_TYPE_UINT32: case DBUS_TYPE_INT64: case DBUS_TYPE_UINT64: case DBUS_TYPE_DOUBLE: case DBUS_TYPE_STRING: case DBUS_TYPE_OBJECT_PATH: case DBUS_TYPE_SIGNATURE: case DBUS_TYPE_VARIANT: break; case DBUS_TYPE_ARRAY: array_depth += 1; if (array_depth > DBUS_MAXIMUM_TYPE_RECURSION_DEPTH) { result = DBUS_INVALID_EXCEEDED_MAXIMUM_ARRAY_RECURSION; goto out; } break; case DBUS_STRUCT_BEGIN_CHAR: struct_depth += 1; if (struct_depth > DBUS_MAXIMUM_TYPE_RECURSION_DEPTH) { result = DBUS_INVALID_EXCEEDED_MAXIMUM_STRUCT_RECURSION; goto out; } if (!_dbus_list_append (&element_count_stack, _DBUS_INT_TO_POINTER (0))) { result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR; goto out; } break; case DBUS_STRUCT_END_CHAR: if (struct_depth == 0) { result = DBUS_INVALID_STRUCT_ENDED_BUT_NOT_STARTED; goto out; } if (last == DBUS_STRUCT_BEGIN_CHAR) { result = DBUS_INVALID_STRUCT_HAS_NO_FIELDS; goto out; } _dbus_list_pop_last (&element_count_stack); struct_depth -= 1; break; case DBUS_DICT_ENTRY_BEGIN_CHAR: if (last != DBUS_TYPE_ARRAY) { result = DBUS_INVALID_DICT_ENTRY_NOT_INSIDE_ARRAY; goto out; } dict_entry_depth += 1; if (dict_entry_depth > DBUS_MAXIMUM_TYPE_RECURSION_DEPTH) { result = DBUS_INVALID_EXCEEDED_MAXIMUM_DICT_ENTRY_RECURSION; goto out; } if (!_dbus_list_append (&element_count_stack, _DBUS_INT_TO_POINTER (0))) { result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR; goto out; } break; case DBUS_DICT_ENTRY_END_CHAR: if (dict_entry_depth == 0) { result = DBUS_INVALID_DICT_ENTRY_ENDED_BUT_NOT_STARTED; goto out; } dict_entry_depth -= 1; element_count = _DBUS_POINTER_TO_INT (_dbus_list_pop_last (&element_count_stack)); if (element_count != 2) { if (element_count == 0) result = DBUS_INVALID_DICT_ENTRY_HAS_NO_FIELDS; else if (element_count == 1) result = DBUS_INVALID_DICT_ENTRY_HAS_ONLY_ONE_FIELD; else result = DBUS_INVALID_DICT_ENTRY_HAS_TOO_MANY_FIELDS; goto out; } break; case DBUS_TYPE_STRUCT: /* doesn't appear in signatures */ case DBUS_TYPE_DICT_ENTRY: /* ditto */ default: result = DBUS_INVALID_UNKNOWN_TYPECODE; goto out; } if (*p != DBUS_TYPE_ARRAY && *p != DBUS_DICT_ENTRY_BEGIN_CHAR && *p != DBUS_STRUCT_BEGIN_CHAR) { element_count = _DBUS_POINTER_TO_INT (_dbus_list_pop_last (&element_count_stack)); ++element_count; if (!_dbus_list_append (&element_count_stack, _DBUS_INT_TO_POINTER (element_count))) { result = DBUS_VALIDITY_UNKNOWN_OOM_ERROR; goto out; } } if (array_depth > 0) { if (*p == DBUS_TYPE_ARRAY && p != end) { const char *p1; p1 = p + 1; if (*p1 == DBUS_STRUCT_END_CHAR || *p1 == DBUS_DICT_ENTRY_END_CHAR) { result = DBUS_INVALID_MISSING_ARRAY_ELEMENT_TYPE; goto out; } } else { array_depth = 0; } } if (last == DBUS_DICT_ENTRY_BEGIN_CHAR && !dbus_type_is_basic (*p)) { result = DBUS_INVALID_DICT_KEY_MUST_BE_BASIC_TYPE; goto out; } last = *p; ++p; } if (array_depth > 0) { result = DBUS_INVALID_MISSING_ARRAY_ELEMENT_TYPE; goto out; } if (struct_depth > 0) { result = DBUS_INVALID_STRUCT_STARTED_BUT_NOT_ENDED; goto out; } if (dict_entry_depth > 0) { result = DBUS_INVALID_DICT_ENTRY_STARTED_BUT_NOT_ENDED; goto out; } _dbus_assert (last != DBUS_TYPE_ARRAY); _dbus_assert (last != DBUS_STRUCT_BEGIN_CHAR); _dbus_assert (last != DBUS_DICT_ENTRY_BEGIN_CHAR); result = DBUS_VALID; out: _dbus_list_clear (&element_count_stack); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Bug 17803: Panic from dbus_signature_validate * dbus/dbus-marshal-validate.c: Ensure we validate a basic type before calling is_basic on it. * dbus-marshal-validate-util.c: Test.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sctp_disposition_t sctp_sf_do_asconf_ack(const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *asconf_ack = arg; struct sctp_chunk *last_asconf = asoc->addip_last_asconf; struct sctp_chunk *abort; struct sctp_paramhdr *err_param = NULL; sctp_addiphdr_t *addip_hdr; __u32 sent_serial, rcvd_serial; if (!sctp_vtag_verify(asconf_ack, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(ep, asoc, type, arg, commands); } /* ADD-IP, Section 4.1.2: * This chunk MUST be sent in an authenticated way by using * the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk * is received unauthenticated it MUST be silently discarded as * described in [I-D.ietf-tsvwg-sctp-auth]. */ if (!sctp_addip_noauth && !asconf_ack->auth) return sctp_sf_discard_chunk(ep, asoc, type, arg, commands); /* Make sure that the ADDIP chunk has a valid length. */ if (!sctp_chunk_length_valid(asconf_ack, sizeof(sctp_addip_chunk_t))) return sctp_sf_violation_chunklen(ep, asoc, type, arg, commands); addip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data; rcvd_serial = ntohl(addip_hdr->serial); /* Verify the ASCONF-ACK chunk before processing it. */ if (!sctp_verify_asconf(asoc, (sctp_paramhdr_t *)addip_hdr->params, (void *)asconf_ack->chunk_end, &err_param)) return sctp_sf_violation_paramlen(ep, asoc, type, (void *)&err_param, commands); if (last_asconf) { addip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr; sent_serial = ntohl(addip_hdr->serial); } else { sent_serial = asoc->addip_serial - 1; } /* D0) If an endpoint receives an ASCONF-ACK that is greater than or * equal to the next serial number to be used but no ASCONF chunk is * outstanding the endpoint MUST ABORT the association. Note that a * sequence number is greater than if it is no more than 2^^31-1 * larger than the current sequence number (using serial arithmetic). */ if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) && !(asoc->addip_last_asconf)) { abort = sctp_make_abort(asoc, asconf_ack, sizeof(sctp_errhdr_t)); if (abort) { sctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET,SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_ASCONF_ACK)); SCTP_INC_STATS(SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); if (!sctp_process_asconf_ack((struct sctp_association *)asoc, asconf_ack)) return SCTP_DISPOSITION_CONSUME; abort = sctp_make_abort(asoc, asconf_ack, sizeof(sctp_errhdr_t)); if (abort) { sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0); sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); } /* We are going to ABORT, so we might as well stop * processing the rest of the chunks in the packet. */ sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET,SCTP_NULL()); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_ASCONF_ACK)); SCTP_INC_STATS(SCTP_MIB_ABORTEDS); SCTP_DEC_STATS(SCTP_MIB_CURRESTAB); return SCTP_DISPOSITION_ABORT; } return SCTP_DISPOSITION_DISCARD; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'sctp: Fix kernel panic while process protocol violation parameter Since call to function sctp_sf_abort_violation() need paramter 'arg' with 'struct sctp_chunk' type, it will read the chunk type and chunk length from the chunk_hdr member of chunk. But call to sctp_sf_violation_paramlen() always with 'struct sctp_paramhdr' type's parameter, it will be passed to sctp_sf_abort_violation(). This may cause kernel panic. sctp_sf_violation_paramlen() |-- sctp_sf_abort_violation() |-- sctp_make_abort_violation() This patch fixed this problem. This patch also fix two place which called sctp_sf_violation_paramlen() with wrong paramter type. Signed-off-by: Wei Yongjun <yjwei@cn.fujitsu.com> Signed-off-by: Vlad Yasevich <vladislav.yasevich@hp.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int sctp_process_inv_paramlength(const struct sctp_association *asoc, struct sctp_paramhdr *param, const struct sctp_chunk *chunk, struct sctp_chunk **errp) { static const char error[] = "The following parameter had invalid length:"; size_t payload_len = WORD_ROUND(sizeof(error)) + sizeof(sctp_paramhdr_t); /* This is a fatal error. Any accumulated non-fatal errors are * not reported. */ if (*errp) sctp_chunk_free(*errp); /* Create an error chunk and fill it in with our payload. */ *errp = sctp_make_op_error_space(asoc, chunk, payload_len); if (*errp) { sctp_init_cause(*errp, SCTP_ERROR_PROTO_VIOLATION, sizeof(error) + sizeof(sctp_paramhdr_t)); sctp_addto_chunk(*errp, sizeof(error), error); sctp_addto_param(*errp, sizeof(sctp_paramhdr_t), param); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'sctp: Fix kernel panic while process protocol violation parameter Since call to function sctp_sf_abort_violation() need paramter 'arg' with 'struct sctp_chunk' type, it will read the chunk type and chunk length from the chunk_hdr member of chunk. But call to sctp_sf_violation_paramlen() always with 'struct sctp_paramhdr' type's parameter, it will be passed to sctp_sf_abort_violation(). This may cause kernel panic. sctp_sf_violation_paramlen() |-- sctp_sf_abort_violation() |-- sctp_make_abort_violation() This patch fixed this problem. This patch also fix two place which called sctp_sf_violation_paramlen() with wrong paramter type. Signed-off-by: Wei Yongjun <yjwei@cn.fujitsu.com> Signed-off-by: Vlad Yasevich <vladislav.yasevich@hp.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct sctp_transport *sctp_assoc_add_peer(struct sctp_association *asoc, const union sctp_addr *addr, const gfp_t gfp, const int peer_state) { struct sctp_transport *peer; struct sctp_sock *sp; unsigned short port; sp = sctp_sk(asoc->base.sk); /* AF_INET and AF_INET6 share common port field. */ port = ntohs(addr->v4.sin_port); SCTP_DEBUG_PRINTK_IPADDR("sctp_assoc_add_peer:association %p addr: ", " port: %d state:%d\n", asoc, addr, port, peer_state); /* Set the port if it has not been set yet. */ if (0 == asoc->peer.port) asoc->peer.port = port; /* Check to see if this is a duplicate. */ peer = sctp_assoc_lookup_paddr(asoc, addr); if (peer) { if (peer->state == SCTP_UNKNOWN) { if (peer_state == SCTP_ACTIVE) peer->state = SCTP_ACTIVE; if (peer_state == SCTP_UNCONFIRMED) peer->state = SCTP_UNCONFIRMED; } return peer; } peer = sctp_transport_new(addr, gfp); if (!peer) return NULL; sctp_transport_set_owner(peer, asoc); /* Initialize the peer's heartbeat interval based on the * association configured value. */ peer->hbinterval = asoc->hbinterval; /* Set the path max_retrans. */ peer->pathmaxrxt = asoc->pathmaxrxt; /* Initialize the peer's SACK delay timeout based on the * association configured value. */ peer->sackdelay = asoc->sackdelay; peer->sackfreq = asoc->sackfreq; /* Enable/disable heartbeat, SACK delay, and path MTU discovery * based on association setting. */ peer->param_flags = asoc->param_flags; /* Initialize the pmtu of the transport. */ if (peer->param_flags & SPP_PMTUD_ENABLE) sctp_transport_pmtu(peer); else if (asoc->pathmtu) peer->pathmtu = asoc->pathmtu; else peer->pathmtu = SCTP_DEFAULT_MAXSEGMENT; /* If this is the first transport addr on this association, * initialize the association PMTU to the peer's PMTU. * If not and the current association PMTU is higher than the new * peer's PMTU, reset the association PMTU to the new peer's PMTU. */ if (asoc->pathmtu) asoc->pathmtu = min_t(int, peer->pathmtu, asoc->pathmtu); else asoc->pathmtu = peer->pathmtu; SCTP_DEBUG_PRINTK("sctp_assoc_add_peer:association %p PMTU set to " "%d\n", asoc, asoc->pathmtu); peer->pmtu_pending = 0; asoc->frag_point = sctp_frag_point(sp, asoc->pathmtu); /* The asoc->peer.port might not be meaningful yet, but * initialize the packet structure anyway. */ sctp_packet_init(&peer->packet, peer, asoc->base.bind_addr.port, asoc->peer.port); /* 7.2.1 Slow-Start * * o The initial cwnd before DATA transmission or after a sufficiently * long idle period MUST be set to * min(4*MTU, max(2*MTU, 4380 bytes)) * * o The initial value of ssthresh MAY be arbitrarily high * (for example, implementations MAY use the size of the * receiver advertised window). */ peer->cwnd = min(4*asoc->pathmtu, max_t(__u32, 2*asoc->pathmtu, 4380)); /* At this point, we may not have the receiver's advertised window, * so initialize ssthresh to the default value and it will be set * later when we process the INIT. */ peer->ssthresh = SCTP_DEFAULT_MAXWINDOW; peer->partial_bytes_acked = 0; peer->flight_size = 0; /* Set the transport's RTO.initial value */ peer->rto = asoc->rto_initial; /* Set the peer's active state. */ peer->state = peer_state; /* Attach the remote transport to our asoc. */ list_add_tail(&peer->transports, &asoc->peer.transport_addr_list); asoc->peer.transport_count++; /* If we do not yet have a primary path, set one. */ if (!asoc->peer.primary_path) { sctp_assoc_set_primary(asoc, peer); asoc->peer.retran_path = peer; } if (asoc->peer.active_path == asoc->peer.retran_path) { asoc->peer.retran_path = peer; } return peer; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'sctp: Fix oops when INIT-ACK indicates that peer doesn't support AUTH If INIT-ACK is received with SupportedExtensions parameter which indicates that the peer does not support AUTH, the packet will be silently ignore, and sctp_process_init() do cleanup all of the transports in the association. When T1-Init timer is expires, OOPS happen while we try to choose a different init transport. The solution is to only clean up the non-active transports, i.e the ones that the peer added. However, that introduces a problem with sctp_connectx(), because we don't mark the proper state for the transports provided by the user. So, we'll simply mark user-provided transports as ACTIVE. That will allow INIT retransmissions to work properly in the sctp_connectx() context and prevent the crash. Signed-off-by: Vlad Yasevich <vladislav.yasevich@hp.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static long do_splice_from(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags) { int ret; if (unlikely(!out->f_op || !out->f_op->splice_write)) return -EINVAL; if (unlikely(!(out->f_mode & FMODE_WRITE))) return -EBADF; ret = rw_verify_area(WRITE, out, ppos, len); if (unlikely(ret < 0)) return ret; return out->f_op->splice_write(pipe, out, ppos, len, flags); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Don't allow splice() to files opened with O_APPEND This is debatable, but while we're debating it, let's disallow the combination of splice and an O_APPEND destination. It's not entirely clear what the semantics of O_APPEND should be, and POSIX apparently expects pwrite() to ignore O_APPEND, for example. So we could make up any semantics we want, including the old ones. But Miklos convinced me that we should at least give it some thought, and that accepting writes at arbitrary offsets is wrong at least for IS_APPEND() files (which always have O_APPEND set, even if the reverse isn't true: you can obviously have O_APPEND set on a regular file). So disallow O_APPEND entirely for now. I doubt anybody cares, and this way we have one less gray area to worry about. Reported-and-argued-for-by: Miklos Szeredi <miklos@szeredi.hu> Acked-by: Jens Axboe <ens.axboe@oracle.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int hfsplus_block_allocate(struct super_block *sb, u32 size, u32 offset, u32 *max) { struct page *page; struct address_space *mapping; __be32 *pptr, *curr, *end; u32 mask, start, len, n; __be32 val; int i; len = *max; if (!len) return size; dprint(DBG_BITMAP, "block_allocate: %u,%u,%u\n", size, offset, len); mutex_lock(&HFSPLUS_SB(sb).alloc_file->i_mutex); mapping = HFSPLUS_SB(sb).alloc_file->i_mapping; page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL); pptr = kmap(page); curr = pptr + (offset & (PAGE_CACHE_BITS - 1)) / 32; i = offset % 32; offset &= ~(PAGE_CACHE_BITS - 1); if ((size ^ offset) / PAGE_CACHE_BITS) end = pptr + PAGE_CACHE_BITS / 32; else end = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32; /* scan the first partial u32 for zero bits */ val = *curr; if (~val) { n = be32_to_cpu(val); mask = (1U << 31) >> i; for (; i < 32; mask >>= 1, i++) { if (!(n & mask)) goto found; } } curr++; /* scan complete u32s for the first zero bit */ while (1) { while (curr < end) { val = *curr; if (~val) { n = be32_to_cpu(val); mask = 1 << 31; for (i = 0; i < 32; mask >>= 1, i++) { if (!(n & mask)) goto found; } } curr++; } kunmap(page); offset += PAGE_CACHE_BITS; if (offset >= size) break; page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL); curr = pptr = kmap(page); if ((size ^ offset) / PAGE_CACHE_BITS) end = pptr + PAGE_CACHE_BITS / 32; else end = pptr + ((size + 31) & (PAGE_CACHE_BITS - 1)) / 32; } dprint(DBG_BITMAP, "bitmap full\n"); start = size; goto out; found: start = offset + (curr - pptr) * 32 + i; if (start >= size) { dprint(DBG_BITMAP, "bitmap full\n"); goto out; } /* do any partial u32 at the start */ len = min(size - start, len); while (1) { n |= mask; if (++i >= 32) break; mask >>= 1; if (!--len || n & mask) goto done; } if (!--len) goto done; *curr++ = cpu_to_be32(n); /* do full u32s */ while (1) { while (curr < end) { n = be32_to_cpu(*curr); if (len < 32) goto last; if (n) { len = 32; goto last; } *curr++ = cpu_to_be32(0xffffffff); len -= 32; } set_page_dirty(page); kunmap(page); offset += PAGE_CACHE_BITS; page = read_mapping_page(mapping, offset / PAGE_CACHE_BITS, NULL); pptr = kmap(page); curr = pptr; end = pptr + PAGE_CACHE_BITS / 32; } last: /* do any partial u32 at end */ mask = 1U << 31; for (i = 0; i < len; i++) { if (n & mask) break; n |= mask; mask >>= 1; } done: *curr = cpu_to_be32(n); set_page_dirty(page); kunmap(page); *max = offset + (curr - pptr) * 32 + i - start; HFSPLUS_SB(sb).free_blocks -= *max; sb->s_dirt = 1; dprint(DBG_BITMAP, "-> %u,%u\n", start, *max); out: mutex_unlock(&HFSPLUS_SB(sb).alloc_file->i_mutex); return start; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'hfsplus: check read_mapping_page() return value While testing more corrupted images with hfsplus, i came across one which triggered the following bug: [15840.675016] BUG: unable to handle kernel paging request at fffffffb [15840.675016] IP: [<c0116a4f>] kmap+0x15/0x56 [15840.675016] *pde = 00008067 *pte = 00000000 [15840.675016] Oops: 0000 [#1] PREEMPT DEBUG_PAGEALLOC [15840.675016] Modules linked in: [15840.675016] [15840.675016] Pid: 11575, comm: ln Not tainted (2.6.27-rc4-00123-gd3ee1b4-dirty #29) [15840.675016] EIP: 0060:[<c0116a4f>] EFLAGS: 00010202 CPU: 0 [15840.675016] EIP is at kmap+0x15/0x56 [15840.675016] EAX: 00000246 EBX: fffffffb ECX: 00000000 EDX: cab919c0 [15840.675016] ESI: 000007dd EDI: cab0bcf4 EBP: cab0bc98 ESP: cab0bc94 [15840.675016] DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 0068 [15840.675016] Process ln (pid: 11575, ti=cab0b000 task=cab919c0 task.ti=cab0b000) [15840.675016] Stack: 00000000 cab0bcdc c0231cfb 00000000 cab0bce0 00000800 ca9290c0 fffffffb [15840.675016] cab145d0 cab919c0 cab15998 22222222 22222222 22222222 00000001 cab15960 [15840.675016] 000007dd cab0bcf4 cab0bd04 c022cb3a cab0bcf4 cab15a6c ca9290c0 00000000 [15840.675016] Call Trace: [15840.675016] [<c0231cfb>] ? hfsplus_block_allocate+0x6f/0x2d3 [15840.675016] [<c022cb3a>] ? hfsplus_file_extend+0xc4/0x1db [15840.675016] [<c022ce41>] ? hfsplus_get_block+0x8c/0x19d [15840.675016] [<c06adde4>] ? sub_preempt_count+0x9d/0xab [15840.675016] [<c019ece6>] ? __block_prepare_write+0x147/0x311 [15840.675016] [<c0161934>] ? __grab_cache_page+0x52/0x73 [15840.675016] [<c019ef4f>] ? block_write_begin+0x79/0xd5 [15840.675016] [<c022cdb5>] ? hfsplus_get_block+0x0/0x19d [15840.675016] [<c019f22a>] ? cont_write_begin+0x27f/0x2af [15840.675016] [<c022cdb5>] ? hfsplus_get_block+0x0/0x19d [15840.675016] [<c0139ebe>] ? tick_program_event+0x28/0x4c [15840.675016] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [15840.675016] [<c022b723>] ? hfsplus_write_begin+0x2d/0x32 [15840.675016] [<c022cdb5>] ? hfsplus_get_block+0x0/0x19d [15840.675016] [<c0161988>] ? pagecache_write_begin+0x33/0x107 [15840.675016] [<c01879e5>] ? __page_symlink+0x3c/0xae [15840.675016] [<c019ad34>] ? __mark_inode_dirty+0x12f/0x137 [15840.675016] [<c0187a70>] ? page_symlink+0x19/0x1e [15840.675016] [<c022e6eb>] ? hfsplus_symlink+0x41/0xa6 [15840.675016] [<c01886a9>] ? vfs_symlink+0x99/0x101 [15840.675016] [<c018a2f6>] ? sys_symlinkat+0x6b/0xad [15840.675016] [<c018a348>] ? sys_symlink+0x10/0x12 [15840.675016] [<c01038bd>] ? sysenter_do_call+0x12/0x31 [15840.675016] ======================= [15840.675016] Code: 00 00 75 10 83 3d 88 2f ec c0 02 75 07 89 d0 e8 12 56 05 00 5d c3 55 ba 06 00 00 00 89 e5 53 89 c3 b8 3d eb 7e c0 e8 16 74 00 00 <8b> 03 c1 e8 1e 69 c0 d8 02 00 00 05 b8 69 8e c0 2b 80 c4 02 00 [15840.675016] EIP: [<c0116a4f>] kmap+0x15/0x56 SS:ESP 0068:cab0bc94 [15840.675016] ---[ end trace 4fea40dad6b70e5f ]--- This happens because the return value of read_mapping_page() is passed on to kmap unchecked. The bug is triggered after the first read_mapping_page() in hfsplus_block_allocate(), this patch fixes all three usages in this functions but leaves the ones further down in the file unchanged. Signed-off-by: Eric Sesterhenn <snakebyte@gmx.de> Cc: Roman Zippel <zippel@linux-m68k.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int lbs_process_bss(struct bss_descriptor *bss, uint8_t **pbeaconinfo, int *bytesleft) { struct ieeetypes_fhparamset *pFH; struct ieeetypes_dsparamset *pDS; struct ieeetypes_cfparamset *pCF; struct ieeetypes_ibssparamset *pibss; DECLARE_MAC_BUF(mac); struct ieeetypes_countryinfoset *pcountryinfo; uint8_t *pos, *end, *p; uint8_t n_ex_rates = 0, got_basic_rates = 0, n_basic_rates = 0; uint16_t beaconsize = 0; int ret; lbs_deb_enter(LBS_DEB_SCAN); if (*bytesleft >= sizeof(beaconsize)) { /* Extract & convert beacon size from the command buffer */ beaconsize = get_unaligned_le16(*pbeaconinfo); *bytesleft -= sizeof(beaconsize); *pbeaconinfo += sizeof(beaconsize); } if (beaconsize == 0 || beaconsize > *bytesleft) { *pbeaconinfo += *bytesleft; *bytesleft = 0; ret = -1; goto done; } /* Initialize the current working beacon pointer for this BSS iteration */ pos = *pbeaconinfo; end = pos + beaconsize; /* Advance the return beacon pointer past the current beacon */ *pbeaconinfo += beaconsize; *bytesleft -= beaconsize; memcpy(bss->bssid, pos, ETH_ALEN); lbs_deb_scan("process_bss: BSSID %s\n", print_mac(mac, bss->bssid)); pos += ETH_ALEN; if ((end - pos) < 12) { lbs_deb_scan("process_bss: Not enough bytes left\n"); ret = -1; goto done; } /* * next 4 fields are RSSI, time stamp, beacon interval, * and capability information */ /* RSSI is 1 byte long */ bss->rssi = *pos; lbs_deb_scan("process_bss: RSSI %d\n", *pos); pos++; /* time stamp is 8 bytes long */ pos += 8; /* beacon interval is 2 bytes long */ bss->beaconperiod = get_unaligned_le16(pos); pos += 2; /* capability information is 2 bytes long */ bss->capability = get_unaligned_le16(pos); lbs_deb_scan("process_bss: capabilities 0x%04x\n", bss->capability); pos += 2; if (bss->capability & WLAN_CAPABILITY_PRIVACY) lbs_deb_scan("process_bss: WEP enabled\n"); if (bss->capability & WLAN_CAPABILITY_IBSS) bss->mode = IW_MODE_ADHOC; else bss->mode = IW_MODE_INFRA; /* rest of the current buffer are IE's */ lbs_deb_scan("process_bss: IE len %zd\n", end - pos); lbs_deb_hex(LBS_DEB_SCAN, "process_bss: IE info", pos, end - pos); /* process variable IE */ while (pos <= end - 2) { struct ieee80211_info_element * elem = (void *)pos; if (pos + elem->len > end) { lbs_deb_scan("process_bss: error in processing IE, " "bytes left < IE length\n"); break; } switch (elem->id) { case MFIE_TYPE_SSID: bss->ssid_len = elem->len; memcpy(bss->ssid, elem->data, elem->len); lbs_deb_scan("got SSID IE: '%s', len %u\n", escape_essid(bss->ssid, bss->ssid_len), bss->ssid_len); break; case MFIE_TYPE_RATES: n_basic_rates = min_t(uint8_t, MAX_RATES, elem->len); memcpy(bss->rates, elem->data, n_basic_rates); got_basic_rates = 1; lbs_deb_scan("got RATES IE\n"); break; case MFIE_TYPE_FH_SET: pFH = (struct ieeetypes_fhparamset *) pos; memmove(&bss->phyparamset.fhparamset, pFH, sizeof(struct ieeetypes_fhparamset)); lbs_deb_scan("got FH IE\n"); break; case MFIE_TYPE_DS_SET: pDS = (struct ieeetypes_dsparamset *) pos; bss->channel = pDS->currentchan; memcpy(&bss->phyparamset.dsparamset, pDS, sizeof(struct ieeetypes_dsparamset)); lbs_deb_scan("got DS IE, channel %d\n", bss->channel); break; case MFIE_TYPE_CF_SET: pCF = (struct ieeetypes_cfparamset *) pos; memcpy(&bss->ssparamset.cfparamset, pCF, sizeof(struct ieeetypes_cfparamset)); lbs_deb_scan("got CF IE\n"); break; case MFIE_TYPE_IBSS_SET: pibss = (struct ieeetypes_ibssparamset *) pos; bss->atimwindow = le16_to_cpu(pibss->atimwindow); memmove(&bss->ssparamset.ibssparamset, pibss, sizeof(struct ieeetypes_ibssparamset)); lbs_deb_scan("got IBSS IE\n"); break; case MFIE_TYPE_COUNTRY: pcountryinfo = (struct ieeetypes_countryinfoset *) pos; lbs_deb_scan("got COUNTRY IE\n"); if (pcountryinfo->len < sizeof(pcountryinfo->countrycode) || pcountryinfo->len > 254) { lbs_deb_scan("process_bss: 11D- Err CountryInfo len %d, min %zd, max 254\n", pcountryinfo->len, sizeof(pcountryinfo->countrycode)); ret = -1; goto done; } memcpy(&bss->countryinfo, pcountryinfo, pcountryinfo->len + 2); lbs_deb_hex(LBS_DEB_SCAN, "process_bss: 11d countryinfo", (uint8_t *) pcountryinfo, (int) (pcountryinfo->len + 2)); break; case MFIE_TYPE_RATES_EX: /* only process extended supported rate if data rate is * already found. Data rate IE should come before * extended supported rate IE */ lbs_deb_scan("got RATESEX IE\n"); if (!got_basic_rates) { lbs_deb_scan("... but ignoring it\n"); break; } n_ex_rates = elem->len; if (n_basic_rates + n_ex_rates > MAX_RATES) n_ex_rates = MAX_RATES - n_basic_rates; p = bss->rates + n_basic_rates; memcpy(p, elem->data, n_ex_rates); break; case MFIE_TYPE_GENERIC: if (elem->len >= 4 && elem->data[0] == 0x00 && elem->data[1] == 0x50 && elem->data[2] == 0xf2 && elem->data[3] == 0x01) { bss->wpa_ie_len = min(elem->len + 2, MAX_WPA_IE_LEN); memcpy(bss->wpa_ie, elem, bss->wpa_ie_len); lbs_deb_scan("got WPA IE\n"); lbs_deb_hex(LBS_DEB_SCAN, "WPA IE", bss->wpa_ie, elem->len); } else if (elem->len >= MARVELL_MESH_IE_LENGTH && elem->data[0] == 0x00 && elem->data[1] == 0x50 && elem->data[2] == 0x43 && elem->data[3] == 0x04) { lbs_deb_scan("got mesh IE\n"); bss->mesh = 1; } else { lbs_deb_scan("got generic IE: %02x:%02x:%02x:%02x, len %d\n", elem->data[0], elem->data[1], elem->data[2], elem->data[3], elem->len); } break; case MFIE_TYPE_RSN: lbs_deb_scan("got RSN IE\n"); bss->rsn_ie_len = min(elem->len + 2, MAX_WPA_IE_LEN); memcpy(bss->rsn_ie, elem, bss->rsn_ie_len); lbs_deb_hex(LBS_DEB_SCAN, "process_bss: RSN_IE", bss->rsn_ie, elem->len); break; default: lbs_deb_scan("got IE 0x%04x, len %d\n", elem->id, elem->len); break; } pos += elem->len + 2; } /* Timestamp */ bss->last_scanned = jiffies; lbs_unset_basic_rate_flags(bss->rates, sizeof(bss->rates)); ret = 0; done: lbs_deb_leave_args(LBS_DEB_SCAN, "ret %d", ret); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'libertas: fix buffer overrun If somebody sends an invalid beacon/probe response, that can trash the whole BSS descriptor. The descriptor is, luckily, large enough so that it cannot scribble past the end of it; it's well above 400 bytes long. Signed-off-by: Johannes Berg <johannes@sipsolutions.net> Cc: stable@kernel.org [2.6.24-2.6.27, bug present in some form since driver was added (2.6.22)] Signed-off-by: John W. Linville <linville@tuxdriver.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int chip_command(struct i2c_client *client, unsigned int cmd, void *arg) { struct CHIPSTATE *chip = i2c_get_clientdata(client); struct CHIPDESC *desc = chip->desc; if (debug > 0) { v4l_i2c_print_ioctl(chip->c, cmd); printk("\n"); } switch (cmd) { case AUDC_SET_RADIO: chip->radio = 1; chip->watch_stereo = 0; /* del_timer(&chip->wt); */ break; /* --- v4l ioctls --- */ /* take care: bttv does userspace copying, we'll get a kernel pointer here... */ case VIDIOC_QUERYCTRL: { struct v4l2_queryctrl *qc = arg; switch (qc->id) { case V4L2_CID_AUDIO_MUTE: break; case V4L2_CID_AUDIO_VOLUME: case V4L2_CID_AUDIO_BALANCE: if (!(desc->flags & CHIP_HAS_VOLUME)) return -EINVAL; break; case V4L2_CID_AUDIO_BASS: case V4L2_CID_AUDIO_TREBLE: if (desc->flags & CHIP_HAS_BASSTREBLE) return -EINVAL; break; default: return -EINVAL; } return v4l2_ctrl_query_fill_std(qc); } case VIDIOC_S_CTRL: return tvaudio_set_ctrl(chip, arg); case VIDIOC_G_CTRL: return tvaudio_get_ctrl(chip, arg); case VIDIOC_INT_G_AUDIO_ROUTING: { struct v4l2_routing *rt = arg; rt->input = chip->input; rt->output = 0; break; } case VIDIOC_INT_S_AUDIO_ROUTING: { struct v4l2_routing *rt = arg; if (!(desc->flags & CHIP_HAS_INPUTSEL) || rt->input >= 4) return -EINVAL; /* There are four inputs: tuner, radio, extern and intern. */ chip->input = rt->input; if (chip->muted) break; chip_write_masked(chip, desc->inputreg, desc->inputmap[chip->input], desc->inputmask); break; } case VIDIOC_S_TUNER: { struct v4l2_tuner *vt = arg; int mode = 0; if (chip->radio) break; switch (vt->audmode) { case V4L2_TUNER_MODE_MONO: case V4L2_TUNER_MODE_STEREO: case V4L2_TUNER_MODE_LANG1: case V4L2_TUNER_MODE_LANG2: mode = vt->audmode; break; case V4L2_TUNER_MODE_LANG1_LANG2: mode = V4L2_TUNER_MODE_STEREO; break; default: return -EINVAL; } chip->audmode = vt->audmode; if (desc->setmode && mode) { chip->watch_stereo = 0; /* del_timer(&chip->wt); */ chip->mode = mode; desc->setmode(chip, mode); } break; } case VIDIOC_G_TUNER: { struct v4l2_tuner *vt = arg; int mode = V4L2_TUNER_MODE_MONO; if (chip->radio) break; vt->audmode = chip->audmode; vt->rxsubchans = 0; vt->capability = V4L2_TUNER_CAP_STEREO | V4L2_TUNER_CAP_LANG1 | V4L2_TUNER_CAP_LANG2; if (desc->getmode) mode = desc->getmode(chip); if (mode & V4L2_TUNER_MODE_MONO) vt->rxsubchans |= V4L2_TUNER_SUB_MONO; if (mode & V4L2_TUNER_MODE_STEREO) vt->rxsubchans |= V4L2_TUNER_SUB_STEREO; /* Note: for SAP it should be mono/lang2 or stereo/lang2. When this module is converted fully to v4l2, then this should change for those chips that can detect SAP. */ if (mode & V4L2_TUNER_MODE_LANG1) vt->rxsubchans = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2; break; } case VIDIOC_S_STD: chip->radio = 0; break; case VIDIOC_S_FREQUENCY: chip->mode = 0; /* automatic */ /* For chips that provide getmode and setmode, and doesn't automatically follows the stereo carrier, a kthread is created to set the audio standard. In this case, when then the video channel is changed, tvaudio starts on MONO mode. After waiting for 2 seconds, the kernel thread is called, to follow whatever audio standard is pointed by the audio carrier. */ if (chip->thread) { desc->setmode(chip,V4L2_TUNER_MODE_MONO); if (chip->prevmode != V4L2_TUNER_MODE_MONO) chip->prevmode = -1; /* reset previous mode */ mod_timer(&chip->wt, jiffies+msecs_to_jiffies(2000)); } break; case VIDIOC_G_CHIP_IDENT: return v4l2_chip_ident_i2c_client(client, arg, V4L2_IDENT_TVAUDIO, 0); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'V4L/DVB (9624): CVE-2008-5033: fix OOPS on tvaudio when controlling bass/treble This bug were supposed to be fixed by 5ba2f67afb02c5302b2898949ed6fc3b3d37dcf1, where a call to NULL happens. Not all tvaudio chips allow controlling bass/treble. So, the driver has a table with a flag to indicate if the chip does support it. Unfortunately, the handling of this logic were broken for a very long time (probably since the first module version). Due to that, an OOPS were generated for devices that don't support bass/treble. This were the resulting OOPS message before the patch, with debug messages enabled: tvaudio' 1-005b: VIDIOC_S_CTRL BUG: unable to handle kernel NULL pointer dereference at 00000000 IP: [<00000000>] *pde = 22fda067 *pte = 00000000 Oops: 0000 [#1] SMP Modules linked in: snd_hda_intel snd_seq_dummy snd_seq_oss snd_seq_midi_event snd_seq snd_seq_device snd_pcm_oss snd_mixer_oss snd_pcm snd_timer snd_hwdep snd soundcore tuner_simple tuner_types tea5767 tuner tvaudio bttv bridgebnep rfcomm l2cap bluetooth it87 hwmon_vid hwmon fuse sunrpc ipt_REJECT nf_conntrack_ipv4 iptable_filter ip_tables ip6t_REJECT xt_tcpudp nf_conntrack_ipv6 xt_state nf_conntrack ip6table_filter ip6_tables x_tables ipv6 dm_mirrordm_multipath dm_mod configfs videodev v4l1_compat ir_common 8139cp compat_ioctl32 v4l2_common 8139too videobuf_dma_sg videobuf_core mii btcx_risc tveeprom i915 button snd_page_alloc serio_raw drm pcspkr i2c_algo_bit i2c_i801 i2c_core iTCO_wdt iTCO_vendor_support sr_mod cdrom sg ata_generic pata_acpi ata_piix libata sd_mod scsi_mod ext3 jbdmbcache uhci_hcd ohci_hcd ehci_hcd [last unloaded: soundcore] Pid: 15413, comm: qv4l2 Not tainted (2.6.25.14-108.fc9.i686 #1) EIP: 0060:[<00000000>] EFLAGS: 00210246 CPU: 0 EIP is at 0x0 EAX: 00008000 EBX: ebd21600 ECX: e2fd9ec4 EDX: 00200046 ESI: f8c0f0c4 EDI: f8c0f0c4 EBP: e2fd9d50 ESP: e2fd9d2c DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068 Process qv4l2 (pid: 15413, ti=e2fd9000 task=ebe44000 task.ti=e2fd9000) Stack: f8c0c6ae e2ff2a00 00000d00 e2fd9ec4 ebc4e000 e2fd9d5c f8c0c448 00000000 f899c12a e2fd9d5c f899c154 e2fd9d68 e2fd9d80 c0560185 e2fd9d88 f8f3e1d8 f8f3e1dc ebc4e034 f8f3e18c e2fd9ec4 00000000 e2fd9d90 f899c286 c008561c Call Trace: [<f8c0c6ae>] ? chip_command+0x266/0x4b6 [tvaudio] [<f8c0c448>] ? chip_command+0x0/0x4b6 [tvaudio] [<f899c12a>] ? i2c_cmd+0x0/0x2f [i2c_core] [<f899c154>] ? i2c_cmd+0x2a/0x2f [i2c_core] [<c0560185>] ? device_for_each_child+0x21/0x49 [<f899c286>] ? i2c_clients_command+0x1c/0x1e [i2c_core] [<f8f283d8>] ? bttv_call_i2c_clients+0x14/0x16 [bttv] [<f8f23601>] ? bttv_s_ctrl+0x1bc/0x313 [bttv] [<f8f23445>] ? bttv_s_ctrl+0x0/0x313 [bttv] [<f8b6096d>] ? __video_do_ioctl+0x1f84/0x3726 [videodev] [<c05abb4e>] ? sock_aio_write+0x100/0x10d [<c041b23e>] ? kmap_atomic_prot+0x1dd/0x1df [<c043a0c9>] ? enqueue_hrtimer+0xc2/0xcd [<c04f4fa4>] ? copy_from_user+0x39/0x121 [<f8b622b9>] ? __video_ioctl2+0x1aa/0x24a [videodev] [<c04054fd>] ? do_notify_resume+0x768/0x795 [<c043c0f7>] ? getnstimeofday+0x34/0xd1 [<c0437b77>] ? autoremove_wake_function+0x0/0x33 [<f8b62368>] ? video_ioctl2+0xf/0x13 [videodev] [<c048c6f0>] ? vfs_ioctl+0x50/0x69 [<c048c942>] ? do_vfs_ioctl+0x239/0x24c [<c048c995>] ? sys_ioctl+0x40/0x5b [<c0405bf2>] ? syscall_call+0x7/0xb [<c0620000>] ? cpuid4_cache_sysfs_exit+0x3d/0x69 ======================= Code: Bad EIP value. EIP: [<00000000>] 0x0 SS:ESP 0068:e2fd9d2c Signed-off-by: Mauro Carvalho Chehab <mchehab@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void untag_chunk(struct audit_chunk *chunk, struct node *p) { struct audit_chunk *new; struct audit_tree *owner; int size = chunk->count - 1; int i, j; mutex_lock(&chunk->watch.inode->inotify_mutex); if (chunk->dead) { mutex_unlock(&chunk->watch.inode->inotify_mutex); return; } owner = p->owner; if (!size) { chunk->dead = 1; spin_lock(&hash_lock); list_del_init(&chunk->trees); if (owner->root == chunk) owner->root = NULL; list_del_init(&p->list); list_del_rcu(&chunk->hash); spin_unlock(&hash_lock); inotify_evict_watch(&chunk->watch); mutex_unlock(&chunk->watch.inode->inotify_mutex); put_inotify_watch(&chunk->watch); return; } new = alloc_chunk(size); if (!new) goto Fallback; if (inotify_clone_watch(&chunk->watch, &new->watch) < 0) { free_chunk(new); goto Fallback; } chunk->dead = 1; spin_lock(&hash_lock); list_replace_init(&chunk->trees, &new->trees); if (owner->root == chunk) { list_del_init(&owner->same_root); owner->root = NULL; } for (i = j = 0; i < size; i++, j++) { struct audit_tree *s; if (&chunk->owners[j] == p) { list_del_init(&p->list); i--; continue; } s = chunk->owners[j].owner; new->owners[i].owner = s; new->owners[i].index = chunk->owners[j].index - j + i; if (!s) /* result of earlier fallback */ continue; get_tree(s); list_replace_init(&chunk->owners[i].list, &new->owners[j].list); } list_replace_rcu(&chunk->hash, &new->hash); list_for_each_entry(owner, &new->trees, same_root) owner->root = new; spin_unlock(&hash_lock); inotify_evict_watch(&chunk->watch); mutex_unlock(&chunk->watch.inode->inotify_mutex); put_inotify_watch(&chunk->watch); return; Fallback: // do the best we can spin_lock(&hash_lock); if (owner->root == chunk) { list_del_init(&owner->same_root); owner->root = NULL; } list_del_init(&p->list); p->owner = NULL; put_tree(owner); spin_unlock(&hash_lock); mutex_unlock(&chunk->watch.inode->inotify_mutex); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races Inotify watch removals suck violently. To kick the watch out we need (in this order) inode->inotify_mutex and ih->mutex. That's fine if we have a hold on inode; however, for all other cases we need to make damn sure we don't race with umount. We can *NOT* just grab a reference to a watch - inotify_unmount_inodes() will happily sail past it and we'll end with reference to inode potentially outliving its superblock. Ideally we just want to grab an active reference to superblock if we can; that will make sure we won't go into inotify_umount_inodes() until we are done. Cleanup is just deactivate_super(). However, that leaves a messy case - what if we *are* racing with umount() and active references to superblock can't be acquired anymore? We can bump ->s_count, grab ->s_umount, which will almost certainly wait until the superblock is shut down and the watch in question is pining for fjords. That's fine, but there is a problem - we might have hit the window between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e. the moment when superblock is past the point of no return and is heading for shutdown) and the moment when deactivate_super() acquires ->s_umount. We could just do drop_super() yield() and retry, but that's rather antisocial and this stuff is luser-triggerable. OTOH, having grabbed ->s_umount and having found that we'd got there first (i.e. that ->s_root is non-NULL) we know that we won't race with inotify_umount_inodes(). So we could grab a reference to watch and do the rest as above, just with drop_super() instead of deactivate_super(), right? Wrong. We had to drop ih->mutex before we could grab ->s_umount. So the watch could've been gone already. That still can be dealt with - we need to save watch->wd, do idr_find() and compare its result with our pointer. If they match, we either have the damn thing still alive or we'd lost not one but two races at once, the watch had been killed and a new one got created with the same ->wd at the same address. That couldn't have happened in inotify_destroy(), but inotify_rm_wd() could run into that. Still, "new one got created" is not a problem - we have every right to kill it or leave it alone, whatever's more convenient. So we can use idr_find(...) == watch && watch->inode->i_sb == sb as "grab it and kill it" check. If it's been our original watch, we are fine, if it's a newcomer - nevermind, just pretend that we'd won the race and kill the fscker anyway; we are safe since we know that its superblock won't be going away. And yes, this is far beyond mere "not very pretty"; so's the entire concept of inotify to start with. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Acked-by: Greg KH <greg@kroah.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline void free_chunk(struct audit_chunk *chunk) { call_rcu(&chunk->head, __free_chunk); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races Inotify watch removals suck violently. To kick the watch out we need (in this order) inode->inotify_mutex and ih->mutex. That's fine if we have a hold on inode; however, for all other cases we need to make damn sure we don't race with umount. We can *NOT* just grab a reference to a watch - inotify_unmount_inodes() will happily sail past it and we'll end with reference to inode potentially outliving its superblock. Ideally we just want to grab an active reference to superblock if we can; that will make sure we won't go into inotify_umount_inodes() until we are done. Cleanup is just deactivate_super(). However, that leaves a messy case - what if we *are* racing with umount() and active references to superblock can't be acquired anymore? We can bump ->s_count, grab ->s_umount, which will almost certainly wait until the superblock is shut down and the watch in question is pining for fjords. That's fine, but there is a problem - we might have hit the window between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e. the moment when superblock is past the point of no return and is heading for shutdown) and the moment when deactivate_super() acquires ->s_umount. We could just do drop_super() yield() and retry, but that's rather antisocial and this stuff is luser-triggerable. OTOH, having grabbed ->s_umount and having found that we'd got there first (i.e. that ->s_root is non-NULL) we know that we won't race with inotify_umount_inodes(). So we could grab a reference to watch and do the rest as above, just with drop_super() instead of deactivate_super(), right? Wrong. We had to drop ih->mutex before we could grab ->s_umount. So the watch could've been gone already. That still can be dealt with - we need to save watch->wd, do idr_find() and compare its result with our pointer. If they match, we either have the damn thing still alive or we'd lost not one but two races at once, the watch had been killed and a new one got created with the same ->wd at the same address. That couldn't have happened in inotify_destroy(), but inotify_rm_wd() could run into that. Still, "new one got created" is not a problem - we have every right to kill it or leave it alone, whatever's more convenient. So we can use idr_find(...) == watch && watch->inode->i_sb == sb as "grab it and kill it" check. If it's been our original watch, we are fine, if it's a newcomer - nevermind, just pretend that we'd won the race and kill the fscker anyway; we are safe since we know that its superblock won't be going away. And yes, this is far beyond mere "not very pretty"; so's the entire concept of inotify to start with. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Acked-by: Greg KH <greg@kroah.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: struct audit_chunk *audit_tree_lookup(const struct inode *inode) { struct list_head *list = chunk_hash(inode); struct audit_chunk *p; list_for_each_entry_rcu(p, list, hash) { if (p->watch.inode == inode) { get_inotify_watch(&p->watch); return p; } } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races Inotify watch removals suck violently. To kick the watch out we need (in this order) inode->inotify_mutex and ih->mutex. That's fine if we have a hold on inode; however, for all other cases we need to make damn sure we don't race with umount. We can *NOT* just grab a reference to a watch - inotify_unmount_inodes() will happily sail past it and we'll end with reference to inode potentially outliving its superblock. Ideally we just want to grab an active reference to superblock if we can; that will make sure we won't go into inotify_umount_inodes() until we are done. Cleanup is just deactivate_super(). However, that leaves a messy case - what if we *are* racing with umount() and active references to superblock can't be acquired anymore? We can bump ->s_count, grab ->s_umount, which will almost certainly wait until the superblock is shut down and the watch in question is pining for fjords. That's fine, but there is a problem - we might have hit the window between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e. the moment when superblock is past the point of no return and is heading for shutdown) and the moment when deactivate_super() acquires ->s_umount. We could just do drop_super() yield() and retry, but that's rather antisocial and this stuff is luser-triggerable. OTOH, having grabbed ->s_umount and having found that we'd got there first (i.e. that ->s_root is non-NULL) we know that we won't race with inotify_umount_inodes(). So we could grab a reference to watch and do the rest as above, just with drop_super() instead of deactivate_super(), right? Wrong. We had to drop ih->mutex before we could grab ->s_umount. So the watch could've been gone already. That still can be dealt with - we need to save watch->wd, do idr_find() and compare its result with our pointer. If they match, we either have the damn thing still alive or we'd lost not one but two races at once, the watch had been killed and a new one got created with the same ->wd at the same address. That couldn't have happened in inotify_destroy(), but inotify_rm_wd() could run into that. Still, "new one got created" is not a problem - we have every right to kill it or leave it alone, whatever's more convenient. So we can use idr_find(...) == watch && watch->inode->i_sb == sb as "grab it and kill it" check. If it's been our original watch, we are fine, if it's a newcomer - nevermind, just pretend that we'd won the race and kill the fscker anyway; we are safe since we know that its superblock won't be going away. And yes, this is far beyond mere "not very pretty"; so's the entire concept of inotify to start with. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Acked-by: Greg KH <greg@kroah.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline int audit_del_rule(struct audit_entry *entry, struct list_head *list) { struct audit_entry *e; struct audit_field *inode_f = entry->rule.inode_f; struct audit_watch *watch, *tmp_watch = entry->rule.watch; struct audit_tree *tree = entry->rule.tree; LIST_HEAD(inotify_list); int h, ret = 0; #ifdef CONFIG_AUDITSYSCALL int dont_count = 0; /* If either of these, don't count towards total */ if (entry->rule.listnr == AUDIT_FILTER_USER || entry->rule.listnr == AUDIT_FILTER_TYPE) dont_count = 1; #endif if (inode_f) { h = audit_hash_ino(inode_f->val); list = &audit_inode_hash[h]; } mutex_lock(&audit_filter_mutex); e = audit_find_rule(entry, list); if (!e) { mutex_unlock(&audit_filter_mutex); ret = -ENOENT; goto out; } watch = e->rule.watch; if (watch) { struct audit_parent *parent = watch->parent; list_del(&e->rule.rlist); if (list_empty(&watch->rules)) { audit_remove_watch(watch); if (list_empty(&parent->watches)) { /* Put parent on the inotify un-registration * list. Grab a reference before releasing * audit_filter_mutex, to be released in * audit_inotify_unregister(). */ list_add(&parent->ilist, &inotify_list); get_inotify_watch(&parent->wdata); } } } if (e->rule.tree) audit_remove_tree_rule(&e->rule); list_del_rcu(&e->list); call_rcu(&e->rcu, audit_free_rule_rcu); #ifdef CONFIG_AUDITSYSCALL if (!dont_count) audit_n_rules--; if (!audit_match_signal(entry)) audit_signals--; #endif mutex_unlock(&audit_filter_mutex); if (!list_empty(&inotify_list)) audit_inotify_unregister(&inotify_list); out: if (tmp_watch) audit_put_watch(tmp_watch); /* match initial get */ if (tree) audit_put_tree(tree); /* that's the temporary one */ return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races Inotify watch removals suck violently. To kick the watch out we need (in this order) inode->inotify_mutex and ih->mutex. That's fine if we have a hold on inode; however, for all other cases we need to make damn sure we don't race with umount. We can *NOT* just grab a reference to a watch - inotify_unmount_inodes() will happily sail past it and we'll end with reference to inode potentially outliving its superblock. Ideally we just want to grab an active reference to superblock if we can; that will make sure we won't go into inotify_umount_inodes() until we are done. Cleanup is just deactivate_super(). However, that leaves a messy case - what if we *are* racing with umount() and active references to superblock can't be acquired anymore? We can bump ->s_count, grab ->s_umount, which will almost certainly wait until the superblock is shut down and the watch in question is pining for fjords. That's fine, but there is a problem - we might have hit the window between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e. the moment when superblock is past the point of no return and is heading for shutdown) and the moment when deactivate_super() acquires ->s_umount. We could just do drop_super() yield() and retry, but that's rather antisocial and this stuff is luser-triggerable. OTOH, having grabbed ->s_umount and having found that we'd got there first (i.e. that ->s_root is non-NULL) we know that we won't race with inotify_umount_inodes(). So we could grab a reference to watch and do the rest as above, just with drop_super() instead of deactivate_super(), right? Wrong. We had to drop ih->mutex before we could grab ->s_umount. So the watch could've been gone already. That still can be dealt with - we need to save watch->wd, do idr_find() and compare its result with our pointer. If they match, we either have the damn thing still alive or we'd lost not one but two races at once, the watch had been killed and a new one got created with the same ->wd at the same address. That couldn't have happened in inotify_destroy(), but inotify_rm_wd() could run into that. Still, "new one got created" is not a problem - we have every right to kill it or leave it alone, whatever's more convenient. So we can use idr_find(...) == watch && watch->inode->i_sb == sb as "grab it and kill it" check. If it's been our original watch, we are fine, if it's a newcomer - nevermind, just pretend that we'd won the race and kill the fscker anyway; we are safe since we know that its superblock won't be going away. And yes, this is far beyond mere "not very pretty"; so's the entire concept of inotify to start with. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Acked-by: Greg KH <greg@kroah.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct audit_chunk *alloc_chunk(int count) { struct audit_chunk *chunk; size_t size; int i; size = offsetof(struct audit_chunk, owners) + count * sizeof(struct node); chunk = kzalloc(size, GFP_KERNEL); if (!chunk) return NULL; INIT_LIST_HEAD(&chunk->hash); INIT_LIST_HEAD(&chunk->trees); chunk->count = count; for (i = 0; i < count; i++) { INIT_LIST_HEAD(&chunk->owners[i].list); chunk->owners[i].index = i; } inotify_init_watch(&chunk->watch); return chunk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races Inotify watch removals suck violently. To kick the watch out we need (in this order) inode->inotify_mutex and ih->mutex. That's fine if we have a hold on inode; however, for all other cases we need to make damn sure we don't race with umount. We can *NOT* just grab a reference to a watch - inotify_unmount_inodes() will happily sail past it and we'll end with reference to inode potentially outliving its superblock. Ideally we just want to grab an active reference to superblock if we can; that will make sure we won't go into inotify_umount_inodes() until we are done. Cleanup is just deactivate_super(). However, that leaves a messy case - what if we *are* racing with umount() and active references to superblock can't be acquired anymore? We can bump ->s_count, grab ->s_umount, which will almost certainly wait until the superblock is shut down and the watch in question is pining for fjords. That's fine, but there is a problem - we might have hit the window between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e. the moment when superblock is past the point of no return and is heading for shutdown) and the moment when deactivate_super() acquires ->s_umount. We could just do drop_super() yield() and retry, but that's rather antisocial and this stuff is luser-triggerable. OTOH, having grabbed ->s_umount and having found that we'd got there first (i.e. that ->s_root is non-NULL) we know that we won't race with inotify_umount_inodes(). So we could grab a reference to watch and do the rest as above, just with drop_super() instead of deactivate_super(), right? Wrong. We had to drop ih->mutex before we could grab ->s_umount. So the watch could've been gone already. That still can be dealt with - we need to save watch->wd, do idr_find() and compare its result with our pointer. If they match, we either have the damn thing still alive or we'd lost not one but two races at once, the watch had been killed and a new one got created with the same ->wd at the same address. That couldn't have happened in inotify_destroy(), but inotify_rm_wd() could run into that. Still, "new one got created" is not a problem - we have every right to kill it or leave it alone, whatever's more convenient. So we can use idr_find(...) == watch && watch->inode->i_sb == sb as "grab it and kill it" check. If it's been our original watch, we are fine, if it's a newcomer - nevermind, just pretend that we'd won the race and kill the fscker anyway; we are safe since we know that its superblock won't be going away. And yes, this is far beyond mere "not very pretty"; so's the entire concept of inotify to start with. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Acked-by: Greg KH <greg@kroah.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct audit_chunk *find_chunk(struct node *p) { int index = p->index & ~(1U<<31); p -= index; return container_of(p, struct audit_chunk, owners[0]); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races Inotify watch removals suck violently. To kick the watch out we need (in this order) inode->inotify_mutex and ih->mutex. That's fine if we have a hold on inode; however, for all other cases we need to make damn sure we don't race with umount. We can *NOT* just grab a reference to a watch - inotify_unmount_inodes() will happily sail past it and we'll end with reference to inode potentially outliving its superblock. Ideally we just want to grab an active reference to superblock if we can; that will make sure we won't go into inotify_umount_inodes() until we are done. Cleanup is just deactivate_super(). However, that leaves a messy case - what if we *are* racing with umount() and active references to superblock can't be acquired anymore? We can bump ->s_count, grab ->s_umount, which will almost certainly wait until the superblock is shut down and the watch in question is pining for fjords. That's fine, but there is a problem - we might have hit the window between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e. the moment when superblock is past the point of no return and is heading for shutdown) and the moment when deactivate_super() acquires ->s_umount. We could just do drop_super() yield() and retry, but that's rather antisocial and this stuff is luser-triggerable. OTOH, having grabbed ->s_umount and having found that we'd got there first (i.e. that ->s_root is non-NULL) we know that we won't race with inotify_umount_inodes(). So we could grab a reference to watch and do the rest as above, just with drop_super() instead of deactivate_super(), right? Wrong. We had to drop ih->mutex before we could grab ->s_umount. So the watch could've been gone already. That still can be dealt with - we need to save watch->wd, do idr_find() and compare its result with our pointer. If they match, we either have the damn thing still alive or we'd lost not one but two races at once, the watch had been killed and a new one got created with the same ->wd at the same address. That couldn't have happened in inotify_destroy(), but inotify_rm_wd() could run into that. Still, "new one got created" is not a problem - we have every right to kill it or leave it alone, whatever's more convenient. So we can use idr_find(...) == watch && watch->inode->i_sb == sb as "grab it and kill it" check. If it's been our original watch, we are fine, if it's a newcomer - nevermind, just pretend that we'd won the race and kill the fscker anyway; we are safe since we know that its superblock won't be going away. And yes, this is far beyond mere "not very pretty"; so's the entire concept of inotify to start with. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Acked-by: Greg KH <greg@kroah.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void __free_chunk(struct rcu_head *rcu) { struct audit_chunk *chunk = container_of(rcu, struct audit_chunk, head); int i; for (i = 0; i < chunk->count; i++) { if (chunk->owners[i].owner) put_tree(chunk->owners[i].owner); } kfree(chunk); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix inotify watch removal/umount races Inotify watch removals suck violently. To kick the watch out we need (in this order) inode->inotify_mutex and ih->mutex. That's fine if we have a hold on inode; however, for all other cases we need to make damn sure we don't race with umount. We can *NOT* just grab a reference to a watch - inotify_unmount_inodes() will happily sail past it and we'll end with reference to inode potentially outliving its superblock. Ideally we just want to grab an active reference to superblock if we can; that will make sure we won't go into inotify_umount_inodes() until we are done. Cleanup is just deactivate_super(). However, that leaves a messy case - what if we *are* racing with umount() and active references to superblock can't be acquired anymore? We can bump ->s_count, grab ->s_umount, which will almost certainly wait until the superblock is shut down and the watch in question is pining for fjords. That's fine, but there is a problem - we might have hit the window between ->s_active getting to 0 / ->s_count - below S_BIAS (i.e. the moment when superblock is past the point of no return and is heading for shutdown) and the moment when deactivate_super() acquires ->s_umount. We could just do drop_super() yield() and retry, but that's rather antisocial and this stuff is luser-triggerable. OTOH, having grabbed ->s_umount and having found that we'd got there first (i.e. that ->s_root is non-NULL) we know that we won't race with inotify_umount_inodes(). So we could grab a reference to watch and do the rest as above, just with drop_super() instead of deactivate_super(), right? Wrong. We had to drop ih->mutex before we could grab ->s_umount. So the watch could've been gone already. That still can be dealt with - we need to save watch->wd, do idr_find() and compare its result with our pointer. If they match, we either have the damn thing still alive or we'd lost not one but two races at once, the watch had been killed and a new one got created with the same ->wd at the same address. That couldn't have happened in inotify_destroy(), but inotify_rm_wd() could run into that. Still, "new one got created" is not a problem - we have every right to kill it or leave it alone, whatever's more convenient. So we can use idr_find(...) == watch && watch->inode->i_sb == sb as "grab it and kill it" check. If it's been our original watch, we are fine, if it's a newcomer - nevermind, just pretend that we'd won the race and kill the fscker anyway; we are safe since we know that its superblock won't be going away. And yes, this is far beyond mere "not very pretty"; so's the entire concept of inotify to start with. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Acked-by: Greg KH <greg@kroah.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void unix_gc(void) { static bool gc_in_progress = false; struct unix_sock *u; struct unix_sock *next; struct sk_buff_head hitlist; struct list_head cursor; LIST_HEAD(not_cycle_list); spin_lock(&unix_gc_lock); /* Avoid a recursive GC. */ if (gc_in_progress) goto out; gc_in_progress = true; /* * First, select candidates for garbage collection. Only * in-flight sockets are considered, and from those only ones * which don't have any external reference. * * Holding unix_gc_lock will protect these candidates from * being detached, and hence from gaining an external * reference. Since there are no possible receivers, all * buffers currently on the candidates' queues stay there * during the garbage collection. * * We also know that no new candidate can be added onto the * receive queues. Other, non candidate sockets _can_ be * added to queue, so we must make sure only to touch * candidates. */ list_for_each_entry_safe(u, next, &gc_inflight_list, link) { long total_refs; long inflight_refs; total_refs = file_count(u->sk.sk_socket->file); inflight_refs = atomic_long_read(&u->inflight); BUG_ON(inflight_refs < 1); BUG_ON(total_refs < inflight_refs); if (total_refs == inflight_refs) { list_move_tail(&u->link, &gc_candidates); u->gc_candidate = 1; u->gc_maybe_cycle = 1; } } /* * Now remove all internal in-flight reference to children of * the candidates. */ list_for_each_entry(u, &gc_candidates, link) scan_children(&u->sk, dec_inflight, NULL); /* * Restore the references for children of all candidates, * which have remaining references. Do this recursively, so * only those remain, which form cyclic references. * * Use a "cursor" link, to make the list traversal safe, even * though elements might be moved about. */ list_add(&cursor, &gc_candidates); while (cursor.next != &gc_candidates) { u = list_entry(cursor.next, struct unix_sock, link); /* Move cursor to after the current position. */ list_move(&cursor, &u->link); if (atomic_long_read(&u->inflight) > 0) { list_move_tail(&u->link, &not_cycle_list); u->gc_maybe_cycle = 0; scan_children(&u->sk, inc_inflight_move_tail, NULL); } } list_del(&cursor); /* * not_cycle_list contains those sockets which do not make up a * cycle. Restore these to the inflight list. */ while (!list_empty(&not_cycle_list)) { u = list_entry(not_cycle_list.next, struct unix_sock, link); u->gc_candidate = 0; list_move_tail(&u->link, &gc_inflight_list); } /* * Now gc_candidates contains only garbage. Restore original * inflight counters for these as well, and remove the skbuffs * which are creating the cycle(s). */ skb_queue_head_init(&hitlist); list_for_each_entry(u, &gc_candidates, link) scan_children(&u->sk, inc_inflight, &hitlist); spin_unlock(&unix_gc_lock); /* Here we are. Hitlist is filled. Die. */ __skb_queue_purge(&hitlist); spin_lock(&unix_gc_lock); /* All candidates should have been detached by now. */ BUG_ON(!list_empty(&gc_candidates)); gc_in_progress = false; out: spin_unlock(&unix_gc_lock); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'net: Fix soft lockups/OOM issues w/ unix garbage collector This is an implementation of David Miller's suggested fix in: https://bugzilla.redhat.com/show_bug.cgi?id=470201 It has been updated to use wait_event() instead of wait_event_interruptible(). Paraphrasing the description from the above report, it makes sendmsg() block while UNIX garbage collection is in progress. This avoids a situation where child processes continue to queue new FDs over a AF_UNIX socket to a parent which is in the exit path and running garbage collection on these FDs. This contention can result in soft lockups and oom-killing of unrelated processes. Signed-off-by: dann frazier <dannf@hp.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int svc_listen(struct socket *sock,int backlog) { DEFINE_WAIT(wait); struct sock *sk = sock->sk; struct atm_vcc *vcc = ATM_SD(sock); int error; pr_debug("svc_listen %p\n",vcc); lock_sock(sk); /* let server handle listen on unbound sockets */ if (test_bit(ATM_VF_SESSION,&vcc->flags)) { error = -EINVAL; goto out; } vcc_insert_socket(sk); set_bit(ATM_VF_WAITING, &vcc->flags); prepare_to_wait(sk->sk_sleep, &wait, TASK_UNINTERRUPTIBLE); sigd_enq(vcc,as_listen,NULL,NULL,&vcc->local); while (test_bit(ATM_VF_WAITING, &vcc->flags) && sigd) { schedule(); prepare_to_wait(sk->sk_sleep, &wait, TASK_UNINTERRUPTIBLE); } finish_wait(sk->sk_sleep, &wait); if (!sigd) { error = -EUNATCH; goto out; } set_bit(ATM_VF_LISTEN,&vcc->flags); sk->sk_max_ack_backlog = backlog > 0 ? backlog : ATM_BACKLOG_DEFAULT; error = -sk->sk_err; out: release_sock(sk); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'ATM: CVE-2008-5079: duplicate listen() on socket corrupts the vcc table As reported by Hugo Dias that it is possible to cause a local denial of service attack by calling the svc_listen function twice on the same socket and reading /proc/net/atm/*vc Signed-off-by: Chas Williams <chas@cmf.nrl.navy.mil> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int blk_fill_sgv4_hdr_rq(struct request_queue *q, struct request *rq, struct sg_io_v4 *hdr, struct bsg_device *bd, fmode_t has_write_perm) { if (hdr->request_len > BLK_MAX_CDB) { rq->cmd = kzalloc(hdr->request_len, GFP_KERNEL); if (!rq->cmd) return -ENOMEM; } if (copy_from_user(rq->cmd, (void *)(unsigned long)hdr->request, hdr->request_len)) return -EFAULT; if (hdr->subprotocol == BSG_SUB_PROTOCOL_SCSI_CMD) { if (blk_verify_command(&q->cmd_filter, rq->cmd, has_write_perm)) return -EPERM; } else if (!capable(CAP_SYS_RAWIO)) return -EPERM; /* * fill in request structure */ rq->cmd_len = hdr->request_len; rq->cmd_type = REQ_TYPE_BLOCK_PC; rq->timeout = (hdr->timeout * HZ) / 1000; if (!rq->timeout) rq->timeout = q->sg_timeout; if (!rq->timeout) rq->timeout = BLK_DEFAULT_SG_TIMEOUT; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Enforce a minimum SG_IO timeout There's no point in having too short SG_IO timeouts, since if the command does end up timing out, we'll end up through the reset sequence that is several seconds long in order to abort the command that timed out. As a result, shorter timeouts than a few seconds simply do not make sense, as the recovery would be longer than the timeout itself. Add a BLK_MIN_SG_TIMEOUT to match the existign BLK_DEFAULT_SG_TIMEOUT. Suggested-by: Alan Cox <alan@lxorguk.ukuu.org.uk> Acked-by: Tejun Heo <tj@kernel.org> Acked-by: Jens Axboe <jens.axboe@oracle.com> Cc: Jeff Garzik <jeff@garzik.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void dispatch_packet(AvahiServer *s, AvahiDnsPacket *p, const AvahiAddress *src_address, uint16_t port, const AvahiAddress *dst_address, AvahiIfIndex iface, int ttl) { AvahiInterface *i; int from_local_iface = 0; assert(s); assert(p); assert(src_address); assert(dst_address); assert(iface > 0); assert(src_address->proto == dst_address->proto); if (!(i = avahi_interface_monitor_get_interface(s->monitor, iface, src_address->proto)) || !i->announcing) { avahi_log_warn("Received packet from invalid interface."); return; } if (avahi_address_is_ipv4_in_ipv6(src_address)) /* This is an IPv4 address encapsulated in IPv6, so let's ignore it. */ return; if (originates_from_local_legacy_unicast_socket(s, src_address, port)) /* This originates from our local reflector, so let's ignore it */ return; /* We don't want to reflect local traffic, so we check if this packet is generated locally. */ if (s->config.enable_reflector) from_local_iface = originates_from_local_iface(s, iface, src_address, port); if (avahi_dns_packet_check_valid_multicast(p) < 0) { avahi_log_warn("Received invalid packet."); return; } if (avahi_dns_packet_is_query(p)) { int legacy_unicast = 0; if (avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ARCOUNT) != 0) { avahi_log_warn("Invalid query packet."); return; } if (port != AVAHI_MDNS_PORT) { /* Legacy Unicast */ if ((avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT) != 0 || avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_NSCOUNT) != 0)) { avahi_log_warn("Invalid legacy unicast query packet."); return; } legacy_unicast = 1; } if (legacy_unicast) reflect_legacy_unicast_query_packet(s, p, i, src_address, port); handle_query_packet(s, p, i, src_address, port, legacy_unicast, from_local_iface); } else { char t[AVAHI_ADDRESS_STR_MAX]; if (port != AVAHI_MDNS_PORT) { avahi_log_warn("Received response from host %s with invalid source port %u on interface '%s.%i'", avahi_address_snprint(t, sizeof(t), src_address), port, i->hardware->name, i->protocol); return; } if (ttl != 255 && s->config.check_response_ttl) { avahi_log_warn("Received response from host %s with invalid TTL %u on interface '%s.%i'.", avahi_address_snprint(t, sizeof(t), src_address), ttl, i->hardware->name, i->protocol); return; } if (!is_mdns_mcast_address(dst_address) && !avahi_interface_address_on_link(i, src_address)) { avahi_log_warn("Received non-local response from host %s on interface '%s.%i'.", avahi_address_snprint(t, sizeof(t), src_address), i->hardware->name, i->protocol); return; } if (avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_QDCOUNT) != 0 || avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_ANCOUNT) == 0 || avahi_dns_packet_get_field(p, AVAHI_DNS_FIELD_NSCOUNT) != 0) { avahi_log_warn("Invalid response packet from host %s.", avahi_address_snprint(t, sizeof(t), src_address)); return; } handle_response_packet(s, p, i, src_address, from_local_iface); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Don't get confused by UDP packets with a source port that is zero This is a fix for rhbz 475394. Problem identified by Hugo Dias.'</s>