text
stringlengths
481
107k
<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_do_copy(CirrusVGAState *s, int dst, int src, int w, int h) { int sx, sy; int dx, dy; int width, height; int depth; int notify = 0; depth = s->get_bpp((VGAState *)s) / 8; s->get_resolution((VGAState *)s, &width, &height); /* extra x, y */ sx = (src % (width * depth)) / depth; sy = (src / (width * depth)); dx = (dst % (width *depth)) / depth; dy = (dst / (width * depth)); /* normalize width */ w /= depth; /* if we're doing a backward copy, we have to adjust our x/y to be the upper left corner (instead of the lower right corner) */ if (s->cirrus_blt_dstpitch < 0) { sx -= (s->cirrus_blt_width / depth) - 1; dx -= (s->cirrus_blt_width / depth) - 1; sy -= s->cirrus_blt_height - 1; dy -= s->cirrus_blt_height - 1; } /* are we in the visible portion of memory? */ if (sx >= 0 && sy >= 0 && dx >= 0 && dy >= 0 && (sx + w) <= width && (sy + h) <= height && (dx + w) <= width && (dy + h) <= height) { notify = 1; } /* make to sure only copy if it's a plain copy ROP */ if (*s->cirrus_rop != cirrus_bitblt_rop_fwd_src && *s->cirrus_rop != cirrus_bitblt_rop_bkwd_src) notify = 0; /* we have to flush all pending changes so that the copy is generated at the appropriate moment in time */ if (notify) vga_hw_update(); (*s->cirrus_rop) (s, s->vram_ptr + s->cirrus_blt_dstaddr, s->vram_ptr + s->cirrus_blt_srcaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_srcpitch, s->cirrus_blt_width, s->cirrus_blt_height); if (notify) s->ds->dpy_copy(s->ds, sx, sy, dx, dy, s->cirrus_blt_width / depth, s->cirrus_blt_height); /* we don't have to notify the display that this portion has changed since dpy_copy implies this */ if (!notify) cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); } ; 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_videotovideo_copy(CirrusVGAState * s) { if (s->ds->dpy_copy) { cirrus_do_copy(s, s->cirrus_blt_dstaddr - s->start_addr, s->cirrus_blt_srcaddr - s->start_addr, s->cirrus_blt_width, s->cirrus_blt_height); } else { if (BLTUNSAFE(s)) return 0; (*s->cirrus_rop) (s, s->vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask), s->vram_ptr + (s->cirrus_blt_srcaddr & s->cirrus_addr_mask), s->cirrus_blt_dstpitch, s->cirrus_blt_srcpitch, 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); } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2008-4539: fix a heap overflow in Cirrus emulation The code in hw/cirrus_vga.c has changed a lot between CVE-2007-1320 has been announced and the patch has been applied. As a consequence it has wrongly applied and QEMU is still vulnerable to this bug if using VNC. (noticed by Jan Niehusmann) Signed-off-by: Aurelien Jarno <aurelien@aurel32.net> git-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@5587 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 putreg(struct task_struct *child, unsigned long regno, unsigned long value) { unsigned long tmp; /* Some code in the 64bit emulation may not be 64bit clean. Don't take any chances. */ if (test_tsk_thread_flag(child, TIF_IA32)) value &= 0xffffffff; switch (regno) { case offsetof(struct user_regs_struct,fs): if (value && (value & 3) != 3) return -EIO; child->thread.fsindex = value & 0xffff; return 0; case offsetof(struct user_regs_struct,gs): if (value && (value & 3) != 3) return -EIO; child->thread.gsindex = value & 0xffff; return 0; case offsetof(struct user_regs_struct,ds): if (value && (value & 3) != 3) return -EIO; child->thread.ds = value & 0xffff; return 0; case offsetof(struct user_regs_struct,es): if (value && (value & 3) != 3) return -EIO; child->thread.es = value & 0xffff; return 0; case offsetof(struct user_regs_struct,ss): if ((value & 3) != 3) return -EIO; value &= 0xffff; return 0; case offsetof(struct user_regs_struct,fs_base): if (value >= TASK_SIZE_OF(child)) return -EIO; child->thread.fs = value; return 0; case offsetof(struct user_regs_struct,gs_base): if (value >= TASK_SIZE_OF(child)) return -EIO; child->thread.gs = value; return 0; case offsetof(struct user_regs_struct, eflags): value &= FLAG_MASK; tmp = get_stack_long(child, EFL_OFFSET); tmp &= ~FLAG_MASK; value |= tmp; break; case offsetof(struct user_regs_struct,cs): if ((value & 3) != 3) return -EIO; value &= 0xffff; break; } put_stack_long(child, regno - sizeof(struct pt_regs), value); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'x86_64: Zero extend all registers after ptrace in 32bit entry path. Strictly it's only needed for eax. It actually does a little more than strictly needed -- the other registers are already zero extended. Also remove the now unnecessary and non functional compat task check in ptrace. This is CVE-2007-4573 Found by Wojciech Purczynski Signed-off-by: Andi Kleen <ak@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: ProcShmCreatePixmap(client) register ClientPtr client; { PixmapPtr pMap; DrawablePtr pDraw; DepthPtr pDepth; register int i, rc; ShmDescPtr shmdesc; REQUEST(xShmCreatePixmapReq); unsigned int width, height, depth; unsigned long size; 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, DixGetAttrAccess); 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); pMap = (*shmFuncs[pDraw->pScreen->myNum]->CreatePixmap)( pDraw->pScreen, stuff->width, stuff->height, stuff->depth, shmdesc->addr + stuff->offset); if (pMap) { rc = XaceHook(XACE_RESOURCE_ACCESS, client, stuff->pid, RT_PIXMAP, pMap, RT_NONE, NULL, DixCreateAccess); if (rc != Success) { pDraw->pScreen->DestroyPixmap(pMap); return rc; } dixSetPrivate(&pMap->devPrivates, shmPixmapPrivate, shmdesc); shmdesc->refcnt++; pMap->drawable.serialNumber = NEXT_SERIAL_NUMBER; pMap->drawable.id = stuff->pid; if (AddResource(stuff->pid, RT_PIXMAP, (pointer)pMap)) { return(client->noClientException); } pDraw->pScreen->DestroyPixmap(pMap); } return (BadAlloc); } ; 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: int ia32_setup_frame(int sig, struct k_sigaction *ka, compat_sigset_t *set, struct pt_regs *regs) { struct sigframe __user *frame; void __user *restorer; int err = 0; /* copy_to_user optimizes that into a single 8 byte store */ static const struct { u16 poplmovl; u32 val; u16 int80; u16 pad; } __attribute__((packed)) code = { 0xb858, /* popl %eax ; movl $...,%eax */ __NR_ia32_sigreturn, 0x80cd, /* int $0x80 */ 0, }; frame = get_sigframe(ka, regs, sizeof(*frame)); if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame))) goto give_sigsegv; err |= __put_user(sig, &frame->sig); if (err) goto give_sigsegv; err |= ia32_setup_sigcontext(&frame->sc, &frame->fpstate, regs, set->sig[0]); if (err) goto give_sigsegv; if (_COMPAT_NSIG_WORDS > 1) { err |= __copy_to_user(frame->extramask, &set->sig[1], sizeof(frame->extramask)); if (err) goto give_sigsegv; } if (ka->sa.sa_flags & SA_RESTORER) { restorer = ka->sa.sa_restorer; } else { /* Return stub is in 32bit vsyscall page */ if (current->binfmt->hasvdso) restorer = VDSO32_SYMBOL(current->mm->context.vdso, sigreturn); else restorer = &frame->retcode; } err |= __put_user(ptr_to_compat(restorer), &frame->pretcode); /* * These are actually not used anymore, but left because some * gdb versions depend on them as a marker. */ 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 = 0; regs->cx = 0; 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: _gnutls_ciphertext2compressed (gnutls_session_t session, opaque * compress_data, int compress_size, gnutls_datum_t ciphertext, uint8_t type) { uint8_t MAC[MAX_HASH_SIZE]; uint16_t c_length; uint8_t pad; int length; digest_hd_st td; uint16_t blocksize; int ret, i, pad_failed = 0; uint8_t major, minor; gnutls_protocol_t ver; int hash_size = _gnutls_hash_get_algo_len (session->security_parameters. read_mac_algorithm); ver = gnutls_protocol_get_version (session); minor = _gnutls_version_get_minor (ver); major = _gnutls_version_get_major (ver); blocksize = _gnutls_cipher_get_block_size (session->security_parameters. read_bulk_cipher_algorithm); /* initialize MAC */ ret = mac_init (&td, session->security_parameters.read_mac_algorithm, session->connection_state.read_mac_secret.data, session->connection_state.read_mac_secret.size, ver); if (ret < 0 && session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL) { gnutls_assert (); return GNUTLS_E_INTERNAL_ERROR; } /* actual decryption (inplace) */ switch (_gnutls_cipher_is_block (session->security_parameters.read_bulk_cipher_algorithm)) { case CIPHER_STREAM: if ((ret = _gnutls_cipher_decrypt (&session->connection_state. read_cipher_state, ciphertext.data, ciphertext.size)) < 0) { gnutls_assert (); return ret; } length = ciphertext.size - hash_size; break; case CIPHER_BLOCK: if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0)) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } if ((ret = _gnutls_cipher_decrypt (&session->connection_state. read_cipher_state, ciphertext.data, ciphertext.size)) < 0) { gnutls_assert (); return ret; } /* ignore the IV in TLS 1.1. */ if (session->security_parameters.version >= GNUTLS_TLS1_1) { ciphertext.size -= blocksize; ciphertext.data += blocksize; if (ciphertext.size == 0) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } } pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */ length = ciphertext.size - hash_size - pad; if (pad > ciphertext.size - hash_size) { gnutls_assert (); /* We do not fail here. We check below for the * the pad_failed. If zero means success. */ pad_failed = GNUTLS_E_DECRYPTION_FAILED; } /* Check the pading bytes (TLS 1.x) */ if (ver >= GNUTLS_TLS1 && pad_failed == 0) for (i = 2; i < pad; i++) { if (ciphertext.data[ciphertext.size - i] != ciphertext.data[ciphertext.size - 1]) pad_failed = GNUTLS_E_DECRYPTION_FAILED; } break; default: gnutls_assert (); return GNUTLS_E_INTERNAL_ERROR; } if (length < 0) length = 0; c_length = _gnutls_conv_uint16 ((uint16_t) length); /* Pass the type, version, length and compressed through * MAC. */ if (session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL) { _gnutls_hmac (&td, UINT64DATA (session->connection_state. read_sequence_number), 8); _gnutls_hmac (&td, &type, 1); if (ver >= GNUTLS_TLS1) { /* TLS 1.x */ _gnutls_hmac (&td, &major, 1); _gnutls_hmac (&td, &minor, 1); } _gnutls_hmac (&td, &c_length, 2); if (length > 0) _gnutls_hmac (&td, ciphertext.data, length); mac_deinit (&td, MAC, ver); } /* This one was introduced to avoid a timing attack against the TLS * 1.0 protocol. */ if (pad_failed != 0) return pad_failed; /* HMAC was not the same. */ if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } /* copy the decrypted stuff to compress_data. */ if (compress_size < length) { gnutls_assert (); return GNUTLS_E_DECOMPRESSION_FAILED; } memcpy (compress_data, ciphertext.data, length); return length; } ; 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: static struct dentry *__lookup_hash(struct qstr *name, struct dentry *base, struct nameidata *nd) { struct dentry *dentry; struct inode *inode; int err; inode = base->d_inode; /* * See if the low-level filesystem might want * to use its own hash.. */ if (base->d_op && base->d_op->d_hash) { err = base->d_op->d_hash(base, name); dentry = ERR_PTR(err); if (err < 0) goto out; } dentry = cached_lookup(base, name, nd); if (!dentry) { struct dentry *new = d_alloc(base, name); dentry = ERR_PTR(-ENOMEM); if (!new) goto out; dentry = inode->i_op->lookup(inode, new, nd); if (!dentry) dentry = new; else dput(new); } out: return dentry; } ; 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: int run_diff_files(struct rev_info *revs, unsigned int option) { int entries, i; int diff_unmerged_stage = revs->max_count; int silent_on_removed = option & DIFF_SILENT_ON_REMOVED; unsigned ce_option = ((option & DIFF_RACY_IS_MODIFIED) ? CE_MATCH_RACY_IS_DIRTY : 0); char symcache[PATH_MAX]; if (diff_unmerged_stage < 0) diff_unmerged_stage = 2; entries = active_nr; symcache[0] = '\0'; for (i = 0; i < entries; i++) { struct stat st; unsigned int oldmode, newmode; struct cache_entry *ce = active_cache[i]; int changed; if (DIFF_OPT_TST(&revs->diffopt, QUIET) && DIFF_OPT_TST(&revs->diffopt, HAS_CHANGES)) break; if (!ce_path_match(ce, revs->prune_data)) continue; if (ce_stage(ce)) { struct combine_diff_path *dpath; int num_compare_stages = 0; size_t path_len; path_len = ce_namelen(ce); dpath = xmalloc(combine_diff_path_size(5, path_len)); dpath->path = (char *) &(dpath->parent[5]); dpath->next = NULL; dpath->len = path_len; memcpy(dpath->path, ce->name, path_len); dpath->path[path_len] = '\0'; hashclr(dpath->sha1); memset(&(dpath->parent[0]), 0, sizeof(struct combine_diff_parent)*5); changed = check_removed(ce, &st); if (!changed) dpath->mode = ce_mode_from_stat(ce, st.st_mode); else { if (changed < 0) { perror(ce->name); continue; } if (silent_on_removed) continue; } while (i < entries) { struct cache_entry *nce = active_cache[i]; int stage; if (strcmp(ce->name, nce->name)) break; /* Stage #2 (ours) is the first parent, * stage #3 (theirs) is the second. */ stage = ce_stage(nce); if (2 <= stage) { int mode = nce->ce_mode; num_compare_stages++; hashcpy(dpath->parent[stage-2].sha1, nce->sha1); dpath->parent[stage-2].mode = ce_mode_from_stat(nce, mode); dpath->parent[stage-2].status = DIFF_STATUS_MODIFIED; } /* diff against the proper unmerged stage */ if (stage == diff_unmerged_stage) ce = nce; i++; } /* * Compensate for loop update */ i--; if (revs->combine_merges && num_compare_stages == 2) { show_combined_diff(dpath, 2, revs->dense_combined_merges, revs); free(dpath); continue; } free(dpath); dpath = NULL; /* * Show the diff for the 'ce' if we found the one * from the desired stage. */ diff_unmerge(&revs->diffopt, ce->name, 0, null_sha1); if (ce_stage(ce) != diff_unmerged_stage) continue; } if (ce_uptodate(ce)) continue; changed = check_removed(ce, &st); if (changed) { if (changed < 0) { perror(ce->name); continue; } if (silent_on_removed) continue; diff_addremove(&revs->diffopt, '-', ce->ce_mode, ce->sha1, ce->name, NULL); continue; } changed = ce_match_stat(ce, &st, ce_option); if (!changed) { ce_mark_uptodate(ce); if (!DIFF_OPT_TST(&revs->diffopt, FIND_COPIES_HARDER)) continue; } oldmode = ce->ce_mode; newmode = ce_mode_from_stat(ce, st.st_mode); diff_change(&revs->diffopt, oldmode, newmode, ce->sha1, (changed ? null_sha1 : ce->sha1), ce->name, NULL); } diffcore_std(&revs->diffopt); diff_flush(&revs->diffopt); 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: int arch_setup_additional_pages(struct linux_binprm *bprm, int exstack) { struct vm_area_struct *vma; struct mm_struct *mm = current->mm; unsigned long addr; int ret; down_write(&mm->mmap_sem); addr = get_unmapped_area(NULL, 0, PAGE_SIZE, 0, 0); if (IS_ERR_VALUE(addr)) { ret = addr; goto up_fail; } vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL); if (!vma) { ret = -ENOMEM; goto up_fail; } vma->vm_start = addr; vma->vm_end = addr + PAGE_SIZE; /* MAYWRITE to allow gdb to COW and set breakpoints */ vma->vm_flags = VM_READ|VM_EXEC|VM_MAYREAD|VM_MAYEXEC|VM_MAYWRITE; /* * Make sure the vDSO gets into every core dump. * Dumping its contents makes post-mortem fully interpretable later * without matching up the same kernel and hardware config to see * what PC values meant. */ vma->vm_flags |= VM_ALWAYSDUMP; vma->vm_flags |= mm->def_flags; vma->vm_page_prot = protection_map[vma->vm_flags & 7]; vma->vm_ops = &syscall_vm_ops; vma->vm_mm = mm; ret = insert_vm_struct(mm, vma); if (unlikely(ret)) { kmem_cache_free(vm_area_cachep, vma); goto up_fail; } current->mm->context.vdso = (void *)addr; current_thread_info()->sysenter_return = (void *)VDSO_SYM(&SYSENTER_RETURN); mm->total_vm++; up_fail: up_write(&mm->mmap_sem); return ret; } ; 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: jpc_mqdec_t *jpc_mqdec_create(int maxctxs, jas_stream_t *in) { jpc_mqdec_t *mqdec; /* There must be at least one context. */ assert(maxctxs > 0); /* Allocate memory for the MQ decoder. */ if (!(mqdec = jas_malloc(sizeof(jpc_mqdec_t)))) { goto error; } mqdec->in = in; mqdec->maxctxs = maxctxs; /* Allocate memory for the per-context state information. */ if (!(mqdec->ctxs = jas_malloc(mqdec->maxctxs * sizeof(jpc_mqstate_t *)))) { goto error; } /* Set the current context to the first context. */ mqdec->curctx = mqdec->ctxs; /* If an input stream has been associated with the MQ decoder, initialize the decoder state from the stream. */ if (mqdec->in) { jpc_mqdec_init(mqdec); } /* Initialize the per-context state information. */ jpc_mqdec_setctxs(mqdec, 0, 0); return mqdec; error: /* Oops... Something has gone wrong. */ if (mqdec) { jpc_mqdec_destroy(mqdec); } 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_mqenc_t *jpc_mqenc_create(int maxctxs, jas_stream_t *out) { jpc_mqenc_t *mqenc; /* Allocate memory for the MQ encoder. */ if (!(mqenc = jas_malloc(sizeof(jpc_mqenc_t)))) { goto error; } mqenc->out = out; mqenc->maxctxs = maxctxs; /* Allocate memory for the per-context state information. */ if (!(mqenc->ctxs = jas_malloc(mqenc->maxctxs * sizeof(jpc_mqstate_t *)))) { goto error; } /* Set the current context to the first one. */ mqenc->curctx = mqenc->ctxs; jpc_mqenc_init(mqenc); /* Initialize the per-context state information to something sane. */ jpc_mqenc_setctxs(mqenc, 0, 0); return mqenc; error: if (mqenc) { jpc_mqenc_destroy(mqenc); } 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_col(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE]; jpc_fix_t *buf = splitbuf; register jpc_fix_t *srcptr; register jpc_fix_t *dstptr; register int n; register 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) { *dstptr = *srcptr; ++dstptr; 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) { *dstptr = *srcptr; dstptr += stride; srcptr += stride << 1; } /* Copy the saved samples into the highpass channel. */ dstptr = &a[hstartcol * stride]; srcptr = buf; n = m; while (n-- > 0) { *dstptr = *srcptr; dstptr += stride; ++srcptr; } } /* 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: static int jas_cmshapmatlut_invert(jas_cmshapmatlut_t *invlut, jas_cmshapmatlut_t *lut, int n) { int i; int j; int k; jas_cmreal_t ax; jas_cmreal_t ay; jas_cmreal_t bx; jas_cmreal_t by; jas_cmreal_t sx; jas_cmreal_t sy; assert(n >= 2); if (invlut->data) { jas_free(invlut->data); invlut->data = 0; } /* The sample values should be nondecreasing. */ for (i = 1; i < lut->size; ++i) { if (lut->data[i - 1] > lut->data[i]) { assert(0); return -1; } } if (!(invlut->data = jas_malloc(n * sizeof(jas_cmreal_t)))) return -1; invlut->size = n; for (i = 0; i < invlut->size; ++i) { sy = ((double) i) / (invlut->size - 1); sx = 1.0; for (j = 0; j < lut->size; ++j) { ay = lut->data[j]; if (sy == ay) { for (k = j + 1; k < lut->size; ++k) { by = lut->data[k]; if (by != sy) break; #if 0 assert(0); #endif } if (k < lut->size) { --k; ax = ((double) j) / (lut->size - 1); bx = ((double) k) / (lut->size - 1); sx = (ax + bx) / 2.0; } break; } if (j < lut->size - 1) { by = lut->data[j + 1]; if (sy > ay && sy < by) { ax = ((double) j) / (lut->size - 1); bx = ((double) j + 1) / (lut->size - 1); sx = ax + (sy - ay) / (by - ay) * (bx - ax); break; } } } invlut->data[i] = sx; } #if 0 for (i=0;i<lut->size;++i) jas_eprintf("lut[%d]=%f ", i, lut->data[i]); for (i=0;i<invlut->size;++i) jas_eprintf("invlut[%d]=%f ", i, invlut->data[i]); #endif 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: int jpc_enc_enccblk(jpc_enc_t *enc, jas_stream_t *out, jpc_enc_tcmpt_t *tcmpt, jpc_enc_band_t *band, jpc_enc_cblk_t *cblk) { jpc_enc_pass_t *pass; jpc_enc_pass_t *endpasses; int bitpos; int n; int adjust; int ret; int passtype; int t; jpc_bitstream_t *bout; jpc_enc_pass_t *termpass; jpc_enc_rlvl_t *rlvl; int vcausal; int segsym; int termmode; int c; bout = 0; rlvl = band->rlvl; cblk->stream = jas_stream_memopen(0, 0); assert(cblk->stream); cblk->mqenc = jpc_mqenc_create(JPC_NUMCTXS, cblk->stream); assert(cblk->mqenc); jpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs); cblk->numpasses = (cblk->numbps > 0) ? (3 * cblk->numbps - 2) : 0; if (cblk->numpasses > 0) { cblk->passes = jas_malloc(cblk->numpasses * sizeof(jpc_enc_pass_t)); assert(cblk->passes); } else { cblk->passes = 0; } endpasses = (cblk->passes) ? &cblk->passes[cblk->numpasses] : 0; for (pass = cblk->passes; pass != endpasses; ++pass) { pass->start = 0; pass->end = 0; pass->term = JPC_ISTERMINATED(pass - cblk->passes, 0, cblk->numpasses, (tcmpt->cblksty & JPC_COX_TERMALL) != 0, (tcmpt->cblksty & JPC_COX_LAZY) != 0); pass->type = JPC_SEGTYPE(pass - cblk->passes, 0, (tcmpt->cblksty & JPC_COX_LAZY) != 0); pass->lyrno = -1; if (pass == endpasses - 1) { assert(pass->term == 1); pass->term = 1; } } cblk->flags = jas_matrix_create(jas_matrix_numrows(cblk->data) + 2, jas_matrix_numcols(cblk->data) + 2); assert(cblk->flags); bitpos = cblk->numbps - 1; pass = cblk->passes; n = cblk->numpasses; while (--n >= 0) { if (pass->type == JPC_SEG_MQ) { /* NOP */ } else { assert(pass->type == JPC_SEG_RAW); if (!bout) { bout = jpc_bitstream_sopen(cblk->stream, "w"); assert(bout); } } #if 1 passtype = (pass - cblk->passes + 2) % 3; #else passtype = JPC_PASSTYPE(pass - cblk->passes + 2); #endif pass->start = jas_stream_tell(cblk->stream); #if 0 assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream)); #endif assert(bitpos >= 0); vcausal = (tcmpt->cblksty & JPC_COX_VSC) != 0; segsym = (tcmpt->cblksty & JPC_COX_SEGSYM) != 0; if (pass->term) { termmode = ((tcmpt->cblksty & JPC_COX_PTERM) ? JPC_MQENC_PTERM : JPC_MQENC_DEFTERM) + 1; } else { termmode = 0; } switch (passtype) { case JPC_SIGPASS: ret = (pass->type == JPC_SEG_MQ) ? jpc_encsigpass(cblk->mqenc, bitpos, band->orient, vcausal, cblk->flags, cblk->data, termmode, &pass->nmsedec) : jpc_encrawsigpass(bout, bitpos, vcausal, cblk->flags, cblk->data, termmode, &pass->nmsedec); break; case JPC_REFPASS: ret = (pass->type == JPC_SEG_MQ) ? jpc_encrefpass(cblk->mqenc, bitpos, vcausal, cblk->flags, cblk->data, termmode, &pass->nmsedec) : jpc_encrawrefpass(bout, bitpos, vcausal, cblk->flags, cblk->data, termmode, &pass->nmsedec); break; case JPC_CLNPASS: assert(pass->type == JPC_SEG_MQ); ret = jpc_encclnpass(cblk->mqenc, bitpos, band->orient, vcausal, segsym, cblk->flags, cblk->data, termmode, &pass->nmsedec); break; default: assert(0); break; } if (pass->type == JPC_SEG_MQ) { if (pass->term) { jpc_mqenc_init(cblk->mqenc); } jpc_mqenc_getstate(cblk->mqenc, &pass->mqencstate); pass->end = jas_stream_tell(cblk->stream); if (tcmpt->cblksty & JPC_COX_RESET) { jpc_mqenc_setctxs(cblk->mqenc, JPC_NUMCTXS, jpc_mqctxs); } } else { if (pass->term) { if (jpc_bitstream_pending(bout)) { jpc_bitstream_outalign(bout, 0x2a); } jpc_bitstream_close(bout); bout = 0; pass->end = jas_stream_tell(cblk->stream); } else { pass->end = jas_stream_tell(cblk->stream) + jpc_bitstream_pending(bout); /* NOTE - This will not work. need to adjust by # of pending output bytes */ } } #if 0 /* XXX - This assertion fails sometimes when various coding modes are used. This seems to be harmless, but why does it happen at all? */ assert(jas_stream_tell(cblk->stream) == jas_stream_getrwcount(cblk->stream)); #endif pass->wmsedec = jpc_fixtodbl(band->rlvl->tcmpt->synweight) * jpc_fixtodbl(band->rlvl->tcmpt->synweight) * jpc_fixtodbl(band->synweight) * jpc_fixtodbl(band->synweight) * jpc_fixtodbl(band->absstepsize) * jpc_fixtodbl(band->absstepsize) * ((double) (1 << bitpos)) * ((double)(1 << bitpos)) * jpc_fixtodbl(pass->nmsedec); pass->cumwmsedec = pass->wmsedec; if (pass != cblk->passes) { pass->cumwmsedec += pass[-1].cumwmsedec; } if (passtype == JPC_CLNPASS) { --bitpos; } ++pass; } #if 0 dump_passes(cblk->passes, cblk->numpasses, cblk); #endif n = 0; endpasses = (cblk->passes) ? &cblk->passes[cblk->numpasses] : 0; for (pass = cblk->passes; pass != endpasses; ++pass) { if (pass->start < n) { pass->start = n; } if (pass->end < n) { pass->end = n; } if (!pass->term) { termpass = pass; while (termpass - pass < cblk->numpasses && !termpass->term) { ++termpass; } if (pass->type == JPC_SEG_MQ) { t = (pass->mqencstate.lastbyte == 0xff) ? 1 : 0; if (pass->mqencstate.ctreg >= 5) { adjust = 4 + t; } else { adjust = 5 + t; } pass->end += adjust; } if (pass->end > termpass->end) { pass->end = termpass->end; } if ((c = getthebyte(cblk->stream, pass->end - 1)) == EOF) { abort(); } if (c == 0xff) { ++pass->end; } n = JAS_MAX(n, pass->end); } else { n = JAS_MAX(n, pass->end); } } #if 0 dump_passes(cblk->passes, cblk->numpasses, cblk); #endif if (bout) { jpc_bitstream_close(bout); } 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_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; uint_fast8_t tmp; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &siz->caps) || jpc_getuint32(in, &siz->width) || jpc_getuint32(in, &siz->height) || jpc_getuint32(in, &siz->xoff) || jpc_getuint32(in, &siz->yoff) || jpc_getuint32(in, &siz->tilewidth) || jpc_getuint32(in, &siz->tileheight) || jpc_getuint32(in, &siz->tilexoff) || jpc_getuint32(in, &siz->tileyoff) || jpc_getuint16(in, &siz->numcomps)) { return -1; } if (!siz->width || !siz->height || !siz->tilewidth || !siz->tileheight || !siz->numcomps) { return -1; } if (!(siz->comps = jas_malloc(siz->numcomps * sizeof(jpc_sizcomp_t)))) { return -1; } for (i = 0; i < siz->numcomps; ++i) { if (jpc_getuint8(in, &tmp) || jpc_getuint8(in, &siz->comps[i].hsamp) || jpc_getuint8(in, &siz->comps[i].vsamp)) { jas_free(siz->comps); return -1; } siz->comps[i].sgnd = (tmp >> 7) & 1; siz->comps[i].prec = (tmp & 0x7f) + 1; } if (jas_stream_eof(in)) { jas_free(siz->comps); 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 jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_pclr_t *pclr = &box->data.pclr; int lutsize; unsigned int i; unsigned int j; int_fast32_t x; pclr->lutdata = 0; if (jp2_getuint16(in, &pclr->numlutents) || jp2_getuint8(in, &pclr->numchans)) { return -1; } lutsize = pclr->numlutents * pclr->numchans; if (!(pclr->lutdata = jas_malloc(lutsize * sizeof(int_fast32_t)))) { return -1; } if (!(pclr->bpc = jas_malloc(pclr->numchans * sizeof(uint_fast8_t)))) { return -1; } for (i = 0; i < pclr->numchans; ++i) { if (jp2_getuint8(in, &pclr->bpc[i])) { return -1; } } for (i = 0; i < pclr->numlutents; ++i) { for (j = 0; j < pclr->numchans; ++j) { if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0, (pclr->bpc[j] & 0x7f) + 1, &x)) { return -1; } pclr->lutdata[i * pclr->numchans + j] = x; } } return 0; } ; 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: _dbus_marshal_validate_test (void) { DBusString str; int i; const char *valid_paths[] = { "/", "/foo/bar", "/foo", "/foo/bar/baz" }; const char *invalid_paths[] = { "bar", "bar/baz", "/foo/bar/", "/foo/" "foo/", "boo//blah", "//", "///", "foo///blah/", "Hello World", "", " ", "foo bar" }; const char *valid_interfaces[] = { "org.freedesktop.Foo", "Bar.Baz", "Blah.Blah.Blah.Blah.Blah", "a.b", "a.b.c.d.e.f.g", "a0.b1.c2.d3.e4.f5.g6", "abc123.foo27" }; const char *invalid_interfaces[] = { ".", "", "..", ".Foo.Bar", "..Foo.Bar", "Foo.Bar.", "Foo.Bar..", "Foo", "9foo.bar.baz", "foo.bar..baz", "foo.bar...baz", "foo.bar.b..blah", ":", ":0-1", "10", ":11.34324", "0.0.0", "0..0", "foo.Bar.%", "foo.Bar!!", "!Foo.bar.bz", "foo.$.blah", "", " ", "foo bar" }; const char *valid_unique_names[] = { ":0", ":a", ":", ":.a", ":.1", ":0.1", ":000.2222", ":.blah", ":abce.freedesktop.blah" }; const char *invalid_unique_names[] = { //":-", ":!", //":0-10", ":blah.", ":blah.", ":blah..org", ":blah.org..", ":..blah.org", "", " ", "foo bar" }; const char *valid_members[] = { "Hello", "Bar", "foobar", "_foobar", "foo89" }; const char *invalid_members[] = { "9Hello", "10", "1", "foo-bar", "blah.org", ".blah", "blah.", "Hello.", "!foo", "", " ", "foo bar" }; const char *valid_signatures[] = { "", "sss", "i", "b" }; const char *invalid_signatures[] = { " ", "not a valid signature", "123", ".", "(" }; /* Signature with reason */ run_validity_tests (signature_tests, _DBUS_N_ELEMENTS (signature_tests), _dbus_validate_signature_with_reason); /* Path validation */ i = 0; while (i < (int) _DBUS_N_ELEMENTS (valid_paths)) { _dbus_string_init_const (&str, valid_paths[i]); if (!_dbus_validate_path (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Path \"%s\" should have been valid\n", valid_paths[i]); _dbus_assert_not_reached ("invalid path"); } ++i; } i = 0; while (i < (int) _DBUS_N_ELEMENTS (invalid_paths)) { _dbus_string_init_const (&str, invalid_paths[i]); if (_dbus_validate_path (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Path \"%s\" should have been invalid\n", invalid_paths[i]); _dbus_assert_not_reached ("valid path"); } ++i; } /* Interface validation */ i = 0; while (i < (int) _DBUS_N_ELEMENTS (valid_interfaces)) { _dbus_string_init_const (&str, valid_interfaces[i]); if (!_dbus_validate_interface (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Interface \"%s\" should have been valid\n", valid_interfaces[i]); _dbus_assert_not_reached ("invalid interface"); } ++i; } i = 0; while (i < (int) _DBUS_N_ELEMENTS (invalid_interfaces)) { _dbus_string_init_const (&str, invalid_interfaces[i]); if (_dbus_validate_interface (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Interface \"%s\" should have been invalid\n", invalid_interfaces[i]); _dbus_assert_not_reached ("valid interface"); } ++i; } /* Bus name validation (check that valid interfaces are valid bus names, * and invalid interfaces are invalid services except if they start with ':') */ i = 0; while (i < (int) _DBUS_N_ELEMENTS (valid_interfaces)) { _dbus_string_init_const (&str, valid_interfaces[i]); if (!_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Bus name \"%s\" should have been valid\n", valid_interfaces[i]); _dbus_assert_not_reached ("invalid bus name"); } ++i; } i = 0; while (i < (int) _DBUS_N_ELEMENTS (invalid_interfaces)) { if (invalid_interfaces[i][0] != ':') { _dbus_string_init_const (&str, invalid_interfaces[i]); if (_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Bus name \"%s\" should have been invalid\n", invalid_interfaces[i]); _dbus_assert_not_reached ("valid bus name"); } } ++i; } /* unique name validation */ i = 0; while (i < (int) _DBUS_N_ELEMENTS (valid_unique_names)) { _dbus_string_init_const (&str, valid_unique_names[i]); if (!_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Bus name \"%s\" should have been valid\n", valid_unique_names[i]); _dbus_assert_not_reached ("invalid unique name"); } ++i; } i = 0; while (i < (int) _DBUS_N_ELEMENTS (invalid_unique_names)) { _dbus_string_init_const (&str, invalid_unique_names[i]); if (_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Bus name \"%s\" should have been invalid\n", invalid_unique_names[i]); _dbus_assert_not_reached ("valid unique name"); } ++i; } /* Error name validation (currently identical to interfaces) */ i = 0; while (i < (int) _DBUS_N_ELEMENTS (valid_interfaces)) { _dbus_string_init_const (&str, valid_interfaces[i]); if (!_dbus_validate_error_name (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Error name \"%s\" should have been valid\n", valid_interfaces[i]); _dbus_assert_not_reached ("invalid error name"); } ++i; } i = 0; while (i < (int) _DBUS_N_ELEMENTS (invalid_interfaces)) { if (invalid_interfaces[i][0] != ':') { _dbus_string_init_const (&str, invalid_interfaces[i]); if (_dbus_validate_error_name (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Error name \"%s\" should have been invalid\n", invalid_interfaces[i]); _dbus_assert_not_reached ("valid error name"); } } ++i; } /* Member validation */ i = 0; while (i < (int) _DBUS_N_ELEMENTS (valid_members)) { _dbus_string_init_const (&str, valid_members[i]); if (!_dbus_validate_member (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Member \"%s\" should have been valid\n", valid_members[i]); _dbus_assert_not_reached ("invalid member"); } ++i; } i = 0; while (i < (int) _DBUS_N_ELEMENTS (invalid_members)) { _dbus_string_init_const (&str, invalid_members[i]); if (_dbus_validate_member (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Member \"%s\" should have been invalid\n", invalid_members[i]); _dbus_assert_not_reached ("valid member"); } ++i; } /* Signature validation */ i = 0; while (i < (int) _DBUS_N_ELEMENTS (valid_signatures)) { _dbus_string_init_const (&str, valid_signatures[i]); if (!_dbus_validate_signature (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Signature \"%s\" should have been valid\n", valid_signatures[i]); _dbus_assert_not_reached ("invalid signature"); } ++i; } i = 0; while (i < (int) _DBUS_N_ELEMENTS (invalid_signatures)) { _dbus_string_init_const (&str, invalid_signatures[i]); if (_dbus_validate_signature (&str, 0, _dbus_string_get_length (&str))) { _dbus_warn ("Signature \"%s\" should have been invalid\n", invalid_signatures[i]); _dbus_assert_not_reached ("valid signature"); } ++i; } /* Validate claimed length longer than real length */ _dbus_string_init_const (&str, "abc.efg"); if (_dbus_validate_bus_name (&str, 0, 8)) _dbus_assert_not_reached ("validated too-long string"); if (_dbus_validate_interface (&str, 0, 8)) _dbus_assert_not_reached ("validated too-long string"); if (_dbus_validate_error_name (&str, 0, 8)) _dbus_assert_not_reached ("validated too-long string"); _dbus_string_init_const (&str, "abc"); if (_dbus_validate_member (&str, 0, 4)) _dbus_assert_not_reached ("validated too-long string"); _dbus_string_init_const (&str, "sss"); if (_dbus_validate_signature (&str, 0, 4)) _dbus_assert_not_reached ("validated too-long signature"); /* Validate string exceeding max name length */ if (!_dbus_string_init (&str)) _dbus_assert_not_reached ("no memory"); while (_dbus_string_get_length (&str) <= DBUS_MAXIMUM_NAME_LENGTH) if (!_dbus_string_append (&str, "abc.def")) _dbus_assert_not_reached ("no memory"); if (_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str))) _dbus_assert_not_reached ("validated overmax string"); if (_dbus_validate_interface (&str, 0, _dbus_string_get_length (&str))) _dbus_assert_not_reached ("validated overmax string"); if (_dbus_validate_error_name (&str, 0, _dbus_string_get_length (&str))) _dbus_assert_not_reached ("validated overmax string"); /* overlong member */ _dbus_string_set_length (&str, 0); while (_dbus_string_get_length (&str) <= DBUS_MAXIMUM_NAME_LENGTH) if (!_dbus_string_append (&str, "abc")) _dbus_assert_not_reached ("no memory"); if (_dbus_validate_member (&str, 0, _dbus_string_get_length (&str))) _dbus_assert_not_reached ("validated overmax string"); /* overlong unique name */ _dbus_string_set_length (&str, 0); _dbus_string_append (&str, ":"); while (_dbus_string_get_length (&str) <= DBUS_MAXIMUM_NAME_LENGTH) if (!_dbus_string_append (&str, "abc")) _dbus_assert_not_reached ("no memory"); if (_dbus_validate_bus_name (&str, 0, _dbus_string_get_length (&str))) _dbus_assert_not_reached ("validated overmax string"); _dbus_string_free (&str); /* Body validation; test basic validation of valid bodies for both endian */ { int sequence; DBusString signature; DBusString body; if (!_dbus_string_init (&signature) || !_dbus_string_init (&body)) _dbus_assert_not_reached ("oom"); sequence = 0; while (dbus_internal_do_not_use_generate_bodies (sequence, DBUS_LITTLE_ENDIAN, &signature, &body)) { DBusValidity validity; validity = _dbus_validate_body_with_reason (&signature, 0, DBUS_LITTLE_ENDIAN, NULL, &body, 0, _dbus_string_get_length (&body)); if (validity != DBUS_VALID) { _dbus_warn ("invalid code %d expected valid on sequence %d little endian\n", validity, sequence); _dbus_verbose_bytes_of_string (&signature, 0, _dbus_string_get_length (&signature)); _dbus_verbose_bytes_of_string (&body, 0, _dbus_string_get_length (&body)); _dbus_assert_not_reached ("test failed"); } _dbus_string_set_length (&signature, 0); _dbus_string_set_length (&body, 0); ++sequence; } sequence = 0; while (dbus_internal_do_not_use_generate_bodies (sequence, DBUS_BIG_ENDIAN, &signature, &body)) { DBusValidity validity; validity = _dbus_validate_body_with_reason (&signature, 0, DBUS_BIG_ENDIAN, NULL, &body, 0, _dbus_string_get_length (&body)); if (validity != DBUS_VALID) { _dbus_warn ("invalid code %d expected valid on sequence %d big endian\n", validity, sequence); _dbus_verbose_bytes_of_string (&signature, 0, _dbus_string_get_length (&signature)); _dbus_verbose_bytes_of_string (&body, 0, _dbus_string_get_length (&body)); _dbus_assert_not_reached ("test failed"); } _dbus_string_set_length (&signature, 0); _dbus_string_set_length (&body, 0); ++sequence; } _dbus_string_free (&signature); _dbus_string_free (&body); } return TRUE; } ; 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: int hfsplus_find_cat(struct super_block *sb, u32 cnid, struct hfs_find_data *fd) { hfsplus_cat_entry tmp; int err; u16 type; hfsplus_cat_build_key(sb, fd->search_key, cnid, NULL); err = hfs_brec_read(fd, &tmp, sizeof(hfsplus_cat_entry)); if (err) return err; type = be16_to_cpu(tmp.type); if (type != HFSPLUS_FOLDER_THREAD && type != HFSPLUS_FILE_THREAD) { printk(KERN_ERR "hfs: found bad thread record in catalog\n"); return -EIO; } hfsplus_cat_build_key_uni(fd->search_key, be32_to_cpu(tmp.thread.parentID), &tmp.thread.nodeName); return hfs_brec_find(fd); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'hfsplus: fix Buffer overflow with a corrupted image When an hfsplus image gets corrupted it might happen that the catalog namelength field gets b0rked. If we mount such an image the memcpy() in hfsplus_cat_build_key_uni() writes more than the 255 that fit in the name field. Depending on the size of the overwritten data, we either only get memory corruption or also trigger an oops like this: [ 221.628020] BUG: unable to handle kernel paging request at c82b0000 [ 221.629066] IP: [<c022d4b1>] hfsplus_find_cat+0x10d/0x151 [ 221.629066] *pde = 0ea29163 *pte = 082b0160 [ 221.629066] Oops: 0002 [#1] PREEMPT DEBUG_PAGEALLOC [ 221.629066] Modules linked in: [ 221.629066] [ 221.629066] Pid: 4845, comm: mount Not tainted (2.6.27-rc4-00123-gd3ee1b4-dirty #28) [ 221.629066] EIP: 0060:[<c022d4b1>] EFLAGS: 00010206 CPU: 0 [ 221.629066] EIP is at hfsplus_find_cat+0x10d/0x151 [ 221.629066] EAX: 00000029 EBX: 00016210 ECX: 000042c2 EDX: 00000002 [ 221.629066] ESI: c82d70ca EDI: c82b0000 EBP: c82d1bcc ESP: c82d199c [ 221.629066] DS: 007b ES: 007b FS: 0000 GS: 0033 SS: 0068 [ 221.629066] Process mount (pid: 4845, ti=c82d1000 task=c8224060 task.ti=c82d1000) [ 221.629066] Stack: c080b3c4 c82aa8f8 c82d19c2 00016210 c080b3be c82d1bd4 c82aa8f0 00000300 [ 221.629066] 01000000 750008b1 74006e00 74006900 65006c00 c82d6400 c013bd35 c8224060 [ 221.629066] 00000036 00000046 c82d19f0 00000082 c8224548 c8224060 00000036 c0d653cc [ 221.629066] Call Trace: [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c0107aa3>] ? native_sched_clock+0x82/0x96 [ 221.629066] [<c01302d2>] ? __kernel_text_address+0x1b/0x27 [ 221.629066] [<c010487a>] ? dump_trace+0xca/0xd6 [ 221.629066] [<c0109e32>] ? save_stack_address+0x0/0x2c [ 221.629066] [<c0109eaf>] ? save_stack_trace+0x1c/0x3a [ 221.629066] [<c013b571>] ? save_trace+0x37/0x8d [ 221.629066] [<c013b62e>] ? add_lock_to_list+0x67/0x8d [ 221.629066] [<c013ea1c>] ? validate_chain+0x8a4/0x9f4 [ 221.629066] [<c013553d>] ? down+0xc/0x2f [ 221.629066] [<c013f1f6>] ? __lock_acquire+0x68a/0x6e0 [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c0107aa3>] ? native_sched_clock+0x82/0x96 [ 221.629066] [<c013da5d>] ? mark_held_locks+0x43/0x5a [ 221.629066] [<c013dc3a>] ? trace_hardirqs_on+0xb/0xd [ 221.629066] [<c013dbf4>] ? trace_hardirqs_on_caller+0xf4/0x12f [ 221.629066] [<c06abec8>] ? _spin_unlock_irqrestore+0x42/0x58 [ 221.629066] [<c013555c>] ? down+0x2b/0x2f [ 221.629066] [<c022aa68>] ? hfsplus_iget+0xa0/0x154 [ 221.629066] [<c022b0b9>] ? hfsplus_fill_super+0x280/0x447 [ 221.629066] [<c0107aa3>] ? native_sched_clock+0x82/0x96 [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013f1f6>] ? __lock_acquire+0x68a/0x6e0 [ 221.629066] [<c041c9e4>] ? string+0x2b/0x74 [ 221.629066] [<c041cd16>] ? vsnprintf+0x2e9/0x512 [ 221.629066] [<c010487a>] ? dump_trace+0xca/0xd6 [ 221.629066] [<c0109eaf>] ? save_stack_trace+0x1c/0x3a [ 221.629066] [<c0109eaf>] ? save_stack_trace+0x1c/0x3a [ 221.629066] [<c013b571>] ? save_trace+0x37/0x8d [ 221.629066] [<c013b62e>] ? add_lock_to_list+0x67/0x8d [ 221.629066] [<c013ea1c>] ? validate_chain+0x8a4/0x9f4 [ 221.629066] [<c01354d3>] ? up+0xc/0x2f [ 221.629066] [<c013f1f6>] ? __lock_acquire+0x68a/0x6e0 [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c013bca3>] ? trace_hardirqs_off_caller+0x14/0x9b [ 221.629066] [<c013bd35>] ? trace_hardirqs_off+0xb/0xd [ 221.629066] [<c0107aa3>] ? native_sched_clock+0x82/0x96 [ 221.629066] [<c041cfb7>] ? snprintf+0x1b/0x1d [ 221.629066] [<c01ba466>] ? disk_name+0x25/0x67 [ 221.629066] [<c0183960>] ? get_sb_bdev+0xcd/0x10b [ 221.629066] [<c016ad92>] ? kstrdup+0x2a/0x4c [ 221.629066] [<c022a7b3>] ? hfsplus_get_sb+0x13/0x15 [ 221.629066] [<c022ae39>] ? hfsplus_fill_super+0x0/0x447 [ 221.629066] [<c0183583>] ? vfs_kern_mount+0x3b/0x76 [ 221.629066] [<c0183602>] ? do_kern_mount+0x32/0xba [ 221.629066] [<c01960d4>] ? do_new_mount+0x46/0x74 [ 221.629066] [<c0196277>] ? do_mount+0x175/0x193 [ 221.629066] [<c013dbf4>] ? trace_hardirqs_on_caller+0xf4/0x12f [ 221.629066] [<c01663b2>] ? __get_free_pages+0x1e/0x24 [ 221.629066] [<c06ac07b>] ? lock_kernel+0x19/0x8c [ 221.629066] [<c01962e6>] ? sys_mount+0x51/0x9b [ 221.629066] [<c01962f9>] ? sys_mount+0x64/0x9b [ 221.629066] [<c01038bd>] ? sysenter_do_call+0x12/0x31 [ 221.629066] ======================= [ 221.629066] Code: 89 c2 c1 e2 08 c1 e8 08 09 c2 8b 85 e8 fd ff ff 66 89 50 06 89 c7 53 83 c7 08 56 57 68 c4 b3 80 c0 e8 8c 5c ef ff 89 d9 c1 e9 02 <f3> a5 89 d9 83 e1 03 74 02 f3 a4 83 c3 06 8b 95 e8 fd ff ff 0f [ 221.629066] EIP: [<c022d4b1>] hfsplus_find_cat+0x10d/0x151 SS:ESP 0068:c82d199c [ 221.629066] ---[ end trace e417a1d67f0d0066 ]--- Since hfsplus_cat_build_key_uni() returns void and only has one callsite, the check is performed at the callsite. Signed-off-by: Eric Sesterhenn <snakebyte@gmx.de> Reviewed-by: Pekka Enberg <penberg@cs.helsinki.fi> 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 uvc_parse_format(struct uvc_device *dev, struct uvc_streaming *streaming, struct uvc_format *format, __u32 **intervals, unsigned char *buffer, int buflen) { struct usb_interface *intf = streaming->intf; struct usb_host_interface *alts = intf->cur_altsetting; struct uvc_format_desc *fmtdesc; struct uvc_frame *frame; const unsigned char *start = buffer; unsigned int interval; unsigned int i, n; __u8 ftype; format->type = buffer[2]; format->index = buffer[3]; switch (buffer[2]) { case VS_FORMAT_UNCOMPRESSED: case VS_FORMAT_FRAME_BASED: if (buflen < 27) { uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming" "interface %d FORMAT error\n", dev->udev->devnum, alts->desc.bInterfaceNumber); return -EINVAL; } /* Find the format descriptor from its GUID. */ fmtdesc = uvc_format_by_guid(&buffer[5]); if (fmtdesc != NULL) { strncpy(format->name, fmtdesc->name, sizeof format->name); format->fcc = fmtdesc->fcc; } else { uvc_printk(KERN_INFO, "Unknown video format " UVC_GUID_FORMAT "\n", UVC_GUID_ARGS(&buffer[5])); snprintf(format->name, sizeof format->name, UVC_GUID_FORMAT, UVC_GUID_ARGS(&buffer[5])); format->fcc = 0; } format->bpp = buffer[21]; if (buffer[2] == VS_FORMAT_UNCOMPRESSED) { ftype = VS_FRAME_UNCOMPRESSED; } else { ftype = VS_FRAME_FRAME_BASED; if (buffer[27]) format->flags = UVC_FMT_FLAG_COMPRESSED; } break; case VS_FORMAT_MJPEG: if (buflen < 11) { uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming" "interface %d FORMAT error\n", dev->udev->devnum, alts->desc.bInterfaceNumber); return -EINVAL; } strncpy(format->name, "MJPEG", sizeof format->name); format->fcc = V4L2_PIX_FMT_MJPEG; format->flags = UVC_FMT_FLAG_COMPRESSED; format->bpp = 0; ftype = VS_FRAME_MJPEG; break; case VS_FORMAT_DV: if (buflen < 9) { uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming" "interface %d FORMAT error\n", dev->udev->devnum, alts->desc.bInterfaceNumber); return -EINVAL; } switch (buffer[8] & 0x7f) { case 0: strncpy(format->name, "SD-DV", sizeof format->name); break; case 1: strncpy(format->name, "SDL-DV", sizeof format->name); break; case 2: strncpy(format->name, "HD-DV", sizeof format->name); break; default: uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming" "interface %d: unknown DV format %u\n", dev->udev->devnum, alts->desc.bInterfaceNumber, buffer[8]); return -EINVAL; } strncat(format->name, buffer[8] & (1 << 7) ? " 60Hz" : " 50Hz", sizeof format->name); format->fcc = V4L2_PIX_FMT_DV; format->flags = UVC_FMT_FLAG_COMPRESSED | UVC_FMT_FLAG_STREAM; format->bpp = 0; ftype = 0; /* Create a dummy frame descriptor. */ frame = &format->frame[0]; memset(&format->frame[0], 0, sizeof format->frame[0]); frame->bFrameIntervalType = 1; frame->dwDefaultFrameInterval = 1; frame->dwFrameInterval = *intervals; *(*intervals)++ = 1; format->nframes = 1; break; case VS_FORMAT_MPEG2TS: case VS_FORMAT_STREAM_BASED: /* Not supported yet. */ default: uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming" "interface %d unsupported format %u\n", dev->udev->devnum, alts->desc.bInterfaceNumber, buffer[2]); return -EINVAL; } uvc_trace(UVC_TRACE_DESCR, "Found format %s.\n", format->name); buflen -= buffer[0]; buffer += buffer[0]; /* Parse the frame descriptors. Only uncompressed, MJPEG and frame * based formats have frame descriptors. */ while (buflen > 2 && buffer[2] == ftype) { frame = &format->frame[format->nframes]; if (ftype != VS_FRAME_FRAME_BASED) n = buflen > 25 ? buffer[25] : 0; else n = buflen > 21 ? buffer[21] : 0; n = n ? n : 3; if (buflen < 26 + 4*n) { uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming" "interface %d FRAME error\n", dev->udev->devnum, alts->desc.bInterfaceNumber); return -EINVAL; } frame->bFrameIndex = buffer[3]; frame->bmCapabilities = buffer[4]; frame->wWidth = le16_to_cpup((__le16 *)&buffer[5]); frame->wHeight = le16_to_cpup((__le16 *)&buffer[7]); frame->dwMinBitRate = le32_to_cpup((__le32 *)&buffer[9]); frame->dwMaxBitRate = le32_to_cpup((__le32 *)&buffer[13]); if (ftype != VS_FRAME_FRAME_BASED) { frame->dwMaxVideoFrameBufferSize = le32_to_cpup((__le32 *)&buffer[17]); frame->dwDefaultFrameInterval = le32_to_cpup((__le32 *)&buffer[21]); frame->bFrameIntervalType = buffer[25]; } else { frame->dwMaxVideoFrameBufferSize = 0; frame->dwDefaultFrameInterval = le32_to_cpup((__le32 *)&buffer[17]); frame->bFrameIntervalType = buffer[21]; } frame->dwFrameInterval = *intervals; /* Several UVC chipsets screw up dwMaxVideoFrameBufferSize * completely. Observed behaviours range from setting the * value to 1.1x the actual frame size of hardwiring the * 16 low bits to 0. This results in a higher than necessary * memory usage as well as a wrong image size information. For * uncompressed formats this can be fixed by computing the * value from the frame size. */ if (!(format->flags & UVC_FMT_FLAG_COMPRESSED)) frame->dwMaxVideoFrameBufferSize = format->bpp * frame->wWidth * frame->wHeight / 8; /* Some bogus devices report dwMinFrameInterval equal to * dwMaxFrameInterval and have dwFrameIntervalStep set to * zero. Setting all null intervals to 1 fixes the problem and * some other divisions by zero which could happen. */ for (i = 0; i < n; ++i) { interval = le32_to_cpup((__le32 *)&buffer[26+4*i]); *(*intervals)++ = interval ? interval : 1; } /* Make sure that the default frame interval stays between * the boundaries. */ n -= frame->bFrameIntervalType ? 1 : 2; frame->dwDefaultFrameInterval = min(frame->dwFrameInterval[n], max(frame->dwFrameInterval[0], frame->dwDefaultFrameInterval)); uvc_trace(UVC_TRACE_DESCR, "- %ux%u (%u.%u fps)\n", frame->wWidth, frame->wHeight, 10000000/frame->dwDefaultFrameInterval, (100000000/frame->dwDefaultFrameInterval)%10); format->nframes++; buflen -= buffer[0]; buffer += buffer[0]; } if (buflen > 2 && buffer[2] == VS_STILL_IMAGE_FRAME) { buflen -= buffer[0]; buffer += buffer[0]; } if (buflen > 2 && buffer[2] == VS_COLORFORMAT) { if (buflen < 6) { uvc_trace(UVC_TRACE_DESCR, "device %d videostreaming" "interface %d COLORFORMAT error\n", dev->udev->devnum, alts->desc.bInterfaceNumber); return -EINVAL; } format->colorspace = uvc_colorspace(buffer[3]); buflen -= buffer[0]; buffer += buffer[0]; } return buffer - start; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'V4L/DVB (8207): uvcvideo: Fix a buffer overflow in format descriptor parsing Thanks to Oliver Neukum for catching and reporting this bug. Signed-off-by: Laurent Pinchart <laurent.pinchart@skynet.be> Signed-off-by: Mauro Carvalho Chehab <mchehab@infradead.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 audit_inotify_unregister(struct list_head *in_list) { struct audit_parent *p, *n; list_for_each_entry_safe(p, n, in_list, ilist) { list_del(&p->ilist); inotify_rm_watch(audit_ih, &p->wdata); /* the put matching the get in audit_do_del_rule() */ put_inotify_watch(&p->wdata); } } ; 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 audit_put_chunk(struct audit_chunk *chunk) { put_inotify_watch(&chunk->watch); } ; 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 ima_adpcm_reset2 (_AFmoduleinst *i) { ima_adpcm_data *d = (ima_adpcm_data *) i->modspec; int framesPerBlock; framesPerBlock = d->samplesPerBlock / d->track->f.channelCount; d->track->fpos_next_frame = d->track->fpos_first_frame + d->blockAlign * (d->track->nextfframe / framesPerBlock); d->track->frames2ignore += d->framesToIgnore; assert(d->track->nextfframe % framesPerBlock == 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix decoding of multi-channel ADPCM audio files.'</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: long keyctl_join_session_keyring(const char __user *_name) { char *name; long ret; /* fetch the name from userspace */ name = NULL; if (_name) { name = strndup_user(_name, PAGE_SIZE); if (IS_ERR(name)) { ret = PTR_ERR(name); goto error; } } /* join the session */ ret = join_session_keyring(name); error: return ret; } /* end keyctl_join_session_keyring() */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'security: introduce missing kfree Plug this leak. Acked-by: David Howells <dhowells@redhat.com> Cc: James Morris <jmorris@namei.org> Cc: <stable@kernel.org> Signed-off-by: Vegard Nossum <vegard.nossum@gmail.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 originates_from_local_legacy_unicast_socket(AvahiServer *s, const AvahiAddress *address, uint16_t port) { assert(s); assert(address); assert(port > 0); if (!s->config.enable_reflector) return 0; if (!avahi_address_is_local(s->monitor, address)) return 0; if (address->proto == AVAHI_PROTO_INET && s->fd_legacy_unicast_ipv4 >= 0) { struct sockaddr_in lsa; socklen_t l = sizeof(lsa); if (getsockname(s->fd_legacy_unicast_ipv4, (struct sockaddr*) &lsa, &l) != 0) avahi_log_warn("getsockname(): %s", strerror(errno)); else return lsa.sin_port == port; } if (address->proto == AVAHI_PROTO_INET6 && s->fd_legacy_unicast_ipv6 >= 0) { struct sockaddr_in6 lsa; socklen_t l = sizeof(lsa); if (getsockname(s->fd_legacy_unicast_ipv6, (struct sockaddr*) &lsa, &l) != 0) avahi_log_warn("getsockname(): %s", strerror(errno)); else return lsa.sin6_port == port; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2009-0758: Reflector creates packet storm on legacy unicast traffic Fixes rhbz #488314.'</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 nfs_server *nfs_clone_server(struct nfs_server *source, struct nfs_fh *fh, struct nfs_fattr *fattr) { struct nfs_server *server; struct nfs_fattr fattr_fsinfo; int error; dprintk("--> nfs_clone_server(,%llx:%llx,)\n", (unsigned long long) fattr->fsid.major, (unsigned long long) fattr->fsid.minor); server = nfs_alloc_server(); if (!server) return ERR_PTR(-ENOMEM); /* Copy data from the source */ server->nfs_client = source->nfs_client; atomic_inc(&server->nfs_client->cl_count); nfs_server_copy_userdata(server, source); server->fsid = fattr->fsid; error = nfs_init_server_rpcclient(server, source->client->cl_auth->au_flavor); if (error < 0) goto out_free_server; if (!IS_ERR(source->client_acl)) nfs_init_server_aclclient(server); /* probe the filesystem info for this server filesystem */ error = nfs_probe_fsinfo(server, fh, &fattr_fsinfo); if (error < 0) goto out_free_server; dprintk("Cloned FSID: %llx:%llx\n", (unsigned long long) server->fsid.major, (unsigned long long) server->fsid.minor); error = nfs_start_lockd(server); if (error < 0) goto out_free_server; spin_lock(&nfs_client_lock); list_add_tail(&server->client_link, &server->nfs_client->cl_superblocks); list_add_tail(&server->master_link, &nfs_volume_list); spin_unlock(&nfs_client_lock); server->mount_time = jiffies; dprintk("<-- nfs_clone_server() = %p\n", server); return server; out_free_server: nfs_free_server(server); dprintk("<-- nfs_clone_server() = error %d\n", error); return ERR_PTR(error); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'NFS: Fix an Oops in encode_lookup() It doesn't look as if the NFS file name limit is being initialised correctly in the struct nfs_server. Make sure that we limit whatever is being set in nfs_probe_fsinfo() and nfs_init_server(). Also ensure that readdirplus and nfs4_path_walk respect our file name limits. Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.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 tc_fill_tclass(struct sk_buff *skb, struct Qdisc *q, unsigned long cl, u32 pid, u32 seq, u16 flags, int event) { struct tcmsg *tcm; struct nlmsghdr *nlh; unsigned char *b = skb_tail_pointer(skb); struct gnet_dump d; const struct Qdisc_class_ops *cl_ops = q->ops->cl_ops; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*tcm), flags); tcm = NLMSG_DATA(nlh); tcm->tcm_family = AF_UNSPEC; tcm->tcm_ifindex = qdisc_dev(q)->ifindex; tcm->tcm_parent = q->handle; tcm->tcm_handle = q->handle; tcm->tcm_info = 0; NLA_PUT_STRING(skb, TCA_KIND, q->ops->id); if (cl_ops->dump && cl_ops->dump(q, cl, skb, tcm) < 0) goto nla_put_failure; if (gnet_stats_start_copy_compat(skb, TCA_STATS2, TCA_STATS, TCA_XSTATS, qdisc_root_sleeping_lock(q), &d) < 0) goto nla_put_failure; if (cl_ops->dump_stats && cl_ops->dump_stats(q, cl, &d) < 0) goto nla_put_failure; if (gnet_stats_finish_copy(&d) < 0) goto nla_put_failure; nlh->nlmsg_len = skb_tail_pointer(skb) - b; return skb->len; nlmsg_failure: nla_put_failure: nlmsg_trim(skb, b); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-909'], 'message': 'tc: Fix unitialized kernel memory leak Three bytes of uninitialized kernel memory are currently leaked to user Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Reviewed-by: Jiri Pirko <jpirko@redhat.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: tca_get_fill(struct sk_buff *skb, struct tc_action *a, u32 pid, u32 seq, u16 flags, int event, int bind, int ref) { struct tcamsg *t; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct rtattr *x; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*t), flags); t = NLMSG_DATA(nlh); t->tca_family = AF_UNSPEC; x = (struct rtattr*) skb->tail; RTA_PUT(skb, TCA_ACT_TAB, 0, NULL); if (tcf_action_dump(skb, a, bind, ref) < 0) goto rtattr_failure; x->rta_len = skb->tail - (u8*)x; nlh->nlmsg_len = skb->tail - b; return skb->len; rtattr_failure: nlmsg_failure: skb_trim(skb, b - skb->data); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Missing initializations in dumped data Mostly missing initialization of padding fields of 1 or 2 bytes length, two instances of uninitialized nlmsgerr->msg of 16 bytes length. Signed-off-by: Patrick McHardy <kaber@trash.net> 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: void __rta_fill(struct sk_buff *skb, int attrtype, int attrlen, const void *data) { struct rtattr *rta; int size = RTA_LENGTH(attrlen); rta = (struct rtattr*)skb_put(skb, RTA_ALIGN(size)); rta->rta_type = attrtype; rta->rta_len = size; memcpy(RTA_DATA(rta), data, attrlen); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': '[NETLINK]: Clear padding in netlink messages Signed-off-by: Patrick McHardy <kaber@trash.net> 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 main(int argc, char ** argv) { int c; unsigned long flags = MS_MANDLOCK; char * orgoptions = NULL; char * share_name = NULL; const char * ipaddr = NULL; char * uuid = NULL; char * mountpoint = NULL; char * options = NULL; char * optionstail; char * resolved_path = NULL; char * temp; char * dev_name; int rc = 0; int rsize = 0; int wsize = 0; int nomtab = 0; int uid = 0; int gid = 0; int optlen = 0; int orgoptlen = 0; size_t options_size = 0; size_t current_len; int retry = 0; /* set when we have to retry mount with uppercase */ struct addrinfo *addrhead = NULL, *addr; struct utsname sysinfo; struct mntent mountent; struct sockaddr_in *addr4; struct sockaddr_in6 *addr6; FILE * pmntfile; /* setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); */ if(argc && argv) thisprogram = argv[0]; else mount_cifs_usage(stderr); if(thisprogram == NULL) thisprogram = "mount.cifs"; uname(&sysinfo); /* BB add workstation name and domain and pass down */ /* #ifdef _GNU_SOURCE fprintf(stderr, " node: %s machine: %s sysname %s domain %s\n", sysinfo.nodename,sysinfo.machine,sysinfo.sysname,sysinfo.domainname); #endif */ if(argc > 2) { dev_name = argv[1]; share_name = strndup(argv[1], MAX_UNC_LEN); if (share_name == NULL) { fprintf(stderr, "%s: %s", argv[0], strerror(ENOMEM)); exit(EX_SYSERR); } mountpoint = argv[2]; } else if (argc == 2) { if ((strcmp(argv[1], "-V") == 0) || (strcmp(argv[1], "--version") == 0)) { print_cifs_mount_version(); exit(0); } if ((strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "-?") == 0) || (strcmp(argv[1], "--help") == 0)) mount_cifs_usage(stdout); mount_cifs_usage(stderr); } else { mount_cifs_usage(stderr); } /* add sharename in opts string as unc= parm */ while ((c = getopt_long (argc, argv, "afFhilL:no:O:rsSU:vVwt:", longopts, NULL)) != -1) { switch (c) { /* No code to do the following options yet */ /* case 'l': list_with_volumelabel = 1; break; case 'L': volumelabel = optarg; break; */ /* case 'a': ++mount_all; break; */ case '?': case 'h': /* help */ mount_cifs_usage(stdout); case 'n': ++nomtab; break; case 'b': #ifdef MS_BIND flags |= MS_BIND; #else fprintf(stderr, "option 'b' (MS_BIND) not supported\n"); #endif break; case 'm': #ifdef MS_MOVE flags |= MS_MOVE; #else fprintf(stderr, "option 'm' (MS_MOVE) not supported\n"); #endif break; case 'o': orgoptions = strdup(optarg); break; case 'r': /* mount readonly */ flags |= MS_RDONLY; break; case 'U': uuid = optarg; break; case 'v': ++verboseflag; break; case 'V': print_cifs_mount_version(); exit (0); case 'w': flags &= ~MS_RDONLY; break; case 'R': rsize = atoi(optarg) ; break; case 'W': wsize = atoi(optarg); break; case '1': if (isdigit(*optarg)) { char *ep; uid = strtoul(optarg, &ep, 10); if (*ep) { fprintf(stderr, "bad uid value \"%s\"\n", optarg); exit(EX_USAGE); } } else { struct passwd *pw; if (!(pw = getpwnam(optarg))) { fprintf(stderr, "bad user name \"%s\"\n", optarg); exit(EX_USAGE); } uid = pw->pw_uid; endpwent(); } break; case '2': if (isdigit(*optarg)) { char *ep; gid = strtoul(optarg, &ep, 10); if (*ep) { fprintf(stderr, "bad gid value \"%s\"\n", optarg); exit(EX_USAGE); } } else { struct group *gr; if (!(gr = getgrnam(optarg))) { fprintf(stderr, "bad user name \"%s\"\n", optarg); exit(EX_USAGE); } gid = gr->gr_gid; endpwent(); } break; case 'u': got_user = 1; user_name = optarg; break; case 'd': domain_name = optarg; /* BB fix this - currently ignored */ got_domain = 1; break; case 'p': if(mountpassword == NULL) mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1); if(mountpassword) { got_password = 1; strlcpy(mountpassword,optarg,MOUNT_PASSWD_SIZE+1); } break; case 'S': get_password_from_file(0 /* stdin */,NULL); break; case 't': break; case 'f': ++fakemnt; break; default: fprintf(stderr, "unknown mount option %c\n",c); mount_cifs_usage(stderr); } } if((argc < 3) || (dev_name == NULL) || (mountpoint == NULL)) { mount_cifs_usage(stderr); } /* make sure mountpoint is legit */ rc = chdir(mountpoint); if (rc) { fprintf(stderr, "Couldn't chdir to %s: %s\n", mountpoint, strerror(errno)); rc = EX_USAGE; goto mount_exit; } rc = check_mountpoint(thisprogram, mountpoint); if (rc) goto mount_exit; /* sanity check for unprivileged mounts */ if (getuid()) { rc = check_fstab(thisprogram, mountpoint, dev_name, &orgoptions); if (rc) goto mount_exit; /* enable any default user mount flags */ flags |= CIFS_SETUID_FLAGS; } if (getenv("PASSWD")) { if(mountpassword == NULL) mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1); if(mountpassword) { strlcpy(mountpassword,getenv("PASSWD"),MOUNT_PASSWD_SIZE+1); got_password = 1; } } else if (getenv("PASSWD_FD")) { get_password_from_file(atoi(getenv("PASSWD_FD")),NULL); } else if (getenv("PASSWD_FILE")) { get_password_from_file(0, getenv("PASSWD_FILE")); } if (orgoptions && parse_options(&orgoptions, &flags)) { rc = EX_USAGE; goto mount_exit; } if (getuid()) { #if !CIFS_LEGACY_SETUID_CHECK if (!(flags & (MS_USERS|MS_USER))) { fprintf(stderr, "%s: permission denied\n", thisprogram); rc = EX_USAGE; goto mount_exit; } #endif /* !CIFS_LEGACY_SETUID_CHECK */ if (geteuid()) { fprintf(stderr, "%s: not installed setuid - \"user\" " "CIFS mounts not supported.", thisprogram); rc = EX_FAIL; goto mount_exit; } } flags &= ~(MS_USERS|MS_USER); addrhead = addr = parse_server(&share_name); if((addrhead == NULL) && (got_ip == 0)) { fprintf(stderr, "No ip address specified and hostname not found\n"); rc = EX_USAGE; goto mount_exit; } /* BB save off path and pop after mount returns? */ resolved_path = (char *)malloc(PATH_MAX+1); if (!resolved_path) { fprintf(stderr, "Unable to allocate memory.\n"); rc = EX_SYSERR; goto mount_exit; } /* Note that if we can not canonicalize the name, we get another chance to see if it is valid when we chdir to it */ if(!realpath(".", resolved_path)) { fprintf(stderr, "Unable to resolve %s to canonical path: %s\n", mountpoint, strerror(errno)); rc = EX_SYSERR; goto mount_exit; } mountpoint = resolved_path; if(got_user == 0) { /* Note that the password will not be retrieved from the USER env variable (ie user%password form) as there is already a PASSWD environment varaible */ if (getenv("USER")) user_name = strdup(getenv("USER")); if (user_name == NULL) user_name = getusername(); got_user = 1; } if(got_password == 0) { char *tmp_pass = getpass("Password: "); /* BB obsolete sys call but no good replacement yet. */ mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1); if (!tmp_pass || !mountpassword) { fprintf(stderr, "Password not entered, exiting\n"); exit(EX_USAGE); } strlcpy(mountpassword, tmp_pass, MOUNT_PASSWD_SIZE+1); got_password = 1; } /* FIXME launch daemon (handles dfs name resolution and credential change) remember to clear parms and overwrite password field before launching */ if(orgoptions) { optlen = strlen(orgoptions); orgoptlen = optlen; } else optlen = 0; if(share_name) optlen += strlen(share_name) + 4; else { fprintf(stderr, "No server share name specified\n"); fprintf(stderr, "\nMounting the DFS root for server not implemented yet\n"); exit(EX_USAGE); } if(user_name) optlen += strlen(user_name) + 6; optlen += MAX_ADDRESS_LEN + 4; if(mountpassword) optlen += strlen(mountpassword) + 6; mount_retry: SAFE_FREE(options); options_size = optlen + 10 + DOMAIN_SIZE; options = (char *)malloc(options_size /* space for commas in password */ + 8 /* space for domain= , domain name itself was counted as part of the length username string above */); if(options == NULL) { fprintf(stderr, "Could not allocate memory for mount options\n"); exit(EX_SYSERR); } strlcpy(options, "unc=", options_size); strlcat(options,share_name,options_size); /* scan backwards and reverse direction of slash */ temp = strrchr(options, '/'); if(temp > options + 6) *temp = '\\'; if(user_name) { /* check for syntax like user=domain\user */ if(got_domain == 0) domain_name = check_for_domain(&user_name); strlcat(options,",user=",options_size); strlcat(options,user_name,options_size); } if(retry == 0) { if(domain_name) { /* extra length accounted for in option string above */ strlcat(options,",domain=",options_size); strlcat(options,domain_name,options_size); } } strlcat(options,",ver=",options_size); strlcat(options,MOUNT_CIFS_VERSION_MAJOR,options_size); if(orgoptions) { strlcat(options,",",options_size); strlcat(options,orgoptions,options_size); } if(prefixpath) { strlcat(options,",prefixpath=",options_size); strlcat(options,prefixpath,options_size); /* no need to cat the / */ } /* convert all '\\' to '/' in share portion so that /proc/mounts looks pretty */ replace_char(dev_name, '\\', '/', strlen(share_name)); if (!got_ip && addr) { strlcat(options, ",ip=", options_size); current_len = strnlen(options, options_size); optionstail = options + current_len; switch (addr->ai_addr->sa_family) { case AF_INET6: addr6 = (struct sockaddr_in6 *) addr->ai_addr; ipaddr = inet_ntop(AF_INET6, &addr6->sin6_addr, optionstail, options_size - current_len); break; case AF_INET: addr4 = (struct sockaddr_in *) addr->ai_addr; ipaddr = inet_ntop(AF_INET, &addr4->sin_addr, optionstail, options_size - current_len); break; default: ipaddr = NULL; } /* if the address looks bogus, try the next one */ if (!ipaddr) { addr = addr->ai_next; if (addr) goto mount_retry; rc = EX_SYSERR; goto mount_exit; } } if (addr->ai_addr->sa_family == AF_INET6 && addr6->sin6_scope_id) { strlcat(options, "%", options_size); current_len = strnlen(options, options_size); optionstail = options + current_len; snprintf(optionstail, options_size - current_len, "%u", addr6->sin6_scope_id); } if(verboseflag) fprintf(stderr, "\nmount.cifs kernel mount options: %s", options); if (mountpassword) { /* * Commas have to be doubled, or else they will * look like the parameter separator */ if(retry == 0) check_for_comma(&mountpassword); strlcat(options,",pass=",options_size); strlcat(options,mountpassword,options_size); if (verboseflag) fprintf(stderr, ",pass=********"); } if (verboseflag) fprintf(stderr, "\n"); rc = check_mtab(thisprogram, dev_name, mountpoint); if (rc) goto mount_exit; if (!fakemnt && mount(dev_name, ".", cifs_fstype, flags, options)) { switch (errno) { case ECONNREFUSED: case EHOSTUNREACH: if (addr) { addr = addr->ai_next; if (addr) goto mount_retry; } break; case ENODEV: fprintf(stderr, "mount error: cifs filesystem not supported by the system\n"); break; case ENXIO: if(retry == 0) { retry = 1; if (uppercase_string(dev_name) && uppercase_string(share_name) && uppercase_string(prefixpath)) { fprintf(stderr, "retrying with upper case share name\n"); goto mount_retry; } } } fprintf(stderr, "mount error(%d): %s\n", errno, strerror(errno)); fprintf(stderr, "Refer to the mount.cifs(8) manual page (e.g. man " "mount.cifs)\n"); rc = EX_FAIL; goto mount_exit; } if (nomtab) goto mount_exit; atexit(unlock_mtab); rc = lock_mtab(); if (rc) { fprintf(stderr, "cannot lock mtab"); goto mount_exit; } pmntfile = setmntent(MOUNTED, "a+"); if (!pmntfile) { fprintf(stderr, "could not update mount table\n"); unlock_mtab(); rc = EX_FILEIO; goto mount_exit; } mountent.mnt_fsname = dev_name; mountent.mnt_dir = mountpoint; mountent.mnt_type = (char *)(void *)cifs_fstype; mountent.mnt_opts = (char *)malloc(220); if(mountent.mnt_opts) { char * mount_user = getusername(); memset(mountent.mnt_opts,0,200); if(flags & MS_RDONLY) strlcat(mountent.mnt_opts,"ro",220); else strlcat(mountent.mnt_opts,"rw",220); if(flags & MS_MANDLOCK) strlcat(mountent.mnt_opts,",mand",220); if(flags & MS_NOEXEC) strlcat(mountent.mnt_opts,",noexec",220); if(flags & MS_NOSUID) strlcat(mountent.mnt_opts,",nosuid",220); if(flags & MS_NODEV) strlcat(mountent.mnt_opts,",nodev",220); if(flags & MS_SYNCHRONOUS) strlcat(mountent.mnt_opts,",sync",220); if(mount_user) { if(getuid() != 0) { strlcat(mountent.mnt_opts, ",user=", 220); strlcat(mountent.mnt_opts, mount_user, 220); } } } mountent.mnt_freq = 0; mountent.mnt_passno = 0; rc = addmntent(pmntfile,&mountent); endmntent(pmntfile); unlock_mtab(); SAFE_FREE(mountent.mnt_opts); if (rc) rc = EX_FILEIO; mount_exit: if(mountpassword) { int len = strlen(mountpassword); memset(mountpassword,0,len); SAFE_FREE(mountpassword); } if (addrhead) freeaddrinfo(addrhead); SAFE_FREE(options); SAFE_FREE(orgoptions); SAFE_FREE(resolved_path); SAFE_FREE(share_name); exit(rc); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'mount.cifs: don't allow it to be run as setuid root program mount.cifs has been the subject of several "security" fire drills due to distributions installing it as a setuid root program. This program has not been properly audited for security and the Samba team highly recommends that it not be installed as a setuid root program at this time. To make that abundantly clear, this patch forcibly disables the ability for mount.cifs to run as a setuid root program. People are welcome to trivially patch this out, but they do so at their own peril. A security audit and redesign of this program is in progress and we hope that we'll be able to remove this in the near future. Signed-off-by: Jeff Layton <jlayton@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 int do_insn_fetch(struct x86_emulate_ctxt *ctxt, struct x86_emulate_ops *ops, unsigned long eip, void *dest, unsigned size) { int rc = 0; eip += ctxt->cs_base; while (size--) { rc = do_fetch_insn_byte(ctxt, ops, eip++, dest++); if (rc) return rc; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'KVM: x86 emulator: limit instructions to 15 bytes While we are never normally passed an instruction that exceeds 15 bytes, smp games can cause us to attempt to interpret one, which will cause large latencies in non-preempt hosts. Cc: stable@kernel.org Signed-off-by: Avi Kivity <avi@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: nma_gconf_connection_new (GConfClient *client, const char *conf_dir) { NMConnection *connection; NMAGConfConnection *gconf_connection; g_return_val_if_fail (GCONF_IS_CLIENT (client), NULL); g_return_val_if_fail (conf_dir != NULL, NULL); /* retrieve GConf data */ connection = nm_gconf_read_connection (client, conf_dir); if (connection) { gconf_connection = nma_gconf_connection_new_from_connection (client, conf_dir, connection); g_object_unref (connection); } else { nm_warning ("No connection read from GConf at %s.", conf_dir); gconf_connection = NULL; } return gconf_connection; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793) If a connection was created with a CA certificate, but the user later moved or deleted that CA certificate, the applet would simply provide the connection to NetworkManager without any CA certificate. This could cause NM to connect to the original network (or a network spoofing the original network) without verifying the identity of the network as the user expects. In the future we can/should do better here by (1) alerting the user that some connection is now no longer complete by flagging it in the connection editor or notifying the user somehow, and (2) by using a freaking' cert store already (not that Linux has one yet).'</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: constructor (GType type, guint n_construct_params, GObjectConstructParam *construct_params) { GObject *object; NMAGConfConnectionPrivate *priv; NMConnection *connection; GError *error = NULL; object = G_OBJECT_CLASS (nma_gconf_connection_parent_class)->constructor (type, n_construct_params, construct_params); if (!object) return NULL; priv = NMA_GCONF_CONNECTION_GET_PRIVATE (object); if (!priv->client) { nm_warning ("GConfClient not provided."); goto err; } if (!priv->dir) { nm_warning ("GConf directory not provided."); goto err; } connection = nm_exported_connection_get_connection (NM_EXPORTED_CONNECTION (object)); utils_fill_connection_certs (connection); if (!nm_connection_verify (connection, &error)) { utils_clear_filled_connection_certs (connection); g_warning ("Invalid connection: '%s' / '%s' invalid: %d", g_type_name (nm_connection_lookup_setting_type_by_quark (error->domain)), error->message, error->code); g_error_free (error); goto err; } utils_clear_filled_connection_certs (connection); fill_vpn_user_name (connection); return object; err: g_object_unref (object); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'core: fix CA cert mishandling after cert file deletion (deb #560067) (rh #546793) If a connection was created with a CA certificate, but the user later moved or deleted that CA certificate, the applet would simply provide the connection to NetworkManager without any CA certificate. This could cause NM to connect to the original network (or a network spoofing the original network) without verifying the identity of the network as the user expects. In the future we can/should do better here by (1) alerting the user that some connection is now no longer complete by flagging it in the connection editor or notifying the user somehow, and (2) by using a freaking' cert store already (not that Linux has one yet).'</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 usb_host_handle_control(USBHostDevice *s, USBPacket *p) { struct usbdevfs_urb *urb; AsyncURB *aurb; int ret, value, index; /* * Process certain standard device requests. * These are infrequent and are processed synchronously. */ value = le16_to_cpu(s->ctrl.req.wValue); index = le16_to_cpu(s->ctrl.req.wIndex); dprintf("husb: ctrl type 0x%x req 0x%x val 0x%x index %u len %u\n", s->ctrl.req.bRequestType, s->ctrl.req.bRequest, value, index, s->ctrl.len); if (s->ctrl.req.bRequestType == 0) { switch (s->ctrl.req.bRequest) { case USB_REQ_SET_ADDRESS: return usb_host_set_address(s, value); case USB_REQ_SET_CONFIGURATION: return usb_host_set_config(s, value & 0xff); } } if (s->ctrl.req.bRequestType == 1 && s->ctrl.req.bRequest == USB_REQ_SET_INTERFACE) return usb_host_set_interface(s, index, value); /* The rest are asynchronous */ aurb = async_alloc(); aurb->hdev = s; aurb->packet = p; /* * Setup ctrl transfer. * * s->ctrl is layed out such that data buffer immediately follows * 'req' struct which is exactly what usbdevfs expects. */ urb = &aurb->urb; urb->type = USBDEVFS_URB_TYPE_CONTROL; urb->endpoint = p->devep; urb->buffer = &s->ctrl.req; urb->buffer_length = 8 + s->ctrl.len; urb->usercontext = s; ret = ioctl(s->fd, USBDEVFS_SUBMITURB, urb); dprintf("husb: submit ctrl. len %u aurb %p\n", urb->buffer_length, aurb); if (ret < 0) { dprintf("husb: submit failed. errno %d\n", errno); async_free(aurb); switch(errno) { case ETIMEDOUT: return USB_RET_NAK; case EPIPE: default: return USB_RET_STALL; } } usb_defer_packet(p, async_cancel, aurb); return USB_RET_ASYNC; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'usb-linux.c: fix buffer overflow In usb-linux.c:usb_host_handle_control, we pass a 1024-byte buffer and length to the kernel. However, the length was provided by the caller of dev->handle_packet, and is not checked, so the kernel might provide too much data and overflow our buffer. For example, hw/usb-uhci.c could set the length to 2047. hw/usb-ohci.c looks like it might go up to 4096 or 8192. This causes a qemu crash, as reported here: http://www.mail-archive.com/kvm@vger.kernel.org/msg18447.html This patch increases the usb-linux.c buffer size to 2048 to fix the specific device reported, and adds a check to avoid the overflow in any case. Signed-off-by: Jim Paris <jim@jtan.com> Signed-off-by: Anthony Liguori <aliguori@us.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 NTSTATUS smb_set_file_unix_link(connection_struct *conn, struct smb_request *req, const char *pdata, int total_data, const struct smb_filename *smb_fname) { char *link_target = NULL; const char *newname = smb_fname->base_name; NTSTATUS status = NT_STATUS_OK; TALLOC_CTX *ctx = talloc_tos(); /* Set a symbolic link. */ /* Don't allow this if follow links is false. */ if (total_data == 0) { return NT_STATUS_INVALID_PARAMETER; } if (!lp_symlinks(SNUM(conn))) { return NT_STATUS_ACCESS_DENIED; } srvstr_pull_talloc(ctx, pdata, req->flags2, &link_target, pdata, total_data, STR_TERMINATE); if (!link_target) { return NT_STATUS_INVALID_PARAMETER; } /* !widelinks forces the target path to be within the share. */ /* This means we can interpret the target as a pathname. */ if (!lp_widelinks(SNUM(conn))) { char *rel_name = NULL; char *last_dirp = NULL; if (*link_target == '/') { /* No absolute paths allowed. */ return NT_STATUS_ACCESS_DENIED; } rel_name = talloc_strdup(ctx,newname); if (!rel_name) { return NT_STATUS_NO_MEMORY; } last_dirp = strrchr_m(rel_name, '/'); if (last_dirp) { last_dirp[1] = '\0'; } else { rel_name = talloc_strdup(ctx,"./"); if (!rel_name) { return NT_STATUS_NO_MEMORY; } } rel_name = talloc_asprintf_append(rel_name, "%s", link_target); if (!rel_name) { return NT_STATUS_NO_MEMORY; } status = check_name(conn, rel_name); if (!NT_STATUS_IS_OK(status)) { return status; } } DEBUG(10,("smb_set_file_unix_link: SMB_SET_FILE_UNIX_LINK doing symlink %s -> %s\n", newname, link_target )); if (SMB_VFS_SYMLINK(conn,link_target,newname) != 0) { return map_nt_error_from_unix(errno); } return NT_STATUS_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Fix bug 7104 - "wide links" and "unix extensions" are incompatible. Change parameter "wide links" to default to "no". Ensure "wide links = no" if "unix extensions = yes" on a share. Fix man pages to refect this. Remove "within share" checks for a UNIX symlink set - even if widelinks = no. The server will not follow that link anyway. Correct DEBUG message in check_reduced_name() to add missing "\n" so it's really clear when a path is being denied as it's outside the enclosing share path. Jeremy.'</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: long do_io_submit(aio_context_t ctx_id, long nr, struct iocb __user *__user *iocbpp, bool compat) { struct kioctx *ctx; long ret = 0; int i; struct hlist_head batch_hash[AIO_BATCH_HASH_SIZE] = { { 0, }, }; if (unlikely(nr < 0)) return -EINVAL; if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp))))) return -EFAULT; ctx = lookup_ioctx(ctx_id); if (unlikely(!ctx)) { pr_debug("EINVAL: io_submit: invalid context id\n"); return -EINVAL; } /* * AKPM: should this return a partial result if some of the IOs were * successfully submitted? */ for (i=0; i<nr; i++) { struct iocb __user *user_iocb; struct iocb tmp; if (unlikely(__get_user(user_iocb, iocbpp + i))) { ret = -EFAULT; break; } if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) { ret = -EFAULT; break; } ret = io_submit_one(ctx, user_iocb, &tmp, batch_hash, compat); if (ret) break; } aio_batch_free(batch_hash); put_ioctx(ctx); return i ? i : ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'aio: check for multiplication overflow in do_io_submit Tavis Ormandy pointed out that do_io_submit does not do proper bounds checking on the passed-in iocb array:        if (unlikely(nr < 0))                return -EINVAL;        if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(iocbpp)))))                return -EFAULT;                      ^^^^^^^^^^^^^^^^^^ The attached patch checks for overflow, and if it is detected, the number of iocbs submitted is scaled down to a number that will fit in the long.  This is an ok thing to do, as sys_io_submit is documented as returning the number of iocbs submitted, so callers should handle a return value of less than the 'nr' argument passed in. Reported-by: Tavis Ormandy <taviso@cmpxchg8b.com> Signed-off-by: Jeff Moyer <jmoyer@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 void vmx_save_host_state(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); int i; if (vmx->host_state.loaded) return; vmx->host_state.loaded = 1; /* * Set host fs and gs selectors. Unfortunately, 22.2.3 does not * allow segment selectors with cpl > 0 or ti == 1. */ vmx->host_state.ldt_sel = kvm_read_ldt(); vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel; vmx->host_state.fs_sel = kvm_read_fs(); if (!(vmx->host_state.fs_sel & 7)) { vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel); vmx->host_state.fs_reload_needed = 0; } else { vmcs_write16(HOST_FS_SELECTOR, 0); vmx->host_state.fs_reload_needed = 1; } vmx->host_state.gs_sel = kvm_read_gs(); if (!(vmx->host_state.gs_sel & 7)) vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel); else { vmcs_write16(HOST_GS_SELECTOR, 0); vmx->host_state.gs_ldt_reload_needed = 1; } #ifdef CONFIG_X86_64 vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE)); vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE)); #else vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel)); vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel)); #endif #ifdef CONFIG_X86_64 if (is_long_mode(&vmx->vcpu)) { rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base); wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base); } #endif for (i = 0; i < vmx->save_nmsrs; ++i) kvm_set_shared_msr(vmx->guest_msrs[i].index, vmx->guest_msrs[i].data, vmx->guest_msrs[i].mask); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'KVM: Fix fs/gs reload oops with invalid ldt kvm reloads the host's fs and gs blindly, however the underlying segment descriptors may be invalid due to the user modifying the ldt after loading them. Fix by using the safe accessors (loadsegment() and load_gs_index()) instead of home grown unsafe versions. This is CVE-2010-3698. KVM-Stable-Tag. Signed-off-by: Avi Kivity <avi@redhat.com> Signed-off-by: Marcelo Tosatti <mtosatti@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 int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct net_device *dev; struct sock *sk = sock->sk; if (peer) return -EOPNOTSUPP; uaddr->sa_family = AF_PACKET; rcu_read_lock(); dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex); if (dev) strlcpy(uaddr->sa_data, dev->name, 15); else memset(uaddr->sa_data, 0, 14); rcu_read_unlock(); *uaddr_len = sizeof(*uaddr); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-909'], 'message': 'net: packet: fix information leak to userland packet_getname_spkt() doesn't initialize all members of sa_data field of sockaddr struct if strlen(dev->name) < 13. This structure is then copied to userland. It leads to leaking of contents of kernel stack memory. We have to fully fill sa_data with strncpy() instead of strlcpy(). The same with packet_getname(): it doesn't initialize sll_pkttype field of sockaddr_ll. Set it to zero. Signed-off-by: Vasiliy Kulikov <segooon@gmail.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 udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { struct udp_sock *up = udp_sk(sk); int rc; int is_udplite = IS_UDPLITE(sk); /* * Charge it to the socket, dropping if the queue is full. */ if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) goto drop; nf_reset(skb); if (up->encap_type) { /* * This is an encapsulation socket so pass the skb to * the socket's udp_encap_rcv() hook. Otherwise, just * fall through and pass this up the UDP socket. * up->encap_rcv() returns the following value: * =0 if skb was successfully passed to the encap * handler or was discarded by it. * >0 if skb should be passed on to UDP. * <0 if skb should be resubmitted as proto -N */ /* if we're overly short, let UDP handle it */ if (skb->len > sizeof(struct udphdr) && up->encap_rcv != NULL) { int ret; ret = (*up->encap_rcv)(sk, skb); if (ret <= 0) { UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); return -ret; } } /* FALLTHROUGH -- it's a UDP Packet */ } /* * UDP-Lite specific tests, ignored on UDP sockets */ if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) { /* * MIB statistics other than incrementing the error count are * disabled for the following two types of errors: these depend * on the application settings, not on the functioning of the * protocol stack as such. * * RFC 3828 here recommends (sec 3.3): "There should also be a * way ... to ... at least let the receiving application block * delivery of packets with coverage values less than a value * provided by the application." */ if (up->pcrlen == 0) { /* full coverage was set */ LIMIT_NETDEBUG(KERN_WARNING "UDPLITE: partial coverage " "%d while full coverage %d requested\n", UDP_SKB_CB(skb)->cscov, skb->len); goto drop; } /* The next case involves violating the min. coverage requested * by the receiver. This is subtle: if receiver wants x and x is * greater than the buffersize/MTU then receiver will complain * that it wants x while sender emits packets of smaller size y. * Therefore the above ...()->partial_cov statement is essential. */ if (UDP_SKB_CB(skb)->cscov < up->pcrlen) { LIMIT_NETDEBUG(KERN_WARNING "UDPLITE: coverage %d too small, need min %d\n", UDP_SKB_CB(skb)->cscov, up->pcrlen); goto drop; } } if (sk->sk_filter) { if (udp_lib_checksum_complete(skb)) goto drop; } rc = 0; bh_lock_sock(sk); if (!sock_owned_by_user(sk)) rc = __udp_queue_rcv_skb(sk, skb); else if (sk_add_backlog(sk, skb)) { bh_unlock_sock(sk); goto drop; } bh_unlock_sock(sk); return rc; drop: UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); atomic_inc(&sk->sk_drops); kfree_skb(skb); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'net: sk_add_backlog() take rmem_alloc into account Current socket backlog limit is not enough to really stop DDOS attacks, because user thread spend many time to process a full backlog each round, and user might crazy spin on socket lock. We should add backlog size and receive_queue size (aka rmem_alloc) to pace writers, and let user run without being slow down too much. Introduce a sk_rcvqueues_full() helper, to avoid taking socket lock in stress situations. Under huge stress from a multiqueue/RPS enabled NIC, a single flow udp receiver can now process ~200.000 pps (instead of ~100 pps before the patch) on a 8 core machine. Signed-off-by: Eric Dumazet <eric.dumazet@gmail.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 xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op, xmlNodeSetPtr set, int contextSize, int minPos, int maxPos, int hasNsNodes) { if (op->ch1 != -1) { xmlXPathCompExprPtr comp = ctxt->comp; if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) { /* * TODO: raise an internal error. */ } contextSize = xmlXPathCompOpEvalPredicate(ctxt, &comp->steps[op->ch1], set, contextSize, hasNsNodes); CHECK_ERROR0; if (contextSize <= 0) return(0); } /* * Check if the node set contains a sufficient number of nodes for * the requested range. */ if (contextSize < minPos) { xmlXPathNodeSetClear(set, hasNsNodes); return(0); } if (op->ch2 == -1) { /* * TODO: Can this ever happen? */ return (contextSize); } else { xmlDocPtr oldContextDoc; int i, pos = 0, newContextSize = 0, contextPos = 0, res; xmlXPathStepOpPtr exprOp; xmlXPathObjectPtr contextObj = NULL, exprRes = NULL; xmlNodePtr oldContextNode, contextNode = NULL; xmlXPathContextPtr xpctxt = ctxt->context; #ifdef LIBXML_XPTR_ENABLED /* * URGENT TODO: Check the following: * We don't expect location sets if evaluating prediates, right? * Only filters should expect location sets, right? */ #endif /* LIBXML_XPTR_ENABLED */ /* * Save old context. */ oldContextNode = xpctxt->node; oldContextDoc = xpctxt->doc; /* * Get the expression of this predicate. */ exprOp = &ctxt->comp->steps[op->ch2]; for (i = 0; i < set->nodeNr; i++) { if (set->nodeTab[i] == NULL) continue; contextNode = set->nodeTab[i]; xpctxt->node = contextNode; xpctxt->contextSize = contextSize; xpctxt->proximityPosition = ++contextPos; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ if ((contextNode->type != XML_NAMESPACE_DECL) && (contextNode->doc != NULL)) xpctxt->doc = contextNode->doc; /* * Evaluate the predicate expression with 1 context node * at a time; this node is packaged into a node set; this * node set is handed over to the evaluation mechanism. */ if (contextObj == NULL) contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode); else xmlXPathNodeSetAddUnique(contextObj->nodesetval, contextNode); valuePush(ctxt, contextObj); res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1); if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) { xmlXPathObjectPtr tmp; /* pop the result */ tmp = valuePop(ctxt); xmlXPathReleaseObject(xpctxt, tmp); /* then pop off contextObj, which will be freed later */ valuePop(ctxt); goto evaluation_error; } if (res) pos++; if (res && (pos >= minPos) && (pos <= maxPos)) { /* * Fits in the requested range. */ newContextSize++; if (minPos == maxPos) { /* * Only 1 node was requested. */ if (contextNode->type == XML_NAMESPACE_DECL) { /* * As always: take care of those nasty * namespace nodes. */ set->nodeTab[i] = NULL; } xmlXPathNodeSetClear(set, hasNsNodes); set->nodeNr = 1; set->nodeTab[0] = contextNode; goto evaluation_exit; } if (pos == maxPos) { /* * We are done. */ xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes); goto evaluation_exit; } } else { /* * Remove the entry from the initial node set. */ set->nodeTab[i] = NULL; if (contextNode->type == XML_NAMESPACE_DECL) xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode); } if (exprRes != NULL) { xmlXPathReleaseObject(ctxt->context, exprRes); exprRes = NULL; } if (ctxt->value == contextObj) { /* * Don't free the temporary XPath object holding the * context node, in order to avoid massive recreation * inside this loop. */ valuePop(ctxt); xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes); } else { /* * The object was lost in the evaluation machinery. * Can this happen? Maybe in case of internal-errors. */ contextObj = NULL; } } goto evaluation_exit; evaluation_error: xmlXPathNodeSetClear(set, hasNsNodes); newContextSize = 0; evaluation_exit: if (contextObj != NULL) { if (ctxt->value == contextObj) valuePop(ctxt); xmlXPathReleaseObject(xpctxt, contextObj); } if (exprRes != NULL) xmlXPathReleaseObject(ctxt->context, exprRes); /* * Reset/invalidate the context. */ xpctxt->node = oldContextNode; xpctxt->doc = oldContextDoc; xpctxt->contextSize = -1; xpctxt->proximityPosition = -1; return(newContextSize); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix a potential freeing error in XPath'</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 mainloop(CLIENT *client) { struct nbd_request request; struct nbd_reply reply; gboolean go_on=TRUE; #ifdef DODBG int i = 0; #endif negotiate(client->net, client, NULL); DEBUG("Entering request loop!\n"); reply.magic = htonl(NBD_REPLY_MAGIC); reply.error = 0; while (go_on) { char buf[BUFSIZE]; size_t len; #ifdef DODBG i++; printf("%d: ", i); #endif readit(client->net, &request, sizeof(request)); request.from = ntohll(request.from); request.type = ntohl(request.type); if (request.type==NBD_CMD_DISC) { msg2(LOG_INFO, "Disconnect request received."); if (client->server->flags & F_COPYONWRITE) { if (client->difmap) g_free(client->difmap) ; close(client->difffile); unlink(client->difffilename); free(client->difffilename); } go_on=FALSE; continue; } len = ntohl(request.len); if (request.magic != htonl(NBD_REQUEST_MAGIC)) err("Not enough magic."); if (len > BUFSIZE + sizeof(struct nbd_reply)) err("Request too big!"); #ifdef DODBG printf("%s from %llu (%llu) len %d, ", request.type ? "WRITE" : "READ", (unsigned long long)request.from, (unsigned long long)request.from / 512, len); #endif memcpy(reply.handle, request.handle, sizeof(reply.handle)); if ((request.from + len) > (OFFT_MAX)) { DEBUG("[Number too large!]"); ERROR(client, reply, EINVAL); continue; } if (((ssize_t)((off_t)request.from + len) > client->exportsize)) { DEBUG("[RANGE!]"); ERROR(client, reply, EINVAL); continue; } if (request.type==NBD_CMD_WRITE) { DEBUG("wr: net->buf, "); readit(client->net, buf, len); DEBUG("buf->exp, "); if ((client->server->flags & F_READONLY) || (client->server->flags & F_AUTOREADONLY)) { DEBUG("[WRITE to READONLY!]"); ERROR(client, reply, EPERM); continue; } if (expwrite(request.from, buf, len, client)) { DEBUG("Write failed: %m" ); ERROR(client, reply, errno); continue; } SEND(client->net, reply); DEBUG("OK!\n"); continue; } /* READ */ DEBUG("exp->buf, "); if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { DEBUG("Read failed: %m"); ERROR(client, reply, errno); continue; } DEBUG("buf->net, "); memcpy(buf, &reply, sizeof(struct nbd_reply)); writeit(client->net, buf, len + sizeof(struct nbd_reply)); DEBUG("OK!\n"); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix buffer size checking Yes, this means we've re-introduced CVE-2005-3534. Sigh.'</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 tpm_open(struct inode *inode, struct file *file) { int minor = iminor(inode); struct tpm_chip *chip = NULL, *pos; rcu_read_lock(); list_for_each_entry_rcu(pos, &tpm_chip_list, list) { if (pos->vendor.miscdev.minor == minor) { chip = pos; get_device(chip->dev); break; } } rcu_read_unlock(); if (!chip) return -ENODEV; if (test_and_set_bit(0, &chip->is_open)) { dev_dbg(chip->dev, "Another process owns this TPM\n"); put_device(chip->dev); return -EBUSY; } chip->data_buffer = kmalloc(TPM_BUFSIZE * sizeof(u8), GFP_KERNEL); if (chip->data_buffer == NULL) { clear_bit(0, &chip->is_open); put_device(chip->dev); return -ENOMEM; } atomic_set(&chip->data_pending, 0); file->private_data = chip; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'char/tpm: Fix unitialized usage of data buffer This patch fixes information leakage to the userspace by initializing the data buffer to zero. Reported-by: Peter Huewe <huewe.external@infineon.com> Signed-off-by: Peter Huewe <huewe.external@infineon.com> Signed-off-by: Marcel Selhorst <m.selhorst@sirrix.com> [ Also removed the silly "* sizeof(u8)". If that isn't 1, we have way deeper problems than a simple multiplication can fix. - Linus ] 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: network_init () { #ifdef HAVE_GNUTLS char *ca_path, *ca_path2; gnutls_global_init (); gnutls_certificate_allocate_credentials (&gnutls_xcred); ca_path = string_expand_home (CONFIG_STRING(config_network_gnutls_ca_file)); if (ca_path) { ca_path2 = string_replace (ca_path, "%h", weechat_home); if (ca_path2) { gnutls_certificate_set_x509_trust_file (gnutls_xcred, ca_path2, GNUTLS_X509_FMT_PEM); free (ca_path2); } free (ca_path); } gnutls_certificate_client_set_retrieve_function (gnutls_xcred, &hook_connect_gnutls_set_certificates); network_init_ok = 1; #endif #ifdef HAVE_GCRYPT gcry_check_version (GCRYPT_VERSION); gcry_control (GCRYCTL_DISABLE_SECMEM, 0); gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix verification of SSL certificates by calling gnutls verify callback (patch #7459)'</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: do_ip6t_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case IP6T_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case IP6T_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case IP6T_SO_GET_REVISION_MATCH: case IP6T_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; int target; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } if (cmd == IP6T_SO_GET_REVISION_TARGET) target = 1; else target = 0; try_then_request_module(xt_find_revision(AF_INET6, rev.name, rev.revision, target, &ret), "ip6t_%s", rev.name); break; } default: duprintf("do_ip6t_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'ipv6: netfilter: ip6_tables: fix infoleak to userspace Structures ip6t_replace, compat_ip6t_replace, and xt_get_revision are copied from userspace. Fields of these structs that are zero-terminated strings are not checked. When they are used as argument to a format string containing "%s" in request_module(), some sensitive information is leaked to userspace via argument of spawned modprobe process. The first bug was introduced before the git epoch; the second was introduced in 3bc3fe5e (v2.6.25-rc1); the third is introduced by 6b7d31fc (v2.6.15-rc1). To trigger the bug one should have CAP_NET_ADMIN. Signed-off-by: Vasiliy Kulikov <segoon@openwall.com> Signed-off-by: Patrick McHardy <kaber@trash.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: processBatchMultiRuleset(batch_t *pBatch) { ruleset_t *currRuleset; batch_t snglRuleBatch; int i; int iStart; /* start index of partial batch */ int iNew; /* index for new (temporary) batch */ DEFiRet; CHKiRet(batchInit(&snglRuleBatch, pBatch->nElem)); snglRuleBatch.pbShutdownImmediate = pBatch->pbShutdownImmediate; while(1) { /* loop broken inside */ /* search for first unprocessed element */ for(iStart = 0 ; iStart < pBatch->nElem && pBatch->pElem[iStart].state == BATCH_STATE_DISC ; ++iStart) /* just search, no action */; if(iStart == pBatch->nElem) FINALIZE; /* everything processed */ /* prepare temporary batch */ currRuleset = batchElemGetRuleset(pBatch, iStart); iNew = 0; for(i = iStart ; i < pBatch->nElem ; ++i) { if(batchElemGetRuleset(pBatch, i) == currRuleset) { batchCopyElem(&(snglRuleBatch.pElem[iNew++]), &(pBatch->pElem[i])); /* We indicate the element also as done, so it will not be processed again */ pBatch->pElem[i].state = BATCH_STATE_DISC; } } snglRuleBatch.nElem = iNew; /* was left just right by the for loop */ batchSetSingleRuleset(&snglRuleBatch, 1); /* process temp batch */ processBatch(&snglRuleBatch); } batchFree(&snglRuleBatch); finalize_it: RETiRet; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'bugfix: fixed a memory leak and potential abort condition this could happen if multiple rulesets were used and some output batches contained messages belonging to more than one ruleset. fixes: http://bugzilla.adiscon.com/show_bug.cgi?id=226 fixes: http://bugzilla.adiscon.com/show_bug.cgi?id=218'</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 mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb) { ReflectionMethodBuilder rmb; MonoMethodSignature *sig; MonoClass *klass; GSList *l; int i; sig = dynamic_method_to_signature (mb); reflection_methodbuilder_from_dynamic_method (&rmb, mb); /* * Resolve references. */ /* * Every second entry in the refs array is reserved for storing handle_class, * which is needed by the ldtoken implementation in the JIT. */ rmb.nrefs = mb->nrefs; rmb.refs = g_new0 (gpointer, mb->nrefs + 1); for (i = 0; i < mb->nrefs; i += 2) { MonoClass *handle_class; gpointer ref; MonoObject *obj = mono_array_get (mb->refs, MonoObject*, i); if (strcmp (obj->vtable->klass->name, "DynamicMethod") == 0) { MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj; /* * The referenced DynamicMethod should already be created by the managed * code, except in the case of circular references. In that case, we store * method in the refs array, and fix it up later when the referenced * DynamicMethod is created. */ if (method->mhandle) { ref = method->mhandle; } else { /* FIXME: GC object stored in unmanaged memory */ ref = method; /* FIXME: GC object stored in unmanaged memory */ method->referenced_by = g_slist_append (method->referenced_by, mb); } handle_class = mono_defaults.methodhandle_class; } else { MonoException *ex = NULL; ref = resolve_object (mb->module->image, obj, &handle_class, NULL); if (!ref) ex = mono_get_exception_type_load (NULL, NULL); else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) ex = mono_security_core_clr_ensure_dynamic_method_resolved_object (ref, handle_class); if (ex) { g_free (rmb.refs); mono_raise_exception (ex); return; } } rmb.refs [i] = ref; /* FIXME: GC object stored in unmanaged memory (change also resolve_object() signature) */ rmb.refs [i + 1] = handle_class; } klass = mb->owner ? mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mb->owner)) : mono_defaults.object_class; mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig); /* Fix up refs entries pointing at us */ for (l = mb->referenced_by; l; l = l->next) { MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)l->data; MonoMethodWrapper *wrapper = (MonoMethodWrapper*)method->mhandle; gpointer *data; g_assert (method->mhandle); data = (gpointer*)wrapper->method_data; for (i = 0; i < GPOINTER_TO_UINT (data [0]); i += 2) { if ((data [i + 1] == mb) && (data [i + 1 + 1] == mono_defaults.methodhandle_class)) data [i + 1] = mb->mhandle; } } g_slist_free (mb->referenced_by); g_free (rmb.refs); /* ilgen is no longer needed */ mb->ilgen = NULL; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-264'], 'message': 'Don't use finalization to cleanup dynamic methods. * reflection.c: Use a reference queue to cleanup dynamic methods instead of finalization. * runtime.c: Shutdown the dynamic method queue before runtime cleanup begins. * DynamicMethod.cs: No longer finalizable. * icall-def.h: Remove unused dynamic method icall. Fixes #660422 Implement a reference queue API. * gc.c: A reference queue allows one to queue callbcks for when objects are collected. It allows for safe cleanup of objects that can only be done when it is effectively collected. The major difference with regular finalization is that the collector makes sure the object was collected - and can't be resurrected. * gc-internal.h: Export entrypoints for the new API.'</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 virtio_blk_handle_write(VirtIOBlockReq *req, MultiReqBuffer *mrb) { BlockRequest *blkreq; uint64_t sector; sector = ldq_p(&req->out->sector); trace_virtio_blk_handle_write(req, sector, req->qiov.size / 512); if (sector & req->dev->sector_mask) { virtio_blk_rw_complete(req, -EIO); return; } if (mrb->num_writes == 32) { virtio_submit_multiwrite(req->dev->bs, mrb); } blkreq = &mrb->blkreq[mrb->num_writes]; blkreq->sector = sector; blkreq->nb_sectors = req->qiov.size / BDRV_SECTOR_SIZE; blkreq->qiov = &req->qiov; blkreq->cb = virtio_blk_rw_complete; blkreq->opaque = req; blkreq->error = 0; mrb->num_writes++; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'virtio-blk: fail unaligned requests Like all block drivers virtio-blk should not allow small than block size granularity access. But given that the protocol specifies a byte unit length field we currently accept such requests, which cause qemu to abort() in lower layers. Add checks to the main read and write handlers to catch them early. Reported-by: Conor Murphy <conor_murphy_virt@hotmail.com> Tested-by: Conor Murphy <conor_murphy_virt@hotmail.com> Signed-off-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Stefan Hajnoczi <stefanha@linux.vnet.ibm.com> Signed-off-by: Kevin Wolf <kwolf@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: const char *string_of_NPNVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPNVxDisplay); _(NPNVxtAppContext); _(NPNVnetscapeWindow); _(NPNVjavascriptEnabledBool); _(NPNVasdEnabledBool); _(NPNVisOfflineBool); _(NPNVserviceManager); _(NPNVDOMElement); _(NPNVDOMWindow); _(NPNVToolkit); _(NPNVSupportsXEmbedBool); _(NPNVWindowNPObject); _(NPNVPluginElementNPObject); _(NPNVSupportsWindowless); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPNVserviceManager); _(11, NPNVDOMElement); _(12, NPNVDOMWindow); _(13, NPNVToolkit); #undef _ default: str = "<unknown variable>"; break; } break; } return str; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Support all the new variables added'</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 cli_hm_scan(const unsigned char *digest, uint32_t size, const char **virname, const struct cli_matcher *root, enum CLI_HASH_TYPE type) { const struct cli_htu32_element *item; unsigned int keylen; struct cli_sz_hash *szh; size_t l, r; if(!digest || !size || size == 0xffffffff || !root || !root->hm.sizehashes[type].capacity) return CL_CLEAN; item = cli_htu32_find(&root->hm.sizehashes[type], size); if(!item) return CL_CLEAN; szh = (struct cli_sz_hash *)item->data.as_ptr; keylen = hashlen[type]; l = 0; r = szh->items; while(l <= r) { size_t c = (l + r) / 2; int res = hm_cmp(digest, &szh->hash_array[keylen * c], keylen); if(res < 0) { if(!c) break; r = c - 1; } else if(res > 0) l = c + 1; else { if(virname) *virname = szh->virusnames[c]; return CL_VIRUS; } } return CL_CLEAN; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'bb#2818'</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: gdk_pixbuf__tiff_image_load (FILE *f, GError **error) { return gdk_pixbuf__tiff_image_load_real (f, NULL, error); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <jrb@redhat.com> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</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: gdk_pixbuf__tiff_image_stop_load (gpointer data, GError **error) { TiffData *context = (TiffData*) data; gboolean retval = FALSE; g_return_val_if_fail (data != NULL, TRUE); fflush (context->file); rewind (context->file); if (context->all_okay) { GdkPixbuf *pixbuf; pixbuf = gdk_pixbuf__tiff_image_load_real (context->file, context, error); if (pixbuf != NULL) retval = TRUE; } fclose (context->file); unlink (context->tempname); g_free (context->tempname); g_free ((TiffData *) context); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <jrb@redhat.com> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</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: jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; long rem; value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &rem); value->tv_usec = rem / NSEC_PER_USEC; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <zippel@linux-m68k.org> Cc: Ralf Baechle <ralf@linux-mips.org> Cc: Ingo Molnar <mingo@elte.hu> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: john stultz <johnstul@us.ibm.com> Cc: Christoph Lameter <clameter@sgi.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</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 sample_to_timespec(const clockid_t which_clock, union cpu_time_count cpu, struct timespec *tp) { if (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED) { tp->tv_sec = div_long_long_rem(cpu.sched, NSEC_PER_SEC, &tp->tv_nsec); } else { cputime_to_timespec(cpu.cpu, tp); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <zippel@linux-m68k.org> Cc: Ralf Baechle <ralf@linux-mips.org> Cc: Ingo Molnar <mingo@elte.hu> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: john stultz <johnstul@us.ibm.com> Cc: Christoph Lameter <clameter@sgi.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</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: valuePop(xmlXPathParserContextPtr ctxt) { xmlXPathObjectPtr ret; if ((ctxt == NULL) || (ctxt->valueNr <= 0)) return (NULL); ctxt->valueNr--; if (ctxt->valueNr > 0) ctxt->value = ctxt->valueTab[ctxt->valueNr - 1]; else ctxt->value = NULL; ret = ctxt->valueTab[ctxt->valueNr]; ctxt->valueTab[ctxt->valueNr] = NULL; return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Hardening of XPath evaluation Add a mechanism of frame for XPath evaluation when entering a function or a scoped evaluation, also fix a potential problem in predicate evaluation.'</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 int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev); int32_t len; uint8_t command; uint8_t *outbuf; int rc; command = buf[0]; outbuf = (uint8_t *)r->iov.iov_base; DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", req->lun, req->tag, buf[0]); #ifdef DEBUG_SCSI { int i; for (i = 1; i < r->req.cmd.len; i++) { printf(" 0x%02x", buf[i]); } printf("\n"); } #endif switch (command) { case TEST_UNIT_READY: case INQUIRY: case MODE_SENSE: case MODE_SENSE_10: case RESERVE: case RESERVE_10: case RELEASE: case RELEASE_10: case START_STOP: case ALLOW_MEDIUM_REMOVAL: case READ_CAPACITY_10: case READ_TOC: case GET_CONFIGURATION: case SERVICE_ACTION_IN_16: case VERIFY_10: rc = scsi_disk_emulate_command(r, outbuf); if (rc < 0) { return 0; } r->iov.iov_len = rc; break; case SYNCHRONIZE_CACHE: bdrv_acct_start(s->bs, &r->acct, 0, BDRV_ACCT_FLUSH); r->req.aiocb = bdrv_aio_flush(s->bs, scsi_flush_complete, r); if (r->req.aiocb == NULL) { scsi_flush_complete(r, -EIO); } return 0; case READ_6: case READ_10: case READ_12: case READ_16: len = r->req.cmd.xfer / s->qdev.blocksize; DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len); if (r->req.cmd.lba > s->max_lba) goto illegal_lba; r->sector = r->req.cmd.lba * s->cluster_size; r->sector_count = len * s->cluster_size; break; case WRITE_6: case WRITE_10: case WRITE_12: case WRITE_16: case WRITE_VERIFY_10: case WRITE_VERIFY_12: case WRITE_VERIFY_16: len = r->req.cmd.xfer / s->qdev.blocksize; DPRINTF("Write %s(sector %" PRId64 ", count %d)\n", (command & 0xe) == 0xe ? "And Verify " : "", r->req.cmd.lba, len); if (r->req.cmd.lba > s->max_lba) goto illegal_lba; r->sector = r->req.cmd.lba * s->cluster_size; r->sector_count = len * s->cluster_size; break; case MODE_SELECT: DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer); /* We don't support mode parameter changes. Allow the mode parameter header + block descriptors only. */ if (r->req.cmd.xfer > 12) { goto fail; } break; case MODE_SELECT_10: DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer); /* We don't support mode parameter changes. Allow the mode parameter header + block descriptors only. */ if (r->req.cmd.xfer > 16) { goto fail; } break; case SEEK_6: case SEEK_10: DPRINTF("Seek(%d) (sector %" PRId64 ")\n", command == SEEK_6 ? 6 : 10, r->req.cmd.lba); if (r->req.cmd.lba > s->max_lba) { goto illegal_lba; } break; case WRITE_SAME_16: len = r->req.cmd.xfer / s->qdev.blocksize; DPRINTF("WRITE SAME(16) (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len); if (r->req.cmd.lba > s->max_lba) { goto illegal_lba; } /* * We only support WRITE SAME with the unmap bit set for now. */ if (!(buf[1] & 0x8)) { goto fail; } rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size, len * s->cluster_size); if (rc < 0) { /* XXX: better error code ?*/ goto fail; } break; case REQUEST_SENSE: abort(); default: DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]); scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE)); return 0; fail: scsi_check_condition(r, SENSE_CODE(INVALID_FIELD)); return 0; illegal_lba: scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE)); return 0; } if (r->sector_count == 0 && r->iov.iov_len == 0) { scsi_req_complete(&r->req, GOOD); } len = r->sector_count * 512 + r->iov.iov_len; if (r->req.cmd.mode == SCSI_XFER_TO_DEV) { return -len; } else { if (!r->sector_count) r->sector_count = -1; return len; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Kevin Wolf <kwolf@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: void list_proxy(char *server, void *data __attribute__((unused)), void *rock) { struct enum_rock *erock = (struct enum_rock *) rock; struct backend *be; int r; char *result; be = proxy_findserver(server, &nntp_protocol, nntp_userid ? nntp_userid : "anonymous", &backend_cached, &backend_current, NULL, nntp_in); if (!be) return; prot_printf(be->out, "LIST %s %s\r\n", erock->cmd, erock->wild); r = read_response(be, 0, &result); if (!r && !strncmp(result, "215 ", 4)) { while (!(r = read_response(be, 0, &result)) && result[0] != '.') { prot_printf(nntp_out, "%s", result); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'Secunia SA46093 - make sure nntp authentication completes Discovered by Stefan Cornelius, Secunia Research The vulnerability is caused due to the access restriction for certain commands only checking whether or not variable "nntp_userid" is non-NULL, without performing additional checks to verify that a complete, successful authentication actually took place. The variable "nntp_userid" can be set to point to a string holding the username (changing it to a non-NULL, thus allowing attackers to bypass the checks) by sending an "AUTHINFO USER" command. The variable is not reset to NULL until e.g. a wrong "AUTHINFO PASS" command is received. This can be exploited to bypass the authentication mechanism and allows access to e.g. the "NEWNEWS" or the "LIST NEWSGROUPS" commands by sending an "AUTHINFO USER" command without a following "AUTHINFO PASS" command.'</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: add_mtab(char *devname, char *mountpoint, unsigned long flags) { int rc = 0; char *mount_user; struct mntent mountent; FILE *pmntfile; atexit(unlock_mtab); rc = lock_mtab(); if (rc) { fprintf(stderr, "cannot lock mtab"); rc = EX_FILEIO; goto add_mtab_exit; } pmntfile = setmntent(MOUNTED, "a+"); if (!pmntfile) { fprintf(stderr, "could not update mount table\n"); unlock_mtab(); rc = EX_FILEIO; goto add_mtab_exit; } mountent.mnt_fsname = devname; mountent.mnt_dir = mountpoint; mountent.mnt_type = (char *)(void *)cifs_fstype; mountent.mnt_opts = (char *)calloc(MTAB_OPTIONS_LEN, 1); if (mountent.mnt_opts) { if (flags & MS_RDONLY) strlcat(mountent.mnt_opts, "ro", MTAB_OPTIONS_LEN); else strlcat(mountent.mnt_opts, "rw", MTAB_OPTIONS_LEN); if (flags & MS_MANDLOCK) strlcat(mountent.mnt_opts, ",mand", MTAB_OPTIONS_LEN); if (flags & MS_NOEXEC) strlcat(mountent.mnt_opts, ",noexec", MTAB_OPTIONS_LEN); if (flags & MS_NOSUID) strlcat(mountent.mnt_opts, ",nosuid", MTAB_OPTIONS_LEN); if (flags & MS_NODEV) strlcat(mountent.mnt_opts, ",nodev", MTAB_OPTIONS_LEN); if (flags & MS_SYNCHRONOUS) strlcat(mountent.mnt_opts, ",sync", MTAB_OPTIONS_LEN); if (getuid() != 0) { strlcat(mountent.mnt_opts, ",user=", MTAB_OPTIONS_LEN); mount_user = getusername(); if (mount_user) strlcat(mountent.mnt_opts, mount_user, MTAB_OPTIONS_LEN); } } mountent.mnt_freq = 0; mountent.mnt_passno = 0; rc = addmntent(pmntfile, &mountent); endmntent(pmntfile); unlock_mtab(); SAFE_FREE(mountent.mnt_opts); add_mtab_exit: if (rc) { fprintf(stderr, "unable to add mount entry to mtab\n"); rc = EX_FILEIO; } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'mount.cifs: guard against signals by unprivileged users If mount.cifs is setuid root, then the unprivileged user who runs the program can send the mount.cifs process a signal and kill it. This is not a huge problem unless we happen to be updating the mtab at the time, in which case the mtab lockfiles might not get cleaned up. To remedy this, have the privileged mount.cifs process set its real uid to the effective uid (usually, root). This prevents unprivileged users from being able to signal the process. While we're at it, also mask off signals while we're updating the mtab. This leaves a SIGKILL by root as the only way to interrupt the mtab update, but there's really nothing we can do about that. Signed-off-by: Jeff Layton <jlayton@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: int32_t cli_bcapi_extract_new(struct cli_bc_ctx *ctx, int32_t id) { cli_ctx *cctx; int res = -1; cli_event_count(EV, BCEV_EXTRACTED); cli_dbgmsg("previous tempfile had %u bytes\n", ctx->written); if (!ctx->written) return 0; if (ctx->ctx && cli_updatelimits(ctx->ctx, ctx->written)) return -1; ctx->written = 0; lseek(ctx->outfd, 0, SEEK_SET); cli_dbgmsg("bytecode: scanning extracted file %s\n", ctx->tempfile); cctx = (cli_ctx*)ctx->ctx; if (cctx) { cli_file_t current = cctx->container_type; if (ctx->containertype != CL_TYPE_ANY) cctx->container_type = ctx->containertype; res = cli_magic_scandesc(ctx->outfd, cctx); cctx->container_type = current; if (res == CL_VIRUS) { if (cctx->virname) ctx->virname = *cctx->virname; ctx->found = 1; } } if ((cctx && cctx->engine->keeptmp) || (ftruncate(ctx->outfd, 0) == -1)) { close(ctx->outfd); if (!(cctx && cctx->engine->keeptmp) && ctx->tempfile) cli_unlink(ctx->tempfile); free(ctx->tempfile); ctx->tempfile = NULL; ctx->outfd = 0; } cli_dbgmsg("bytecode: extracting new file with id %u\n", id); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'fix recursion level crash (bb #3706). Thanks to Stephane Chazelas for the analysis.'</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: set_routerstatus_from_routerinfo(routerstatus_t *rs, routerinfo_t *ri, time_t now, int naming, int listbadexits, int listbaddirs, int vote_on_hsdirs) { int unstable_version = !tor_version_as_new_as(ri->platform,"0.1.1.16-rc-cvs"); memset(rs, 0, sizeof(routerstatus_t)); rs->is_authority = router_digest_is_trusted_dir(ri->cache_info.identity_digest); /* Already set by compute_performance_thresholds. */ rs->is_exit = ri->is_exit; rs->is_stable = ri->is_stable = router_is_active(ri, now) && !dirserv_thinks_router_is_unreliable(now, ri, 1, 0) && !unstable_version; rs->is_fast = ri->is_fast = router_is_active(ri, now) && !dirserv_thinks_router_is_unreliable(now, ri, 0, 1); rs->is_running = ri->is_running; /* computed above */ if (naming) { uint32_t name_status = dirserv_get_name_status( ri->cache_info.identity_digest, ri->nickname); rs->is_named = (naming && (name_status & FP_NAMED)) ? 1 : 0; rs->is_unnamed = (naming && (name_status & FP_UNNAMED)) ? 1 : 0; } rs->is_valid = ri->is_valid; if (rs->is_fast && (router_get_advertised_bandwidth(ri) >= BANDWIDTH_TO_GUARANTEE_GUARD || router_get_advertised_bandwidth(ri) >= MIN(guard_bandwidth_including_exits, guard_bandwidth_excluding_exits)) && is_router_version_good_for_possible_guard(ri->platform)) { long tk = rep_hist_get_weighted_time_known( ri->cache_info.identity_digest, now); double wfu = rep_hist_get_weighted_fractional_uptime( ri->cache_info.identity_digest, now); rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0; } else { rs->is_possible_guard = 0; } rs->is_bad_directory = listbaddirs && ri->is_bad_directory; rs->is_bad_exit = listbadexits && ri->is_bad_exit; ri->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, now); rs->is_hs_dir = vote_on_hsdirs && ri->is_hs_dir; rs->is_v2_dir = ri->dir_port != 0; if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME)) rs->is_named = rs->is_unnamed = 0; rs->published_on = ri->cache_info.published_on; memcpy(rs->identity_digest, ri->cache_info.identity_digest, DIGEST_LEN); memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest, DIGEST_LEN); rs->addr = ri->addr; strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname)); rs->or_port = ri->or_port; rs->dir_port = ri->dir_port; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Add option to give guard flag to relays without the CVE-2011-2768 fix This way, all of the DA operators can upgrade immediately, without nuking every client's set of entry guards as soon as a majority of them upgrade. Until enough guards have upgraded, a majority of dirauths should set this config option so that there are still enough guards in the network. After a few days pass, all dirauths should use the default.'</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: xmlParsePI(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int cur, l; const xmlChar *target; xmlParserInputState state; int count = 0; if ((RAW == '<') && (NXT(1) == '?')) { xmlParserInputPtr input = ctxt->input; state = ctxt->instate; ctxt->instate = XML_PARSER_PI; /* * this is a Processing Instruction. */ SKIP(2); SHRINK; /* * Parse the target name and check for special support like * namespace. */ target = xmlParsePITarget(ctxt); if (target != NULL) { if ((RAW == '?') && (NXT(1) == '>')) { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "PI declaration doesn't start and stop in the same entity\n"); } SKIP(2); /* * SAX: PI detected. */ if ((ctxt->sax) && (!ctxt->disableSAX) && (ctxt->sax->processingInstruction != NULL)) ctxt->sax->processingInstruction(ctxt->userData, target, NULL); ctxt->instate = state; return; } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } cur = CUR; if (!IS_BLANK(cur)) { xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED, "ParsePI: PI %s space expected\n", target); } SKIP_BLANKS; cur = CUR_CHAR(l); while (IS_CHAR(cur) && /* checked */ ((cur != '?') || (NXT(1) != '>'))) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); ctxt->instate = state; return; } buf = tmp; } count++; if (count > 50) { GROW; count = 0; } COPY_BUF(l,buf,len,cur); NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { SHRINK; GROW; cur = CUR_CHAR(l); } } buf[len] = 0; if (cur != '?') { xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, "ParsePI: PI %s never end ...\n", target); } else { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "PI declaration doesn't start and stop in the same entity\n"); } SKIP(2); #ifdef LIBXML_CATALOG_ENABLED if (((state == XML_PARSER_MISC) || (state == XML_PARSER_START)) && (xmlStrEqual(target, XML_CATALOG_PI))) { xmlCatalogAllow allow = xmlCatalogGetDefaults(); if ((allow == XML_CATA_ALLOW_DOCUMENT) || (allow == XML_CATA_ALLOW_ALL)) xmlParseCatalogPI(ctxt, buf); } #endif /* * SAX: PI detected. */ if ((ctxt->sax) && (!ctxt->disableSAX) && (ctxt->sax->processingInstruction != NULL)) ctxt->sax->processingInstruction(ctxt->userData, target, buf); } xmlFree(buf); } else { xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL); } ctxt->instate = state; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Make sure the parser returns when getting a Stop order patch backported from chromiun bug fixes, assuming author is Chris'</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 *suhosin_decrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key, char **where TSRMLS_DC) { char buffer[4096]; char buffer2[4096]; int o_name_len = name_len; char *buf = buffer, *buf2 = buffer2, *d, *d_url; int l; if (name_len > sizeof(buffer)-2) { buf = estrndup(name, name_len); } else { memcpy(buf, name, name_len); buf[name_len] = 0; } name_len = php_url_decode(buf, name_len); normalize_varname(buf); name_len = strlen(buf); if (SUHOSIN_G(cookie_plainlist)) { if (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) { decrypt_return_plain: if (buf != buffer) { efree(buf); } memcpy(*where, name, o_name_len); *where += o_name_len; **where = '='; *where +=1; memcpy(*where, value, value_len); *where += value_len; return *where; } } else if (SUHOSIN_G(cookie_cryptlist)) { if (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) { goto decrypt_return_plain; } } if (strlen(value) <= sizeof(buffer2)-2) { memcpy(buf2, value, value_len); buf2[value_len] = 0; } else { buf2 = estrndup(value, value_len); } value_len = php_url_decode(buf2, value_len); d = suhosin_decrypt_string(buf2, value_len, buf, name_len, key, &l, SUHOSIN_G(cookie_checkraddr) TSRMLS_CC); if (d == NULL) { goto skip_cookie; } d_url = php_url_encode(d, l, &l); efree(d); memcpy(*where, name, o_name_len); *where += o_name_len; **where = '=';*where += 1; memcpy(*where, d_url, l); *where += l; efree(d_url); skip_cookie: if (buf != buffer) { efree(buf); } if (buf2 != buffer2) { efree(buf2); } return *where; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed stack based buffer overflow in transparent cookie encryption (see separate advisory)'</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: xmlDictComputeBigKey(const xmlChar* data, int namelen) { uint32_t hash; int i; if (namelen <= 0 || data == NULL) return(0); hash = 0; for (i = 0;i < namelen; i++) { hash += data[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Add hash randomization to hash and dict structures Following http://www.ocert.org/advisories/ocert-2011-003.html it seems that having hash randomization might be a good idea when using XML with untrusted data * configure.in: lookup for rand, srand and time * dict.c: add randomization to dictionaries hash tables * hash.c: add randomization to normal hash tables'</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 preempt_conditional_cli(struct pt_regs *regs) { if (regs->flags & X86_EFLAGS_IF) local_irq_disable(); dec_preempt_count(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'x86: Do not disable preemption in int3 on 32bit Preemption must be disabled before enabling interrupts in do_trap on x86_64 because the stack in use for int3 and debug is a per CPU stack set by th IST. But 32bit does not have an IST and the stack still belongs to the current task and there is no problem in scheduling out the task. Keep preemption enabled on X86_32 when enabling interrupts for do_trap(). The name of the function is changed from preempt_conditional_sti/cli() to conditional_sti/cli_ist(), to annotate that this function is used when the stack is on the IST. Cc: stable-rt@vger.kernel.org Signed-off-by: Steven Rostedt <rostedt@goodmis.org> Signed-off-by: Thomas Gleixner <tglx@linutronix.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: peek_for_as4_capability (struct peer *peer, u_char length) { struct stream *s = BGP_INPUT (peer); size_t orig_getp = stream_get_getp (s); size_t end = orig_getp + length; as_t as4 = 0; /* The full capability parser will better flag the error.. */ if (STREAM_READABLE(s) < length) return 0; if (BGP_DEBUG (as4, AS4)) zlog_info ("%s [AS4] rcv OPEN w/ OPTION parameter len: %u," " peeking for as4", peer->host, length); /* the error cases we DONT handle, we ONLY try to read as4 out of * correctly formatted options. */ while (stream_get_getp(s) < end) { u_char opt_type; u_char opt_length; /* Check the length. */ if (stream_get_getp (s) + 2 > end) goto end; /* Fetch option type and length. */ opt_type = stream_getc (s); opt_length = stream_getc (s); /* Option length check. */ if (stream_get_getp (s) + opt_length > end) goto end; if (opt_type == BGP_OPEN_OPT_CAP) { unsigned long capd_start = stream_get_getp (s); unsigned long capd_end = capd_start + opt_length; assert (capd_end <= end); while (stream_get_getp (s) < capd_end) { struct capability_header hdr; if (stream_get_getp (s) + 2 > capd_end) goto end; hdr.code = stream_getc (s); hdr.length = stream_getc (s); if ((stream_get_getp(s) + hdr.length) > capd_end) goto end; if (hdr.code == CAPABILITY_CODE_AS4) { if (hdr.length != CAPABILITY_CODE_AS4_LEN) goto end; if (BGP_DEBUG (as4, AS4)) zlog_info ("[AS4] found AS4 capability, about to parse"); as4 = bgp_capability_as4 (peer, &hdr); goto end; } stream_forward_getp (s, hdr.length); } } } end: stream_set_getp (s, orig_getp); return as4; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'bgpd: Open option parse errors don't NOTIFY, resulting in abort & DoS * bgp_packet.c: (bgp_open_receive) Errors from bgp_open_option_parse are detected, and the code will stop processing the OPEN and return. However it does so without calling bgp_notify_send to send a NOTIFY - which means the peer FSM doesn't get stopped, and bgp_read will be called again later. Because it returns, it doesn't go through the code near the end of the function that removes the current message from the peer input streaam. Thus the next call to bgp_read will try to parse a half-parsed stream as if it were a new BGP message, leading to an assert later in the code when it tries to read stuff that isn't there. Add the required call to bgp_notify_send before returning. * bgp_open.c: (bgp_capability_as4) Be a bit stricter, check the length field corresponds to the only value it can be, which is the amount we're going to read off the stream. And make sure the capability flag gets set, so callers can know this capability was read, regardless. (peek_for_as4_capability) Let bgp_capability_as4 do the length check.'</s>
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card