text
stringlengths
478
227k
<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: SPL_METHOD(SplObjectStorage, unserialize) { spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis()); char *buf; size_t buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval entry, inf; zval *pcount, *pmembers; spl_SplObjectStorageElement *element; zend_long count; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; pcount = var_tmp_var(&var_hash); if (!php_var_unserialize(pcount, &p, s + buf_len, &var_hash) || Z_TYPE_P(pcount) != IS_LONG) { goto outexcept; } --p; /* for ';' */ count = Z_LVAL_P(pcount); while (count-- > 0) { spl_SplObjectStorageElement *pelement; zend_string *hash; if (*p != ';') { goto outexcept; } ++p; if(*p != 'O' && *p != 'C' && *p != 'r') { goto outexcept; } /* store reference to allow cross-references between different elements */ if (!php_var_unserialize(&entry, &p, s + buf_len, &var_hash)) { goto outexcept; } if (Z_TYPE(entry) != IS_OBJECT) { zval_ptr_dtor(&entry); goto outexcept; } if (*p == ',') { /* new version has inf */ ++p; if (!php_var_unserialize(&inf, &p, s + buf_len, &var_hash)) { zval_ptr_dtor(&entry); goto outexcept; } } else { ZVAL_UNDEF(&inf); } hash = spl_object_storage_get_hash(intern, getThis(), &entry); if (!hash) { zval_ptr_dtor(&entry); zval_ptr_dtor(&inf); goto outexcept; } pelement = spl_object_storage_get(intern, hash); spl_object_storage_free_hash(intern, hash); if (pelement) { if (!Z_ISUNDEF(pelement->inf)) { var_push_dtor(&var_hash, &pelement->inf); } if (!Z_ISUNDEF(pelement->obj)) { var_push_dtor(&var_hash, &pelement->obj); } } element = spl_object_storage_attach(intern, getThis(), &entry, Z_ISUNDEF(inf)?NULL:&inf); var_replace(&var_hash, &entry, &element->obj); var_replace(&var_hash, &inf, &element->inf); zval_ptr_dtor(&entry); ZVAL_UNDEF(&entry); zval_ptr_dtor(&inf); ZVAL_UNDEF(&inf); } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; pmembers = var_tmp_var(&var_hash); if (!php_var_unserialize(pmembers, &p, s + buf_len, &var_hash) || Z_TYPE_P(pmembers) != IS_ARRAY) { goto outexcept; } /* copy members */ object_properties_load(&intern->std, Z_ARRVAL_P(pmembers)); PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return; outexcept: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Error at offset %pd of %d bytes", (zend_long)((char*)p - buf), buf_len); return; } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix bug #73257 and bug #73258 - SplObjectStorage unserialize allows use of non-object as key'</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: BGD_DECLARE(gdImagePtr) gdImageCreate (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sx, sy)) { return NULL; } if (overflow2(sizeof (unsigned char *), sy)) { return NULL; } if (overflow2(sizeof (unsigned char), sx)) { return NULL; } im = (gdImage *) gdCalloc(1, sizeof(gdImage)); if (!im) { return NULL; } /* Row-major ever since gd 1.3 */ im->pixels = (unsigned char **) gdMalloc (sizeof (unsigned char *) * sy); if (!im->pixels) { gdFree(im); return NULL; } im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; (i < sy); i++) { /* Row-major ever since gd 1.3 */ im->pixels[i] = (unsigned char *) gdCalloc (sx, sizeof (unsigned char)); if (!im->pixels[i]) { for (--i ; i >= 0; i--) { gdFree(im->pixels[i]); } gdFree(im->pixels); gdFree(im); return NULL; } } im->sx = sx; im->sy = sy; im->colorsTotal = 0; im->transparent = (-1); im->interlace = 0; im->thick = 1; im->AA = 0; for (i = 0; (i < gdMaxColors); i++) { im->open[i] = 1; }; im->trueColor = 0; im->tpixels = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->res_x = GD_RESOLUTION; im->res_y = GD_RESOLUTION; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix #340: System frozen gdImageCreate() doesn't check for oversized images and as such is prone to DoS vulnerabilities. We fix that by applying the same overflow check that is already in place for gdImageCreateTrueColor(). CVE-2016-9317'</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 size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(uchar *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single"); #endif return (size_t)*(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double"); #endif return (size_t)*(double *)value; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fix bug #73737 FPE when parsing a tag format'</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 ip4_datagram_release_cb(struct sock *sk) { const struct inet_sock *inet = inet_sk(sk); const struct ip_options_rcu *inet_opt; __be32 daddr = inet->inet_daddr; struct flowi4 fl4; struct rtable *rt; if (! __sk_dst_get(sk) || __sk_dst_check(sk, 0)) return; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; rt = ip_route_output_ports(sock_net(sk), &fl4, sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (!IS_ERR(rt)) __sk_dst_set(sk, &rt->dst); rcu_read_unlock(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362', 'CWE-401'], 'message': 'ipv4: fix a race in ip4_datagram_release_cb() Alexey gave a AddressSanitizer[1] report that finally gave a good hint at where was the origin of various problems already reported by Dormando in the past [2] Problem comes from the fact that UDP can have a lockless TX path, and concurrent threads can manipulate sk_dst_cache, while another thread, is holding socket lock and calls __sk_dst_set() in ip4_datagram_release_cb() (this was added in linux-3.8) It seems that all we need to do is to use sk_dst_check() and sk_dst_set() so that all the writers hold same spinlock (sk->sk_dst_lock) to prevent corruptions. TCP stack do not need this protection, as all sk_dst_cache writers hold the socket lock. [1] https://code.google.com/p/address-sanitizer/wiki/AddressSanitizerForKernel AddressSanitizer: heap-use-after-free in ipv4_dst_check Read of size 2 by thread T15453: [<ffffffff817daa3a>] ipv4_dst_check+0x1a/0x90 ./net/ipv4/route.c:1116 [<ffffffff8175b789>] __sk_dst_check+0x89/0xe0 ./net/core/sock.c:531 [<ffffffff81830a36>] ip4_datagram_release_cb+0x46/0x390 ??:0 [<ffffffff8175eaea>] release_sock+0x17a/0x230 ./net/core/sock.c:2413 [<ffffffff81830882>] ip4_datagram_connect+0x462/0x5d0 ??:0 [<ffffffff81846d06>] inet_dgram_connect+0x76/0xd0 ./net/ipv4/af_inet.c:534 [<ffffffff817580ac>] SYSC_connect+0x15c/0x1c0 ./net/socket.c:1701 [<ffffffff817596ce>] SyS_connect+0xe/0x10 ./net/socket.c:1682 [<ffffffff818b0a29>] system_call_fastpath+0x16/0x1b ./arch/x86/kernel/entry_64.S:629 Freed by thread T15455: [<ffffffff8178d9b8>] dst_destroy+0xa8/0x160 ./net/core/dst.c:251 [<ffffffff8178de25>] dst_release+0x45/0x80 ./net/core/dst.c:280 [<ffffffff818304c1>] ip4_datagram_connect+0xa1/0x5d0 ??:0 [<ffffffff81846d06>] inet_dgram_connect+0x76/0xd0 ./net/ipv4/af_inet.c:534 [<ffffffff817580ac>] SYSC_connect+0x15c/0x1c0 ./net/socket.c:1701 [<ffffffff817596ce>] SyS_connect+0xe/0x10 ./net/socket.c:1682 [<ffffffff818b0a29>] system_call_fastpath+0x16/0x1b ./arch/x86/kernel/entry_64.S:629 Allocated by thread T15453: [<ffffffff8178d291>] dst_alloc+0x81/0x2b0 ./net/core/dst.c:171 [<ffffffff817db3b7>] rt_dst_alloc+0x47/0x50 ./net/ipv4/route.c:1406 [< inlined >] __ip_route_output_key+0x3e8/0xf70 __mkroute_output ./net/ipv4/route.c:1939 [<ffffffff817dde08>] __ip_route_output_key+0x3e8/0xf70 ./net/ipv4/route.c:2161 [<ffffffff817deb34>] ip_route_output_flow+0x14/0x30 ./net/ipv4/route.c:2249 [<ffffffff81830737>] ip4_datagram_connect+0x317/0x5d0 ??:0 [<ffffffff81846d06>] inet_dgram_connect+0x76/0xd0 ./net/ipv4/af_inet.c:534 [<ffffffff817580ac>] SYSC_connect+0x15c/0x1c0 ./net/socket.c:1701 [<ffffffff817596ce>] SyS_connect+0xe/0x10 ./net/socket.c:1682 [<ffffffff818b0a29>] system_call_fastpath+0x16/0x1b ./arch/x86/kernel/entry_64.S:629 [2] <4>[196727.311203] general protection fault: 0000 [#1] SMP <4>[196727.311224] Modules linked in: xt_TEE xt_dscp xt_DSCP macvlan bridge coretemp crc32_pclmul ghash_clmulni_intel gpio_ich microcode ipmi_watchdog ipmi_devintf sb_edac edac_core lpc_ich mfd_core tpm_tis tpm tpm_bios ipmi_si ipmi_msghandler isci igb libsas i2c_algo_bit ixgbe ptp pps_core mdio <4>[196727.311333] CPU: 17 PID: 0 Comm: swapper/17 Not tainted 3.10.26 #1 <4>[196727.311344] Hardware name: Supermicro X9DRi-LN4+/X9DR3-LN4+/X9DRi-LN4+/X9DR3-LN4+, BIOS 3.0 07/05/2013 <4>[196727.311364] task: ffff885e6f069700 ti: ffff885e6f072000 task.ti: ffff885e6f072000 <4>[196727.311377] RIP: 0010:[<ffffffff815f8c7f>] [<ffffffff815f8c7f>] ipv4_dst_destroy+0x4f/0x80 <4>[196727.311399] RSP: 0018:ffff885effd23a70 EFLAGS: 00010282 <4>[196727.311409] RAX: dead000000200200 RBX: ffff8854c398ecc0 RCX: 0000000000000040 <4>[196727.311423] RDX: dead000000100100 RSI: dead000000100100 RDI: dead000000200200 <4>[196727.311437] RBP: ffff885effd23a80 R08: ffffffff815fd9e0 R09: ffff885d5a590800 <4>[196727.311451] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000000 <4>[196727.311464] R13: ffffffff81c8c280 R14: 0000000000000000 R15: ffff880e85ee16ce <4>[196727.311510] FS: 0000000000000000(0000) GS:ffff885effd20000(0000) knlGS:0000000000000000 <4>[196727.311554] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 <4>[196727.311581] CR2: 00007a46751eb000 CR3: 0000005e65688000 CR4: 00000000000407e0 <4>[196727.311625] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 <4>[196727.311669] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 <4>[196727.311713] Stack: <4>[196727.311733] ffff8854c398ecc0 ffff8854c398ecc0 ffff885effd23ab0 ffffffff815b7f42 <4>[196727.311784] ffff88be6595bc00 ffff8854c398ecc0 0000000000000000 ffff8854c398ecc0 <4>[196727.311834] ffff885effd23ad0 ffffffff815b86c6 ffff885d5a590800 ffff8816827821c0 <4>[196727.311885] Call Trace: <4>[196727.311907] <IRQ> <4>[196727.311912] [<ffffffff815b7f42>] dst_destroy+0x32/0xe0 <4>[196727.311959] [<ffffffff815b86c6>] dst_release+0x56/0x80 <4>[196727.311986] [<ffffffff81620bd5>] tcp_v4_do_rcv+0x2a5/0x4a0 <4>[196727.312013] [<ffffffff81622b5a>] tcp_v4_rcv+0x7da/0x820 <4>[196727.312041] [<ffffffff815fd9e0>] ? ip_rcv_finish+0x360/0x360 <4>[196727.312070] [<ffffffff815de02d>] ? nf_hook_slow+0x7d/0x150 <4>[196727.312097] [<ffffffff815fd9e0>] ? ip_rcv_finish+0x360/0x360 <4>[196727.312125] [<ffffffff815fda92>] ip_local_deliver_finish+0xb2/0x230 <4>[196727.312154] [<ffffffff815fdd9a>] ip_local_deliver+0x4a/0x90 <4>[196727.312183] [<ffffffff815fd799>] ip_rcv_finish+0x119/0x360 <4>[196727.312212] [<ffffffff815fe00b>] ip_rcv+0x22b/0x340 <4>[196727.312242] [<ffffffffa0339680>] ? macvlan_broadcast+0x160/0x160 [macvlan] <4>[196727.312275] [<ffffffff815b0c62>] __netif_receive_skb_core+0x512/0x640 <4>[196727.312308] [<ffffffff811427fb>] ? kmem_cache_alloc+0x13b/0x150 <4>[196727.312338] [<ffffffff815b0db1>] __netif_receive_skb+0x21/0x70 <4>[196727.312368] [<ffffffff815b0fa1>] netif_receive_skb+0x31/0xa0 <4>[196727.312397] [<ffffffff815b1ae8>] napi_gro_receive+0xe8/0x140 <4>[196727.312433] [<ffffffffa00274f1>] ixgbe_poll+0x551/0x11f0 [ixgbe] <4>[196727.312463] [<ffffffff815fe00b>] ? ip_rcv+0x22b/0x340 <4>[196727.312491] [<ffffffff815b1691>] net_rx_action+0x111/0x210 <4>[196727.312521] [<ffffffff815b0db1>] ? __netif_receive_skb+0x21/0x70 <4>[196727.312552] [<ffffffff810519d0>] __do_softirq+0xd0/0x270 <4>[196727.312583] [<ffffffff816cef3c>] call_softirq+0x1c/0x30 <4>[196727.312613] [<ffffffff81004205>] do_softirq+0x55/0x90 <4>[196727.312640] [<ffffffff81051c85>] irq_exit+0x55/0x60 <4>[196727.312668] [<ffffffff816cf5c3>] do_IRQ+0x63/0xe0 <4>[196727.312696] [<ffffffff816c5aaa>] common_interrupt+0x6a/0x6a <4>[196727.312722] <EOI> <1>[196727.313071] RIP [<ffffffff815f8c7f>] ipv4_dst_destroy+0x4f/0x80 <4>[196727.313100] RSP <ffff885effd23a70> <4>[196727.313377] ---[ end trace 64b3f14fae0f2e29 ]--- <0>[196727.380908] Kernel panic - not syncing: Fatal exception in interrupt Reported-by: Alexey Preobrazhensky <preobr@google.com> Reported-by: dormando <dormando@rydia.ne> Signed-off-by: Eric Dumazet <edumazet@google.com> Fixes: 8141ed9fcedb2 ("ipv4: Add a socket release callback for datagram sockets") Cc: Steffen Klassert <steffen.klassert@secunet.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 inline void timer_stats_hrtimer_clear_start_info(struct hrtimer *timer) { #ifdef CONFIG_TIMER_STATS timer->start_site = NULL; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS Currently CONFIG_TIMER_STATS exposes process information across namespaces: kernel/time/timer_list.c print_timer(): SEQ_printf(m, ", %s/%d", tmp, timer->start_pid); /proc/timer_list: #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570 Given that the tracer can give the same information, this patch entirely removes CONFIG_TIMER_STATS. Suggested-by: Thomas Gleixner <tglx@linutronix.de> Signed-off-by: Kees Cook <keescook@chromium.org> Acked-by: John Stultz <john.stultz@linaro.org> Cc: Nicolas Pitre <nicolas.pitre@linaro.org> Cc: linux-doc@vger.kernel.org Cc: Lai Jiangshan <jiangshanlai@gmail.com> Cc: Shuah Khan <shuah@kernel.org> Cc: Xing Gao <xgao01@email.wm.edu> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Jessica Frazelle <me@jessfraz.com> Cc: kernel-hardening@lists.openwall.com Cc: Nicolas Iooss <nicolas.iooss_linux@m4x.org> Cc: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com> Cc: Petr Mladek <pmladek@suse.com> Cc: Richard Cochran <richardcochran@gmail.com> Cc: Tejun Heo <tj@kernel.org> Cc: Michal Marek <mmarek@suse.com> Cc: Josh Poimboeuf <jpoimboe@redhat.com> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Olof Johansson <olof@lixom.net> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: linux-api@vger.kernel.org Cc: Arjan van de Ven <arjan@linux.intel.com> Link: http://lkml.kernel.org/r/20170208192659.GA32582@beast 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: static void expire_timers(struct timer_base *base, struct hlist_head *head) { while (!hlist_empty(head)) { struct timer_list *timer; void (*fn)(unsigned long); unsigned long data; timer = hlist_entry(head->first, struct timer_list, entry); timer_stats_account_timer(timer); base->running_timer = timer; detach_timer(timer, true); fn = timer->function; data = timer->data; if (timer->flags & TIMER_IRQSAFE) { spin_unlock(&base->lock); call_timer_fn(timer, fn, data); spin_lock(&base->lock); } else { spin_unlock_irq(&base->lock); call_timer_fn(timer, fn, data); spin_lock_irq(&base->lock); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS Currently CONFIG_TIMER_STATS exposes process information across namespaces: kernel/time/timer_list.c print_timer(): SEQ_printf(m, ", %s/%d", tmp, timer->start_pid); /proc/timer_list: #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570 Given that the tracer can give the same information, this patch entirely removes CONFIG_TIMER_STATS. Suggested-by: Thomas Gleixner <tglx@linutronix.de> Signed-off-by: Kees Cook <keescook@chromium.org> Acked-by: John Stultz <john.stultz@linaro.org> Cc: Nicolas Pitre <nicolas.pitre@linaro.org> Cc: linux-doc@vger.kernel.org Cc: Lai Jiangshan <jiangshanlai@gmail.com> Cc: Shuah Khan <shuah@kernel.org> Cc: Xing Gao <xgao01@email.wm.edu> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Jessica Frazelle <me@jessfraz.com> Cc: kernel-hardening@lists.openwall.com Cc: Nicolas Iooss <nicolas.iooss_linux@m4x.org> Cc: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com> Cc: Petr Mladek <pmladek@suse.com> Cc: Richard Cochran <richardcochran@gmail.com> Cc: Tejun Heo <tj@kernel.org> Cc: Michal Marek <mmarek@suse.com> Cc: Josh Poimboeuf <jpoimboe@redhat.com> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Olof Johansson <olof@lixom.net> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: linux-api@vger.kernel.org Cc: Arjan van de Ven <arjan@linux.intel.com> Link: http://lkml.kernel.org/r/20170208192659.GA32582@beast 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: static struct entry *tstat_lookup(struct entry *entry, char *comm) { struct entry **head, *curr, *prev; head = tstat_hashentry(entry); curr = *head; /* * The fastpath is when the entry is already hashed, * we do this with the lookup lock held, but with the * table lock not held: */ while (curr) { if (match_entries(curr, entry)) return curr; curr = curr->next; } /* * Slowpath: allocate, set up and link a new hash entry: */ prev = NULL; curr = *head; raw_spin_lock(&table_lock); /* * Make sure we have not raced with another CPU: */ while (curr) { if (match_entries(curr, entry)) goto out_unlock; prev = curr; curr = curr->next; } curr = alloc_entry(); if (curr) { *curr = *entry; curr->count = 0; curr->next = NULL; memcpy(curr->comm, comm, TASK_COMM_LEN); smp_mb(); /* Ensure that curr is initialized before insert */ if (prev) prev->next = curr; else *head = curr; } out_unlock: raw_spin_unlock(&table_lock); return curr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS Currently CONFIG_TIMER_STATS exposes process information across namespaces: kernel/time/timer_list.c print_timer(): SEQ_printf(m, ", %s/%d", tmp, timer->start_pid); /proc/timer_list: #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570 Given that the tracer can give the same information, this patch entirely removes CONFIG_TIMER_STATS. Suggested-by: Thomas Gleixner <tglx@linutronix.de> Signed-off-by: Kees Cook <keescook@chromium.org> Acked-by: John Stultz <john.stultz@linaro.org> Cc: Nicolas Pitre <nicolas.pitre@linaro.org> Cc: linux-doc@vger.kernel.org Cc: Lai Jiangshan <jiangshanlai@gmail.com> Cc: Shuah Khan <shuah@kernel.org> Cc: Xing Gao <xgao01@email.wm.edu> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Jessica Frazelle <me@jessfraz.com> Cc: kernel-hardening@lists.openwall.com Cc: Nicolas Iooss <nicolas.iooss_linux@m4x.org> Cc: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com> Cc: Petr Mladek <pmladek@suse.com> Cc: Richard Cochran <richardcochran@gmail.com> Cc: Tejun Heo <tj@kernel.org> Cc: Michal Marek <mmarek@suse.com> Cc: Josh Poimboeuf <jpoimboe@redhat.com> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Olof Johansson <olof@lixom.net> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: linux-api@vger.kernel.org Cc: Arjan van de Ven <arjan@linux.intel.com> Link: http://lkml.kernel.org/r/20170208192659.GA32582@beast 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: int del_timer(struct timer_list *timer) { struct timer_base *base; unsigned long flags; int ret = 0; debug_assert_init(timer); timer_stats_timer_clear_start_info(timer); if (timer_pending(timer)) { base = lock_timer_base(timer, &flags); ret = detach_if_pending(timer, base, true); spin_unlock_irqrestore(&base->lock, flags); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS Currently CONFIG_TIMER_STATS exposes process information across namespaces: kernel/time/timer_list.c print_timer(): SEQ_printf(m, ", %s/%d", tmp, timer->start_pid); /proc/timer_list: #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570 Given that the tracer can give the same information, this patch entirely removes CONFIG_TIMER_STATS. Suggested-by: Thomas Gleixner <tglx@linutronix.de> Signed-off-by: Kees Cook <keescook@chromium.org> Acked-by: John Stultz <john.stultz@linaro.org> Cc: Nicolas Pitre <nicolas.pitre@linaro.org> Cc: linux-doc@vger.kernel.org Cc: Lai Jiangshan <jiangshanlai@gmail.com> Cc: Shuah Khan <shuah@kernel.org> Cc: Xing Gao <xgao01@email.wm.edu> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Jessica Frazelle <me@jessfraz.com> Cc: kernel-hardening@lists.openwall.com Cc: Nicolas Iooss <nicolas.iooss_linux@m4x.org> Cc: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com> Cc: Petr Mladek <pmladek@suse.com> Cc: Richard Cochran <richardcochran@gmail.com> Cc: Tejun Heo <tj@kernel.org> Cc: Michal Marek <mmarek@suse.com> Cc: Josh Poimboeuf <jpoimboe@redhat.com> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Olof Johansson <olof@lixom.net> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: linux-api@vger.kernel.org Cc: Arjan van de Ven <arjan@linux.intel.com> Link: http://lkml.kernel.org/r/20170208192659.GA32582@beast 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: static int parse_line(char *str) { uint8_t array[256]; uint16_t value, pskey, length = 0; char *off, *end; pskey = strtol(str + 1, NULL, 16); off = strstr(str, "="); if (!off) return -EIO; off++; while (1) { value = strtol(off, &end, 16); if (value == 0 && off == end) break; array[length++] = value & 0xff; array[length++] = value >> 8; if (*end == '\0') break; off = end + 1; } return psr_put(pskey, array, length); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'tools/csr: Fix possible buffer overflow Make sure we don't write past the end of the array.'</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 vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v) { uint8_t r, g, b; VncDisplay *vd = vs->vd; r = ((((v & vd->server->pf.rmask) >> vd->server->pf.rshift) << vs->clientds.pf.rbits) >> vd->server->pf.rbits); g = ((((v & vd->server->pf.gmask) >> vd->server->pf.gshift) << vs->clientds.pf.gbits) >> vd->server->pf.gbits); b = ((((v & vd->server->pf.bmask) >> vd->server->pf.bshift) << vs->clientds.pf.bbits) >> vd->server->pf.bbits); v = (r << vs->clientds.pf.rshift) | (g << vs->clientds.pf.gshift) | (b << vs->clientds.pf.bshift); switch(vs->clientds.pf.bytes_per_pixel) { case 1: buf[0] = v; break; case 2: if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) { buf[0] = v >> 8; buf[1] = v; } else { buf[1] = v >> 8; buf[0] = v; } break; default: case 4: if (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) { buf[0] = v >> 24; buf[1] = v >> 16; buf[2] = v >> 8; buf[3] = v; } else { buf[3] = v >> 24; buf[2] = v >> 16; buf[1] = v >> 8; buf[0] = v; } break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc. The vnc code uses *three* DisplaySurfaces: First is the surface of the actual QemuConsole, usually the guest screen, but could also be a text console (monitor/serial reachable via Ctrl-Alt-<nr> keys). This is left as-is. Second is the current server's view of the screen content. The vnc code uses this to figure which parts of the guest screen did _really_ change to reduce the amount of updates sent to the vnc clients. It is also used as data source when sending out the updates to the clients. This surface gets replaced by a pixman image. The format changes too, instead of using the guest screen format we'll use fixed 32bit rgb framebuffer and convert the pixels on the fly when comparing and updating the server framebuffer. Third surface carries the format expected by the vnc client. That isn't used to store image data. This surface is switched to PixelFormat and a boolean for bigendian byte order. Signed-off-by: Gerd Hoffmann <kraxel@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: tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h) { uint32_t *buf32; uint32_t pix32; int shift[3]; int *prev; int here[3], upper[3], left[3], upperleft[3]; int prediction; int x, y, c; buf32 = (uint32_t *)buf; memset(vs->tight.gradient.buffer, 0, w * 3 * sizeof(int)); if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) == (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG)) { shift[0] = vs->clientds.pf.rshift; shift[1] = vs->clientds.pf.gshift; shift[2] = vs->clientds.pf.bshift; } else { shift[0] = 24 - vs->clientds.pf.rshift; shift[1] = 24 - vs->clientds.pf.gshift; shift[2] = 24 - vs->clientds.pf.bshift; } for (y = 0; y < h; y++) { for (c = 0; c < 3; c++) { upper[c] = 0; here[c] = 0; } prev = (int *)vs->tight.gradient.buffer; for (x = 0; x < w; x++) { pix32 = *buf32++; for (c = 0; c < 3; c++) { upperleft[c] = upper[c]; left[c] = here[c]; upper[c] = *prev; here[c] = (int)(pix32 >> shift[c] & 0xFF); *prev++ = here[c]; prediction = left[c] + upper[c] - upperleft[c]; if (prediction < 0) { prediction = 0; } else if (prediction > 0xFF) { prediction = 0xFF; } *buf++ = (char)(here[c] - prediction); } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc. The vnc code uses *three* DisplaySurfaces: First is the surface of the actual QemuConsole, usually the guest screen, but could also be a text console (monitor/serial reachable via Ctrl-Alt-<nr> keys). This is left as-is. Second is the current server's view of the screen content. The vnc code uses this to figure which parts of the guest screen did _really_ change to reduce the amount of updates sent to the vnc clients. It is also used as data source when sending out the updates to the clients. This surface gets replaced by a pixman image. The format changes too, instead of using the guest screen format we'll use fixed 32bit rgb framebuffer and convert the pixels on the fly when comparing and updating the server framebuffer. Third surface carries the format expected by the vnc client. That isn't used to store image data. This surface is switched to PixelFormat and a boolean for bigendian byte order. Signed-off-by: Gerd Hoffmann <kraxel@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 send_palette_rect(VncState *vs, int x, int y, int w, int h, VncPalette *palette) { int stream = 2; int level = tight_conf[vs->tight.compression].idx_zlib_level; int colors; ssize_t bytes; #ifdef CONFIG_VNC_PNG if (tight_can_send_png_rect(vs, w, h)) { return send_png_rect(vs, x, y, w, h, palette); } #endif colors = palette_size(palette); vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4); vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE); vnc_write_u8(vs, colors - 1); switch(vs->clientds.pf.bytes_per_pixel) { case 4: { size_t old_offset, offset; uint32_t header[palette_size(palette)]; struct palette_cb_priv priv = { vs, (uint8_t *)header }; old_offset = vs->output.offset; palette_iter(palette, write_palette, &priv); vnc_write(vs, header, sizeof(header)); if (vs->tight.pixel24) { tight_pack24(vs, vs->output.buffer + old_offset, colors, &offset); vs->output.offset = old_offset + offset; } tight_encode_indexed_rect32(vs->tight.tight.buffer, w * h, palette); break; } case 2: { uint16_t header[palette_size(palette)]; struct palette_cb_priv priv = { vs, (uint8_t *)header }; palette_iter(palette, write_palette, &priv); vnc_write(vs, header, sizeof(header)); tight_encode_indexed_rect16(vs->tight.tight.buffer, w * h, palette); break; } default: return -1; /* No palette for 8bits colors */ break; } bytes = w * h; vs->tight.tight.offset = bytes; bytes = tight_compress_data(vs, stream, bytes, level, Z_DEFAULT_STRATEGY); return (bytes >= 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc. The vnc code uses *three* DisplaySurfaces: First is the surface of the actual QemuConsole, usually the guest screen, but could also be a text console (monitor/serial reachable via Ctrl-Alt-<nr> keys). This is left as-is. Second is the current server's view of the screen content. The vnc code uses this to figure which parts of the guest screen did _really_ change to reduce the amount of updates sent to the vnc clients. It is also used as data source when sending out the updates to the clients. This surface gets replaced by a pixman image. The format changes too, instead of using the guest screen format we'll use fixed 32bit rgb framebuffer and convert the pixels on the fly when comparing and updating the server framebuffer. Third surface carries the format expected by the vnc client. That isn't used to store image data. This surface is switched to PixelFormat and a boolean for bigendian byte order. Signed-off-by: Gerd Hoffmann <kraxel@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: int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h) { int i; uint8_t *row; VncDisplay *vd = vs->vd; row = vd->server->data + y * ds_get_linesize(vs->ds) + x * ds_get_bytes_per_pixel(vs->ds); for (i = 0; i < h; i++) { vs->write_pixels(vs, &vd->server->pf, row, w * ds_get_bytes_per_pixel(vs->ds)); row += ds_get_linesize(vs->ds); } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'pixman/vnc: use pixman images in vnc. The vnc code uses *three* DisplaySurfaces: First is the surface of the actual QemuConsole, usually the guest screen, but could also be a text console (monitor/serial reachable via Ctrl-Alt-<nr> keys). This is left as-is. Second is the current server's view of the screen content. The vnc code uses this to figure which parts of the guest screen did _really_ change to reduce the amount of updates sent to the vnc clients. It is also used as data source when sending out the updates to the clients. This surface gets replaced by a pixman image. The format changes too, instead of using the guest screen format we'll use fixed 32bit rgb framebuffer and convert the pixels on the fly when comparing and updating the server framebuffer. Third surface carries the format expected by the vnc client. That isn't used to store image data. This surface is switched to PixelFormat and a boolean for bigendian byte order. Signed-off-by: Gerd Hoffmann <kraxel@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: unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name) { int i; u_entry_T *uep; char_u **array; char_u *line; int line_len; uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T)); if (uep == NULL) return NULL; vim_memset(uep, 0, sizeof(u_entry_T)); #ifdef U_DEBUG uep->ue_magic = UE_MAGIC; #endif uep->ue_top = undo_read_4c(bi); uep->ue_bot = undo_read_4c(bi); uep->ue_lcount = undo_read_4c(bi); uep->ue_size = undo_read_4c(bi); if (uep->ue_size > 0) { array = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size); if (array == NULL) { *error = TRUE; return uep; } vim_memset(array, 0, sizeof(char_u *) * uep->ue_size); } else array = NULL; uep->ue_array = array; for (i = 0; i < uep->ue_size; ++i) { line_len = undo_read_4c(bi); if (line_len >= 0) line = read_string_decrypt(bi, line_len); else { line = NULL; corruption_error("line length", file_name); } if (line == NULL) { *error = TRUE; return uep; } array[i] = line; } return uep; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'patch 8.0.0378: possible overflow when reading corrupted undo file Problem: Another possible overflow when reading corrupted undo file. Solution: Check if allocated size is not too big. (King)'</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 key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = type->match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { construct_get_dest_keyring(&dest_keyring); ret = key_link(dest_keyring, key); key_put(dest_keyring); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <dhowells@redhat.com> Acked-by: Vivek Goyal <vgoyal@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 fanout_add(struct sock *sk, u16 id, u16 type_flags) { struct packet_sock *po = pkt_sk(sk); struct packet_fanout *f, *match; u8 type = type_flags & 0xff; u8 flags = type_flags >> 8; int err; switch (type) { case PACKET_FANOUT_ROLLOVER: if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER) return -EINVAL; case PACKET_FANOUT_HASH: case PACKET_FANOUT_LB: case PACKET_FANOUT_CPU: case PACKET_FANOUT_RND: case PACKET_FANOUT_QM: case PACKET_FANOUT_CBPF: case PACKET_FANOUT_EBPF: break; default: return -EINVAL; } if (!po->running) return -EINVAL; if (po->fanout) return -EALREADY; if (type == PACKET_FANOUT_ROLLOVER || (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) { po->rollover = kzalloc(sizeof(*po->rollover), GFP_KERNEL); if (!po->rollover) return -ENOMEM; atomic_long_set(&po->rollover->num, 0); atomic_long_set(&po->rollover->num_huge, 0); atomic_long_set(&po->rollover->num_failed, 0); } mutex_lock(&fanout_mutex); match = NULL; list_for_each_entry(f, &fanout_list, list) { if (f->id == id && read_pnet(&f->net) == sock_net(sk)) { match = f; break; } } err = -EINVAL; if (match && match->flags != flags) goto out; if (!match) { err = -ENOMEM; match = kzalloc(sizeof(*match), GFP_KERNEL); if (!match) goto out; write_pnet(&match->net, sock_net(sk)); match->id = id; match->type = type; match->flags = flags; INIT_LIST_HEAD(&match->list); spin_lock_init(&match->lock); atomic_set(&match->sk_ref, 0); fanout_init_data(match); match->prot_hook.type = po->prot_hook.type; match->prot_hook.dev = po->prot_hook.dev; match->prot_hook.func = packet_rcv_fanout; match->prot_hook.af_packet_priv = match; match->prot_hook.id_match = match_fanout_group; dev_add_pack(&match->prot_hook); list_add(&match->list, &fanout_list); } err = -EINVAL; if (match->type == type && match->prot_hook.type == po->prot_hook.type && match->prot_hook.dev == po->prot_hook.dev) { err = -ENOSPC; if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) { __dev_remove_pack(&po->prot_hook); po->fanout = match; atomic_inc(&match->sk_ref); __fanout_link(sk, po); err = 0; } } out: mutex_unlock(&fanout_mutex); if (err) { kfree(po->rollover); po->rollover = NULL; } return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'packet: fix races in fanout_add() Multiple threads can call fanout_add() at the same time. We need to grab fanout_mutex earlier to avoid races that could lead to one thread freeing po->rollover that was set by another thread. Do the same in fanout_release(), for peace of mind, and to help us finding lockdep issues earlier. Fixes: dc99f600698d ("packet: Add fanout support.") Fixes: 0648ab70afe6 ("packet: rollover prepare: per-socket state") Signed-off-by: Eric Dumazet <edumazet@google.com> Cc: Willem de Bruijn <willemb@google.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: QStandardItem* PeerListWidget::addPeer(const QString& ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer) { int row = m_listModel->rowCount(); // Adding Peer to peer list m_listModel->insertRow(row); m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip); m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip, Qt::ToolTipRole); m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port); m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP_HIDDEN), ip); if (m_resolveCountries) { const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country()); if (!ico.isNull()) { m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole); const QString countryName = Net::GeoIPManager::CountryName(peer.country()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole); } else { m_missingFlags.insert(ip); } } m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole); m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance()); QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex())); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(";"))); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String("\n")), Qt::ToolTipRole); return m_listModel->item(row, PeerListDelegate::IP); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-79'], 'message': 'Add Utils::String::toHtmlEscaped'</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: am_cache_entry_t *am_new_request_session(request_rec *r) { const char *session_id; /* Generate session id. */ session_id = am_generate_id(r); if(session_id == NULL) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Error creating session id."); return NULL; } /* Set session id. */ am_cookie_set(r, session_id); return am_cache_new(r->server, session_id); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-79'], 'message': 'Fix Cross-Site Session Transfer vulnerability mod_auth_mellon did not verify that the site the session was created for was the same site as the site the user accessed. This allows an attacker with access to one web site on a server to use the same session to get access to a different site running on the same server. This patch fixes this vulnerability by storing the cookie parameters used when creating the session in the session, and verifying those parameters when the session is loaded. Thanks to François Kooman for reporting this vulnerability. This vulnerability has been assigned CVE-2017-6807.'</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 safe_connect(MYSQL* mysql, const char *name, const char *host, const char *user, const char *pass, const char *db, int port, const char *sock) { int failed_attempts= 0; DBUG_ENTER("safe_connect"); verbose_msg("Connecting to server %s:%d (socket %s) as '%s'" ", connection '%s', attempt %d ...", host, port, sock, user, name, failed_attempts); mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0); mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "mysqltest"); mysql_options(mysql, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, &can_handle_expired_passwords); while(!mysql_connect_ssl_check(mysql, host,user, pass, db, port, sock, CLIENT_MULTI_STATEMENTS | CLIENT_REMEMBER_OPTIONS, opt_ssl_required)) { /* Connect failed Only allow retry if this was an error indicating the server could not be contacted. Error code differs depending on protocol/connection type */ if ((mysql_errno(mysql) == CR_CONN_HOST_ERROR || mysql_errno(mysql) == CR_CONNECTION_ERROR) && failed_attempts < opt_max_connect_retries) { verbose_msg("Connect attempt %d/%d failed: %d: %s", failed_attempts, opt_max_connect_retries, mysql_errno(mysql), mysql_error(mysql)); my_sleep(connection_retry_sleep); } else { if (failed_attempts > 0) die("Could not open connection '%s' after %d attempts: %d %s", name, failed_attempts, mysql_errno(mysql), mysql_error(mysql)); else die("Could not open connection '%s': %d %s", name, mysql_errno(mysql), mysql_error(mysql)); } failed_attempts++; } verbose_msg("... Connected."); DBUG_VOID_RETURN; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'</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) { MYSQL mysql; option_string *eptr; MY_INIT(argv[0]); if (load_defaults("my",load_default_groups,&argc,&argv)) { my_end(0); exit(1); } defaults_argv=argv; if (get_options(&argc,&argv)) { free_defaults(defaults_argv); my_end(0); exit(1); } /* Seed the random number generator if we will be using it. */ if (auto_generate_sql) srandom((uint)time(NULL)); /* globals? Yes, so we only have to run strlen once */ delimiter_length= strlen(delimiter); if (argc > 2) { fprintf(stderr,"%s: Too many arguments\n",my_progname); free_defaults(defaults_argv); my_end(0); exit(1); } mysql_init(&mysql); if (opt_compress) mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS); #ifdef HAVE_OPENSSL if (opt_use_ssl) mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); #endif if (opt_protocol) mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset); if (opt_plugin_dir && *opt_plugin_dir) mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth); if (using_opt_enable_cleartext_plugin) mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char*) &opt_enable_cleartext_plugin); if (!opt_only_print) { if (!(mysql_connect_ssl_check(&mysql, host, user, opt_password, NULL, opt_mysql_port, opt_mysql_unix_port, connect_flags, opt_ssl_required))) { fprintf(stderr,"%s: Error when connecting to server: %s\n", my_progname,mysql_error(&mysql)); free_defaults(defaults_argv); my_end(0); exit(1); } } pthread_mutex_init(&counter_mutex, NULL); pthread_cond_init(&count_threshhold, NULL); pthread_mutex_init(&sleeper_mutex, NULL); pthread_cond_init(&sleep_threshhold, NULL); /* Main iterations loop */ eptr= engine_options; do { /* For the final stage we run whatever queries we were asked to run */ uint *current; if (verbose >= 2) printf("Starting Concurrency Test\n"); if (*concurrency) { for (current= concurrency; current && *current; current++) concurrency_loop(&mysql, *current, eptr); } else { uint infinite= 1; do { concurrency_loop(&mysql, infinite, eptr); } while (infinite++); } if (!opt_preserve) drop_schema(&mysql, create_schema_string); } while (eptr ? (eptr= eptr->next) : 0); pthread_mutex_destroy(&counter_mutex); pthread_cond_destroy(&count_threshhold); pthread_mutex_destroy(&sleeper_mutex); pthread_cond_destroy(&sleep_threshhold); if (!opt_only_print) mysql_close(&mysql); /* Close & free connection */ /* now free all the strings we created */ my_free(opt_password); my_free(concurrency); statement_cleanup(create_statements); statement_cleanup(query_statements); statement_cleanup(pre_statements); statement_cleanup(post_statements); option_cleanup(engine_options); #ifdef HAVE_SMEM my_free(shared_memory_base_name); #endif free_defaults(defaults_argv); my_end(my_end_arg); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'</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: MYSQL *mysql_connect_ssl_check(MYSQL *mysql_arg, const char *host, const char *user, const char *passwd, const char *db, uint port, const char *unix_socket, ulong client_flag, my_bool ssl_required __attribute__((unused))) { MYSQL *mysql= mysql_real_connect(mysql_arg, host, user, passwd, db, port, unix_socket, client_flag); #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) if (mysql && /* connection established. */ ssl_required && /* --ssl-mode=REQUIRED. */ !mysql_get_ssl_cipher(mysql)) /* non-SSL connection. */ { NET *net= &mysql->net; net->last_errno= CR_SSL_CONNECTION_ERROR; strmov(net->last_error, "--ssl-mode=REQUIRED option forbids non SSL connections"); strmov(net->sqlstate, "HY000"); return NULL; } #endif return mysql; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'</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 CL_InitRef( void ) { refimport_t ri; refexport_t *ret; #ifdef USE_RENDERER_DLOPEN GetRefAPI_t GetRefAPI; char dllName[MAX_OSPATH]; #endif Com_Printf( "----- Initializing Renderer ----\n" ); #ifdef USE_RENDERER_DLOPEN cl_renderer = Cvar_Get("cl_renderer", "opengl2", CVAR_ARCHIVE | CVAR_LATCH); Com_sprintf(dllName, sizeof(dllName), "renderer_%s_" ARCH_STRING DLL_EXT, cl_renderer->string); if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Cvar_ForceReset("cl_renderer"); Com_sprintf(dllName, sizeof(dllName), "renderer_opengl2_" ARCH_STRING DLL_EXT); rendererLib = Sys_LoadDll(dllName, qfalse); } if(!rendererLib) { Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError()); Com_Error(ERR_FATAL, "Failed to load renderer"); } GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI"); if(!GetRefAPI) { Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError()); } #endif ri.Cmd_AddCommand = Cmd_AddCommand; ri.Cmd_RemoveCommand = Cmd_RemoveCommand; ri.Cmd_Argc = Cmd_Argc; ri.Cmd_Argv = Cmd_Argv; ri.Cmd_ExecuteText = Cbuf_ExecuteText; ri.Printf = CL_RefPrintf; ri.Error = Com_Error; ri.Milliseconds = CL_ScaledMilliseconds; ri.Malloc = CL_RefMalloc; ri.Free = Z_Free; #ifdef HUNK_DEBUG ri.Hunk_AllocDebug = Hunk_AllocDebug; #else ri.Hunk_Alloc = Hunk_Alloc; #endif ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; ri.CM_ClusterPVS = CM_ClusterPVS; ri.CM_DrawDebugSurface = CM_DrawDebugSurface; ri.FS_ReadFile = FS_ReadFile; ri.FS_FreeFile = FS_FreeFile; ri.FS_WriteFile = FS_WriteFile; ri.FS_FreeFileList = FS_FreeFileList; ri.FS_ListFiles = FS_ListFiles; ri.FS_FileIsInPAK = FS_FileIsInPAK; ri.FS_FileExists = FS_FileExists; ri.Cvar_Get = Cvar_Get; ri.Cvar_Set = Cvar_Set; ri.Cvar_SetValue = Cvar_SetValue; ri.Cvar_CheckRange = Cvar_CheckRange; ri.Cvar_SetDescription = Cvar_SetDescription; ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; // cinematic stuff ri.CIN_UploadCinematic = CIN_UploadCinematic; ri.CIN_PlayCinematic = CIN_PlayCinematic; ri.CIN_RunCinematic = CIN_RunCinematic; ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; ri.IN_Init = IN_Init; ri.IN_Shutdown = IN_Shutdown; ri.IN_Restart = IN_Restart; ri.ftol = Q_ftol; ri.Sys_SetEnv = Sys_SetEnv; ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; ri.Sys_GLimpInit = Sys_GLimpInit; ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; ret = GetRefAPI( REF_API_VERSION, &ri ); #if defined __USEA3D && defined __A3D_GEOM hA3Dg_ExportRenderGeom (ret); #endif Com_Printf( "-------------------------------\n"); if ( !ret ) { Com_Error (ERR_FATAL, "Couldn't initialize refresh" ); } re = *ret; // unpause so the cgame definately gets a snapshot and renders a frame Cvar_Set( "cl_paused", "0" ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'Don't load .pk3s as .dlls, and don't load user config files from .pk3s.'</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 * CAPSTONE_API cs_winkernel_malloc(size_t size) { // Disallow zero length allocation because they waste pool header space and, // in many cases, indicate a potential validation issue in the calling code. NT_ASSERT(size); // FP; a use of NonPagedPool is required for Windows 7 support #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory CS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'provide a validity check to prevent against Integer overflow conditions (#870) * provide a validity check to prevent against Integer overflow conditions * fix some style issues.'</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: jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { goto error; } // Mark the box data as never having been constructed // so that we will not errantly attempt to destroy it later. box->ops = &jp2_boxinfo_unk.ops; if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->len = len; JAS_DBGLOG(10, ( "preliminary processing of JP2 box: type=%c%s%c (0x%08x); length=%d\n", '"', boxinfo->name, '"', box->type, box->len )); if (box->len == 1) { if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); // From here onwards, the box data will need to be destroyed. // So, initialize the box operations. box->ops = &boxinfo->ops; if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems.'</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 sock_queue_err_skb(struct sock *sk, struct sk_buff *skb) { if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= (unsigned int)sk->sk_rcvbuf) return -ENOMEM; skb_orphan(skb); skb->sk = sk; skb->destructor = sock_rmem_free; atomic_add(skb->truesize, &sk->sk_rmem_alloc); /* before exiting rcu section, make sure dst is refcounted */ skb_dst_force(skb); skb_queue_tail(&sk->sk_error_queue, skb); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk); return 0; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'tcp: fix SCM_TIMESTAMPING_OPT_STATS for normal skbs __sock_recv_timestamp can be called for both normal skbs (for receive timestamps) and for skbs on the error queue (for transmit timestamps). Commit 1c885808e456 (tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING) assumes any skb passed to __sock_recv_timestamp are from the error queue, containing OPT_STATS in the content of the skb. This results in accessing invalid memory or generating junk data. To fix this, set skb->pkt_type to PACKET_OUTGOING for packets on the error queue. This is safe because on the receive path on local sockets skb->pkt_type is never set to PACKET_OUTGOING. With that, copy OPT_STATS from a packet, only if its pkt_type is PACKET_OUTGOING. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <zzoru007@gmail.com> Signed-off-by: Soheil Hassas Yeganeh <soheil@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Signed-off-by: Willem de Bruijn <willemb@google.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 __u8 *cp_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { unsigned long quirks = (unsigned long)hid_get_drvdata(hdev); unsigned int i; if (!(quirks & CP_RDESC_SWAPPED_MIN_MAX)) return rdesc; for (i = 0; i < *rsize - 4; i++) if (rdesc[i] == 0x29 && rdesc[i + 2] == 0x19) { rdesc[i] = 0x19; rdesc[i + 2] = 0x29; swap(rdesc[i + 3], rdesc[i + 1]); } return rdesc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'HID: hid-cypress: validate length of report Make sure we have enough of a report structure to validate before looking at it. Reported-by: Benoit Camredon <benoit.camredon@airbus.com> Tested-by: Benoit Camredon <benoit.camredon@airbus.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Jiri Kosina <jkosina@suse.cz>'</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 parse_part_sign_sha256(sockent_t *se, /* {{{ */ void **ret_buffer, size_t *ret_buffer_len, int flags) { static c_complain_t complain_no_users = C_COMPLAIN_INIT_STATIC; char *buffer; size_t buffer_len; size_t buffer_offset; size_t username_len; char *secret; part_signature_sha256_t pss; uint16_t pss_head_length; char hash[sizeof(pss.hash)]; gcry_md_hd_t hd; gcry_error_t err; unsigned char *hash_ptr; buffer = *ret_buffer; buffer_len = *ret_buffer_len; buffer_offset = 0; if (se->data.server.userdb == NULL) { c_complain( LOG_NOTICE, &complain_no_users, "network plugin: Received signed network packet but can't verify it " "because no user DB has been configured. Will accept it."); return (0); } /* Check if the buffer has enough data for this structure. */ if (buffer_len <= PART_SIGNATURE_SHA256_SIZE) return (-ENOMEM); /* Read type and length header */ BUFFER_READ(&pss.head.type, sizeof(pss.head.type)); BUFFER_READ(&pss.head.length, sizeof(pss.head.length)); pss_head_length = ntohs(pss.head.length); /* Check if the `pss_head_length' is within bounds. */ if ((pss_head_length <= PART_SIGNATURE_SHA256_SIZE) || (pss_head_length > buffer_len)) { ERROR("network plugin: HMAC-SHA-256 with invalid length received."); return (-1); } /* Copy the hash. */ BUFFER_READ(pss.hash, sizeof(pss.hash)); /* Calculate username length (without null byte) and allocate memory */ username_len = pss_head_length - PART_SIGNATURE_SHA256_SIZE; pss.username = malloc(username_len + 1); if (pss.username == NULL) return (-ENOMEM); /* Read the username */ BUFFER_READ(pss.username, username_len); pss.username[username_len] = 0; assert(buffer_offset == pss_head_length); /* Query the password */ secret = fbh_get(se->data.server.userdb, pss.username); if (secret == NULL) { ERROR("network plugin: Unknown user: %s", pss.username); sfree(pss.username); return (-ENOENT); } /* Create a hash device and check the HMAC */ hd = NULL; err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC); if (err != 0) { ERROR("network plugin: Creating HMAC-SHA-256 object failed: %s", gcry_strerror(err)); sfree(secret); sfree(pss.username); return (-1); } err = gcry_md_setkey(hd, secret, strlen(secret)); if (err != 0) { ERROR("network plugin: gcry_md_setkey failed: %s", gcry_strerror(err)); gcry_md_close(hd); sfree(secret); sfree(pss.username); return (-1); } gcry_md_write(hd, buffer + PART_SIGNATURE_SHA256_SIZE, buffer_len - PART_SIGNATURE_SHA256_SIZE); hash_ptr = gcry_md_read(hd, GCRY_MD_SHA256); if (hash_ptr == NULL) { ERROR("network plugin: gcry_md_read failed."); gcry_md_close(hd); sfree(secret); sfree(pss.username); return (-1); } memcpy(hash, hash_ptr, sizeof(hash)); /* Clean up */ gcry_md_close(hd); hd = NULL; if (memcmp(pss.hash, hash, sizeof(pss.hash)) != 0) { WARNING("network plugin: Verifying HMAC-SHA-256 signature failed: " "Hash mismatch. Username: %s", pss.username); } else { parse_packet(se, buffer + buffer_offset, buffer_len - buffer_offset, flags | PP_SIGNED, pss.username); } sfree(secret); sfree(pss.username); *ret_buffer = buffer + buffer_len; *ret_buffer_len = 0; return (0); } /* }}} int parse_part_sign_sha256 */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'network plugin: Fix endless loop DOS in parse_packet() When correct 'Signature part' is received by Collectd, configured without AuthFile option, condition for endless loop occurs due to missing increase of pointer to next unprocessed part. This is a forward-port of #2233. Fixes: CVE-2017-7401 Closes: #2174 Signed-off-by: Florian Forster <octo@collectd.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 test_re() { assert_true_rule( "rule test { strings: $a = /ssi/ condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /ssi(s|p)/ condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /ssim*/ condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /ssa?/ condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /Miss/ nocase condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /(M|N)iss/ nocase condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /[M-N]iss/ nocase condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /(Mi|ssi)ssippi/ nocase condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /ppi\\tmi/ condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /ppi\\.mi/ condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /^mississippi/ fullword condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_true_rule( "rule test { strings: $a = /mississippi.*mississippi$/s condition: $a }", "mississippi\tmississippi.mississippi\nmississippi"); assert_false_rule( "rule test { strings: $a = /^ssi/ condition: $a }", "mississippi"); assert_false_rule( "rule test { strings: $a = /ssi$/ condition: $a }", "mississippi"); assert_false_rule( "rule test { strings: $a = /ssissi/ fullword condition: $a }", "mississippi"); assert_false_rule( "rule test { strings: $a = /^[isp]+/ condition: $a }", "mississippi"); assert_regexp_syntax_error(")"); assert_true_regexp("abc", "abc", "abc"); assert_false_regexp("abc", "xbc"); assert_false_regexp("abc", "axc"); assert_false_regexp("abc", "abx"); assert_true_regexp("abc", "xabcx", "abc"); assert_true_regexp("abc", "ababc", "abc"); assert_true_regexp("a.c", "abc", "abc"); assert_false_regexp("a.b", "a\nb"); assert_false_regexp("a.*b", "acc\nccb"); assert_false_regexp("a.{4,5}b", "acc\nccb"); assert_true_regexp("a.b", "a\rb", "a\rb"); assert_true_regexp("ab*c", "abc", "abc"); assert_true_regexp("ab*c", "ac", "ac"); assert_true_regexp("ab*bc", "abc", "abc"); assert_true_regexp("ab*bc", "abbc", "abbc"); assert_true_regexp("a.*bb", "abbbb", "abbbb"); assert_true_regexp("a.*?bbb", "abbbbbb", "abbb"); assert_true_regexp("a.*c", "ac", "ac"); assert_true_regexp("a.*c", "axyzc", "axyzc"); assert_true_regexp("ab+c", "abbc", "abbc"); assert_false_regexp("ab+c", "ac"); assert_true_regexp("ab+", "abbbb", "abbbb"); assert_true_regexp("ab+?", "abbbb", "ab"); assert_false_regexp("ab+bc", "abc"); assert_false_regexp("ab+bc", "abq"); assert_true_regexp("a+b+c", "aabbabc", "abc"); assert_false_regexp("ab?bc", "abbbbc"); assert_true_regexp("ab?c", "abc", "abc"); assert_true_regexp("ab*?", "abbb", "a"); assert_true_regexp("ab?c", "abc", "abc"); assert_true_regexp("ab??", "ab", "a"); assert_true_regexp("a(b|x)c", "abc", "abc"); assert_true_regexp("a(b|x)c", "axc", "axc"); assert_true_regexp("a(b|.)c", "axc", "axc"); assert_true_regexp("a(b|x|y)c", "ayc", "ayc"); assert_true_regexp("(a+|b)*", "ab", "ab"); assert_true_regexp("a|b|c|d|e", "e", "e"); assert_true_regexp("(a|b|c|d|e)f", "ef", "ef"); assert_true_regexp(".b{2}", "abb", "abb"); assert_true_regexp("ab{1}c", "abc", "abc"); assert_true_regexp("ab{1,2}c", "abbc", "abbc"); assert_true_regexp("ab{1,}c", "abbbc", "abbbc"); assert_false_regexp("ab{1,}b", "ab"); assert_false_regexp("ab{1}c", "abbc"); assert_true_regexp("ab{0,}c", "ac", "ac"); assert_true_regexp("ab{0,}c", "abbbc", "abbbc"); assert_true_regexp("ab{,3}c", "abbbc", "abbbc"); assert_false_regexp("ab{,2}c", "abbbc"); assert_false_regexp("ab{4,5}bc", "abbbbc"); assert_true_regexp("ab{2,3}?", "abbbbb", "abb"); assert_true_regexp("ab{.*}", "ab{c}", "ab{c}"); assert_true_regexp(".(aa){1,2}", "aaaaaaaaaa", "aaaaa"); assert_true_regexp("a.(bc.){2}", "aabcabca", "aabcabca"); assert_true_regexp("(ab{1,2}c){1,3}", "abbcabc", "abbcabc"); assert_true_regexp("ab(c|cc){1,3}d", "abccccccd", "abccccccd"); assert_true_regexp("a[bx]c", "abc", "abc"); assert_true_regexp("a[bx]c", "axc", "axc"); assert_true_regexp("a[0-9]*b", "ab", "ab"); assert_true_regexp("a[0-9]*b", "a0123456789b", "a0123456789b"); assert_true_regexp("[0-9a-f]+", "0123456789abcdef", "0123456789abcdef"); assert_true_regexp("[0-9a-f]+", "xyz0123456789xyz", "0123456789"); assert_true_regexp("a[\\s\\S]b", "a b", "a b"); assert_true_regexp("a[\\d\\D]b", "a1b", "a1b"); assert_false_regexp("[x-z]+", "abc"); assert_true_regexp("a[-]?c", "ac", "ac"); assert_true_regexp("a[-b]", "a-", "a-"); assert_true_regexp("a[-b]", "ab", "ab"); assert_true_regexp("a[b-]", "a-", "a-"); assert_true_regexp("a[b-]", "ab", "ab"); assert_true_regexp("[a-c-e]", "b", "b"); assert_true_regexp("[a-c-e]", "-", "-"); assert_false_regexp("[a-c-e]", "d"); assert_regexp_syntax_error("[b-a]"); assert_regexp_syntax_error("(abc"); assert_regexp_syntax_error("abc)"); assert_regexp_syntax_error("a[]b"); assert_regexp_syntax_error("a\\"); assert_true_regexp("a[\\-b]", "a-", "a-"); assert_true_regexp("a[\\-b]", "ab", "ab"); assert_regexp_syntax_error("a[\\"); assert_true_regexp("a]", "a]", "a]"); assert_true_regexp("a[]]b", "a]b", "a]b"); assert_true_regexp("a[\\]]b", "a]b", "a]b"); assert_true_regexp("a[^bc]d", "aed", "aed"); assert_false_regexp("a[^bc]d", "abd"); assert_true_regexp("a[^-b]c", "adc", "adc"); assert_false_regexp("a[^-b]c", "a-c"); assert_false_regexp("a[^]b]c", "a]c"); assert_true_regexp("a[^]b]c", "adc", "adc"); assert_true_regexp("[^ab]*", "cde", "cde"); assert_regexp_syntax_error(")("); assert_true_regexp("a\\sb", "a b", "a b"); assert_true_regexp("a\\sb", "a\tb", "a\tb"); assert_true_regexp("a\\sb", "a\rb", "a\rb"); assert_true_regexp("a\\sb", "a\nb", "a\nb"); assert_true_regexp("a\\sb", "a\vb", "a\vb"); assert_true_regexp("a\\sb", "a\fb", "a\fb"); assert_false_regexp("a\\Sb", "a b"); assert_false_regexp("a\\Sb", "a\tb"); assert_false_regexp("a\\Sb", "a\rb"); assert_false_regexp("a\\Sb", "a\nb"); assert_false_regexp("a\\Sb", "a\vb"); assert_false_regexp("a\\Sb", "a\fb"); assert_true_regexp("\\n\\r\\t\\f\\a", "\n\r\t\f\a", "\n\r\t\f\a"); assert_true_regexp("[\\n][\\r][\\t][\\f][\\a]", "\n\r\t\f\a", "\n\r\t\f\a"); assert_true_regexp("\\x01\\x02\\x03", "\x01\x02\x03", "\x01\x02\x03"); assert_true_regexp("[\\x01-\\x03]+", "\x01\x02\x03", "\x01\x02\x03"); assert_false_regexp("[\\x00-\\x02]+", "\x03\x04\x05"); assert_true_regexp("[\\x5D]", "]", "]"); assert_true_regexp("[\\0x5A-\\x5D]", "\x5B", "\x5B"); assert_true_regexp("[\\x5D-\\x5F]", "\x5E", "\x5E"); assert_true_regexp("[\\x5C-\\x5F]", "\x5E", "\x5E"); assert_true_regexp("[\\x5D-\\x5F]", "\x5E", "\x5E"); assert_true_regexp("a\\wc", "abc", "abc"); assert_true_regexp("a\\wc", "a_c", "a_c"); assert_true_regexp("a\\wc", "a0c", "a0c"); assert_false_regexp("a\\wc", "a*c"); assert_true_regexp("\\w+", "--ab_cd0123--", "ab_cd0123"); assert_true_regexp("[\\w]+", "--ab_cd0123--", "ab_cd0123"); assert_true_regexp("\\D+", "1234abc5678", "abc"); assert_true_regexp("[\\d]+", "0123456789", "0123456789"); assert_true_regexp("[\\D]+", "1234abc5678", "abc"); assert_true_regexp("[\\da-fA-F]+", "123abc", "123abc"); assert_false_regexp("^(ab|cd)e", "abcde"); assert_true_regexp("(abc|)ef", "abcdef", "ef"); assert_true_regexp("(abc|)ef", "abcef", "abcef"); assert_true_regexp("\\babc", "abc", "abc"); assert_true_regexp("abc\\b", "abc", "abc"); assert_false_regexp("\\babc", "1abc"); assert_false_regexp("abc\\b", "abc1"); assert_true_regexp("abc\\s\\b", "abc x", "abc "); assert_false_regexp("abc\\s\\b", "abc "); assert_true_regexp("\\babc\\b", " abc ", "abc"); assert_true_regexp("\\b\\w\\w\\w\\b", " abc ", "abc"); assert_true_regexp("\\w\\w\\w\\b", "abcd", "bcd"); assert_true_regexp("\\b\\w\\w\\w", "abcd", "abc"); assert_false_regexp("\\b\\w\\w\\w\\b", "abcd"); assert_false_regexp("\\Babc", "abc"); assert_false_regexp("abc\\B", "abc"); assert_true_regexp("\\Babc", "1abc", "abc"); assert_true_regexp("abc\\B", "abc1", "abc"); assert_false_regexp("abc\\s\\B", "abc x"); assert_true_regexp("abc\\s\\B", "abc ", "abc "); assert_true_regexp("\\w\\w\\w\\B", "abcd", "abc"); assert_true_regexp("\\B\\w\\w\\w", "abcd", "bcd"); assert_false_regexp("\\B\\w\\w\\w\\B", "abcd"); // This is allowed in most regexp engines but in order to keep the // grammar free of shift/reduce conflicts I've decided not supporting // it. Users can use the (abc|) form instead. assert_regexp_syntax_error("(|abc)ef"); assert_true_regexp("((a)(b)c)(d)", "abcd", "abcd"); assert_true_regexp("(a|b)c*d", "abcd", "bcd"); assert_true_regexp("(ab|ab*)bc", "abc", "abc"); assert_true_regexp("a([bc]*)c*", "abc", "abc"); assert_true_regexp("a([bc]*)c*", "ac", "ac"); assert_true_regexp("a([bc]*)c*", "a", "a"); assert_true_regexp("a([bc]*)(c*d)", "abcd", "abcd"); assert_true_regexp("a([bc]+)(c*d)", "abcd", "abcd"); assert_true_regexp("a([bc]*)(c+d)", "abcd", "abcd"); assert_true_regexp("a[bcd]*dcdcde", "adcdcde", "adcdcde"); assert_false_regexp("a[bcd]+dcdcde", "adcdcde"); assert_true_regexp("\\((.*), (.*)\\)", "(a, b)", "(a, b)"); assert_true_regexp("abc|123$", "abcx", "abc"); assert_false_regexp("abc|123$", "123x"); assert_true_regexp("abc|^123", "123", "123"); assert_false_regexp("abc|^123", "x123"); assert_true_regexp("^abc$", "abc", "abc"); assert_false_regexp("^abc$", "abcc"); assert_true_regexp("^abc", "abcc", "abc"); assert_false_regexp("^abc$", "aabc"); assert_true_regexp("abc$", "aabc", "abc"); assert_true_regexp("^a(bc+|b[eh])g|.h$", "abhg", "abhg"); assert_true_regexp("(bc+d$|ef*g.|h?i(j|k))", "effgz", "effgz"); assert_true_regexp("(bc+d$|ef*g.|h?i(j|k))", "ij", "ij"); assert_false_regexp("(bc+d$|ef*g.|h?i(j|k))", "effg"); assert_false_regexp("(bc+d$|ef*g.|h?i(j|k))", "bcdd"); assert_true_regexp("(bc+d$|ef*g.|h?i(j|k))", "reffgz", "effgz"); // Test case for issue #324 assert_true_regexp("whatever| x. x", " xy x", " xy x"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-703', 'CWE-125'], 'message': 're_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c'</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: psf_asciiheader_printf (SF_PRIVATE *psf, const char *format, ...) { va_list argptr ; int maxlen ; char *start ; maxlen = strlen ((char*) psf->header) ; start = ((char*) psf->header) + maxlen ; maxlen = sizeof (psf->header) - maxlen ; va_start (argptr, format) ; vsnprintf (start, maxlen, format, argptr) ; va_end (argptr) ; /* Make sure the string is properly terminated. */ start [maxlen - 1] = 0 ; psf->headindex = strlen ((char*) psf->header) ; return ; } /* psf_asciiheader_printf */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = (x >> 56) ; psf->header [psf->headindex++] = (x >> 48) ; psf->header [psf->headindex++] = (x >> 40) ; psf->header [psf->headindex++] = (x >> 32) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_8byte */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: header_seek (SF_PRIVATE *psf, sf_count_t position, int whence) { switch (whence) { case SEEK_SET : if (position > SIGNED_SIZEOF (psf->header)) { /* Too much header to cache so just seek instead. */ psf_fseek (psf, position, whence) ; return ; } ; if (position > psf->headend) psf->headend += psf_fread (psf->header + psf->headend, 1, position - psf->headend, psf) ; psf->headindex = position ; break ; case SEEK_CUR : if (psf->headindex + position < 0) break ; if (psf->headindex >= SIGNED_SIZEOF (psf->header)) { psf_fseek (psf, position, whence) ; return ; } ; if (psf->headindex + position <= psf->headend) { psf->headindex += position ; break ; } ; if (psf->headindex + position > SIGNED_SIZEOF (psf->header)) { /* Need to jump this without caching it. */ psf->headindex = psf->headend ; psf_fseek (psf, position, SEEK_CUR) ; break ; } ; psf->headend += psf_fread (psf->header + psf->headend, 1, position - (psf->headend - psf->headindex), psf) ; psf->headindex = psf->headend ; break ; case SEEK_END : default : psf_log_printf (psf, "Bad whence param in header_seek().\n") ; break ; } ; return ; } /* header_seek */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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 ahash_def_finup(struct ahash_request *req) { struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); int err; err = ahash_save_req(req, ahash_def_finup_done1); if (err) return err; err = tfm->update(req); return ahash_def_finup_finish1(req, err); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'crypto: ahash - Fix EINPROGRESS notification callback The ahash API modifies the request's callback function in order to clean up after itself in some corner cases (unaligned final and missing finup). When the request is complete ahash will restore the original callback and everything is fine. However, when the request gets an EBUSY on a full queue, an EINPROGRESS callback is made while the request is still ongoing. In this case the ahash API will incorrectly call its own callback. This patch fixes the problem by creating a temporary request object on the stack which is used to relay EINPROGRESS back to the original completion function. This patch also adds code to preserve the original flags value. Fixes: ab6bf4e5e5e4 ("crypto: hash - Fix the pointer voodoo in...") Cc: <stable@vger.kernel.org> Reported-by: Sabrina Dubroca <sd@queasysnail.net> Tested-by: Sabrina Dubroca <sd@queasysnail.net> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</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 ModulateLCHab(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHab(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue >= 1.0) hue-=1.0; ConvertLCHabToRGB(luma,chroma,hue,red,green,blue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31506'</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: fill_threshhold_buffer(byte *dest_strip, byte *src_strip, int src_width, int left_offset, int left_width, int num_tiles, int right_width) { byte *ptr_out_temp = dest_strip; int ii; /* Left part */ memcpy(dest_strip, src_strip + left_offset, left_width); ptr_out_temp += left_width; /* Now the full parts */ for (ii = 0; ii < num_tiles; ii++){ memcpy(ptr_out_temp, src_strip, src_width); ptr_out_temp += src_width; } /* Now the remainder */ memcpy(ptr_out_temp, src_strip, right_width); #ifdef PACIFY_VALGRIND ptr_out_temp += right_width; ii = (dest_strip-ptr_out_temp) % (LAND_BITS-1); if (ii > 0) memset(ptr_out_temp, 0, ii); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug 697459 Buffer overflow in fill_threshold_buffer There was an overflow check for ht_buffer size, but none for the larger threshold_buffer. Note that this file didn't fail on Windows because the combination of the ht_buffer and the size of the (miscalculated due to overflow) threshold_buffer would have exceeded the 2Gb limit.'</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 *get_56_lenc_string(char **buffer, size_t *max_bytes_available, size_t *string_length) { static char empty_string[1]= { '\0' }; char *begin= *buffer; if (*max_bytes_available == 0) return NULL; /* If the length encoded string has the length 0 the total size of the string is only one byte long (the size byte) */ if (*begin == 0) { *string_length= 0; --*max_bytes_available; ++*buffer; /* Return a pointer to the \0 character so the return value will be an empty string. */ return empty_string; } *string_length= (size_t)net_field_length_ll((uchar **)buffer); DBUG_EXECUTE_IF("sha256_password_scramble_too_long", *string_length= SIZE_T_MAX; ); size_t len_len= (size_t)(*buffer - begin); if (*string_length > *max_bytes_available - len_len) return NULL; *max_bytes_available -= *string_length; *max_bytes_available -= len_len; *buffer += *string_length; return (char *)(begin + len_len); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Bug#25714674: MYSQL SERVER REMOTE PREAUTH PROBLEM THROUGH INTEGER OVERFLOW Description: A missing length check for length-encoded string causes problem in preauthorization stage. (cherry picked from commit bb1af908fce21b0d8708cdccde628e3d5b1d86ec)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void cirrus_bitblt_rop_nop(CirrusVGAState *s, uint8_t *dst,const uint8_t *src, int dstpitch,int srcpitch, int bltwidth,int bltheight) { } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <kraxel@redhat.com> Message-id: 1489574872-8679-1-git-send-email-kraxel@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 inline void glue(rop_16_,ROP_NAME)(uint16_t *dst, uint16_t src) { *dst = ROP_FN(*dst, src); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <kraxel@redhat.com> Message-id: 1489574872-8679-1-git-send-email-kraxel@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 cirrus_bitblt_videotovideo_patterncopy(CirrusVGAState * s) { return cirrus_bitblt_common_patterncopy(s, true); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter Does basically the same as "cirrus: stop passing around dst pointers in the blitter", just for the src pointer instead of the dst pointer. For the src we have to care about cputovideo blits though and fetch the data from s->cirrus_bltbuf instead of vga memory. The cirrus_src*() helper functions handle that. Signed-off-by: Gerd Hoffmann <kraxel@redhat.com> Message-id: 1489584487-3489-1-git-send-email-kraxel@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 cirrus_do_copy(CirrusVGAState *s, int dst, int src, int w, int h) { int sx = 0, sy = 0; int dx = 0, dy = 0; int depth = 0; int notify = 0; /* make sure to 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) { int width, height; depth = s->vga.get_bpp(&s->vga) / 8; if (!depth) { return 0; } s->vga.get_resolution(&s->vga, &width, &height); /* extra x, y */ sx = (src % ABS(s->cirrus_blt_srcpitch)) / depth; sy = (src / ABS(s->cirrus_blt_srcpitch)); dx = (dst % ABS(s->cirrus_blt_dstpitch)) / depth; dy = (dst / ABS(s->cirrus_blt_dstpitch)); /* 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; } } (*s->cirrus_rop) (s, s->cirrus_blt_dstaddr, s->vga.vram_ptr + s->cirrus_blt_srcaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_srcpitch, s->cirrus_blt_width, s->cirrus_blt_height); if (notify) { dpy_gfx_update(s->vga.con, 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 qemu_console_copy implies this */ 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-119'], 'message': 'cirrus: stop passing around src pointers in the blitter Does basically the same as "cirrus: stop passing around dst pointers in the blitter", just for the src pointer instead of the dst pointer. For the src we have to care about cputovideo blits though and fetch the data from s->cirrus_bltbuf instead of vga memory. The cirrus_src*() helper functions handle that. Signed-off-by: Gerd Hoffmann <kraxel@redhat.com> Message-id: 1489584487-3489-1-git-send-email-kraxel@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 cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; unsigned long flags; int ret; spin_lock_irqsave(&dev->lock, flags); ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_GET_REPORT); if (ret != CP2112_GPIO_CONFIG_LENGTH) { hid_err(hdev, "error requesting GPIO config: %d\n", ret); goto exit; } buf[1] &= ~(1 << offset); buf[2] = gpio_push_pull; ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf, CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) { hid_err(hdev, "error setting GPIO config: %d\n", ret); goto exit; } ret = 0; exit: spin_unlock_irqrestore(&dev->lock, flags); return ret <= 0 ? ret : -EIO; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-404', 'CWE-703'], 'message': 'HID: cp2112: fix sleep-while-atomic A recent commit fixing DMA-buffers on stack added a shared transfer buffer protected by a spinlock. This is broken as the USB HID request callbacks can sleep. Fix this up by replacing the spinlock with a mutex. Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable") Cc: stable <stable@vger.kernel.org> # 4.9 Signed-off-by: Johan Hovold <johan@kernel.org> Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz>'</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 usb_cypress_load_firmware(struct usb_device *udev, const struct firmware *fw, int type) { struct hexline *hx; u8 reset; int ret,pos=0; hx = kmalloc(sizeof(*hx), GFP_KERNEL); if (!hx) return -ENOMEM; /* stop the CPU */ reset = 1; if ((ret = usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1)) != 1) err("could not stop the USB controller CPU."); while ((ret = dvb_usb_get_hexline(fw, hx, &pos)) > 0) { deb_fw("writing to address 0x%04x (buffer: 0x%02x %02x)\n", hx->addr, hx->len, hx->chk); ret = usb_cypress_writemem(udev, hx->addr, hx->data, hx->len); if (ret != hx->len) { err("error while transferring firmware (transferred size: %d, block size: %d)", ret, hx->len); ret = -EINVAL; break; } } if (ret < 0) { err("firmware download failed at %d with %d",pos,ret); kfree(hx); return ret; } if (ret == 0) { /* restart the CPU */ reset = 0; if (ret || usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1) != 1) { err("could not restart the USB controller CPU."); ret = -EINVAL; } } else ret = -EIO; kfree(hx); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '[media] dvb-usb-firmware: don't do DMA on stack The buffer allocation for the firmware data was changed in commit 43fab9793c1f ("[media] dvb-usb: don't use stack for firmware load") but the same applies for the reset value. Fixes: 43fab9793c1f ("[media] dvb-usb: don't use stack for firmware load") Cc: stable@vger.kernel.org Signed-off-by: Stefan Brüns <stefan.bruens@rwth-aachen.de> Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.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 get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data) { return usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0), RTL8150_REQ_GET_REGS, RTL8150_REQT_READ, indx, 0, data, size, 500); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'rtl8150: Use heap buffers for all register access Allocating USB buffers on the stack is not portable, and no longer works on x86_64 (with VMAP_STACK enabled as per default). Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Signed-off-by: Ben Hutchings <ben@decadent.org.uk> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int rxrpc_krb5_decode_tagged_data(struct krb5_tagged_data *td, size_t max_data_size, const __be32 **_xdr, unsigned int *_toklen) { const __be32 *xdr = *_xdr; unsigned int toklen = *_toklen, len; /* there must be at least one tag and one length word */ if (toklen <= 8) return -EINVAL; _enter(",%zu,{%x,%x},%u", max_data_size, ntohl(xdr[0]), ntohl(xdr[1]), toklen); td->tag = ntohl(*xdr++); len = ntohl(*xdr++); toklen -= 8; if (len > max_data_size) return -EINVAL; td->data_len = len; if (len > 0) { td->data = kmemdup(xdr, len, GFP_KERNEL); if (!td->data) return -ENOMEM; len = (len + 3) & ~3; toklen -= len; xdr += len >> 2; } _debug("tag %x len %x", td->tag, td->data_len); *_xdr = xdr; *_toklen = toklen; _leave(" = 0 [toklen=%u]", toklen); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'rxrpc: Fix several cases where a padded len isn't checked in ticket decode This fixes CVE-2017-7482. When a kerberos 5 ticket is being decoded so that it can be loaded into an rxrpc-type key, there are several places in which the length of a variable-length field is checked to make sure that it's not going to overrun the available data - but the data is padded to the nearest four-byte boundary and the code doesn't check for this extra. This could lead to the size-remaining variable wrapping and the data pointer going over the end of the buffer. Fix this by making the various variable-length data checks use the padded length. Reported-by: 石磊 <shilei-c@360.cn> Signed-off-by: David Howells <dhowells@redhat.com> Reviewed-by: Marc Dionne <marc.c.dionne@auristor.com> Reviewed-by: Dan Carpenter <dan.carpenter@oracle.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: ActionReply Smb4KMountHelper::unmount(const QVariantMap &args) { ActionReply reply; // The mountpoint is a unique and can be used to // find the share. reply.addData("mh_mountpoint", args["mh_mountpoint"]); // Check if the mountpoint is valid and the file system is // also correct. bool mountpoint_ok = false; KMountPoint::List mountpoints = KMountPoint::currentMountPoints(KMountPoint::BasicInfoNeeded|KMountPoint::NeedMountOptions); for(int j = 0; j < mountpoints.size(); j++) { #ifdef Q_OS_LINUX if (QString::compare(args["mh_mountpoint"].toString(), mountpoints.at(j)->mountPoint(), Qt::CaseInsensitive) == 0 && QString::compare(mountpoints.at(j)->mountType(), "cifs", Qt::CaseInsensitive) == 0) #else if (QString::compare(args["mh_mountpoint"].toString(), mountpoints.at(j)->mountPoint(), Qt::CaseInsensitive) == 0 && QString::compare(mountpoints.at(j)->mountType(), "smbfs", Qt::CaseInsensitive) == 0) #endif { mountpoint_ok = true; break; } else { continue; } } if (!mountpoint_ok) { reply.setErrorCode(ActionReply::HelperError); reply.setErrorDescription(i18n("The mountpoint is invalid.")); return reply; } else { // Do nothing } KProcess proc(this); proc.setOutputChannelMode(KProcess::SeparateChannels); proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment()); // Set the umount command here. QStringList command; command << args["mh_command"].toString(); command << args["mh_options"].toStringList(); command << args["mh_mountpoint"].toString(); proc.setProgram(command); // Run the unmount process. proc.start(); if (proc.waitForStarted(-1)) { // We want to be able to terminate the process from outside. // Thus, we implement a loop that checks periodically, if we // need to kill the process. bool user_kill = false; while (!proc.waitForFinished(10)) { if (HelperSupport::isStopped()) { proc.kill(); user_kill = true; break; } else { // Do nothing } } if (proc.exitStatus() == KProcess::CrashExit) { if (!user_kill) { reply.setErrorCode(ActionReply::HelperError); reply.setErrorDescription(i18n("The unmount process crashed.")); return reply; } else { // Do nothing } } else { // Check if there is output on stderr. QString stdErr = QString::fromUtf8(proc.readAllStandardError()); reply.addData("mh_error_message", stdErr.trimmed()); } } else { reply.setErrorCode(ActionReply::HelperError); reply.setErrorDescription(i18n("The unmount process could not be started.")); } return reply; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Find the mount/umount commands in the helper Instead of trusting what we get passed in CVE-2017-8849'</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 sock *inet_csk_clone_lock(const struct sock *sk, const struct request_sock *req, const gfp_t priority) { struct sock *newsk = sk_clone_lock(sk, priority); if (newsk) { struct inet_connection_sock *newicsk = inet_csk(newsk); newsk->sk_state = TCP_SYN_RECV; newicsk->icsk_bind_hash = NULL; inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port; inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num; inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num); newsk->sk_write_space = sk_stream_write_space; /* listeners have SOCK_RCU_FREE, not the children */ sock_reset_flag(newsk, SOCK_RCU_FREE); newsk->sk_mark = inet_rsk(req)->ir_mark; atomic64_set(&newsk->sk_cookie, atomic64_read(&inet_rsk(req)->ir_cookie)); newicsk->icsk_retransmits = 0; newicsk->icsk_backoff = 0; newicsk->icsk_probes_out = 0; /* Deinitialize accept_queue to trap illegal accesses. */ memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue)); security_inet_csk_clone(newsk, req); } return newsk; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-415'], 'message': 'dccp/tcp: do not inherit mc_list from parent syzkaller found a way to trigger double frees from ip_mc_drop_socket() It turns out that leave a copy of parent mc_list at accept() time, which is very bad. Very similar to commit 8b485ce69876 ("tcp: do not inherit fastopen_req from parent") Initial report from Pray3r, completed by Andrey one. Thanks a lot to them ! Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Pray3r <pray3r.z@gmail.com> Reported-by: Andrey Konovalov <andreyknvl@google.com> Tested-by: Andrey Konovalov <andreyknvl@google.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 omninet_open(struct tty_struct *tty, struct usb_serial_port *port) { struct usb_serial *serial = port->serial; struct usb_serial_port *wport; wport = serial->port[1]; tty_port_tty_set(&wport->port, tty); return usb_serial_generic_open(tty, port); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-404'], 'message': 'USB: serial: omninet: fix reference leaks at open This driver needlessly took another reference to the tty on open, a reference which was then never released on close. This lead to not just a leak of the tty, but also a driver reference leak that prevented the driver from being unloaded after a port had once been opened. Fixes: 4a90f09b20f4 ("tty: usb-serial krefs") Cc: stable <stable@vger.kernel.org> # 2.6.28 Signed-off-by: Johan Hovold <johan@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { FD_t payload = rpmtePayload(te); rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int saveerrno = errno; int rc = 0; int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0; int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0; int firsthardlink = -1; int skip; rpmFileAction action; char *tid = NULL; const char *suffix; char *fpath = NULL; if (fi == NULL) { rc = RPMERR_BAD_MAGIC; goto exit; } /* transaction id used for temporary path suffix while installing */ rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts)); /* Detect and create directories not explicitly in package. */ rc = fsmMkdirs(files, fs, plugins); while (!rc) { /* Read next payload header. */ rc = rpmfiNext(fi); if (rc < 0) { if (rc == RPMERR_ITER_END) rc = 0; break; } action = rpmfsGetAction(fs, rpmfiFX(fi)); skip = XFA_SKIPPING(action); suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid; if (action != FA_TOUCH) { fpath = fsmFsPath(fi, suffix); } else { fpath = fsmFsPath(fi, ""); } /* Remap file perms, owner, and group. */ rc = rpmfiStat(fi, 1, &sb); fsmDebug(fpath, action, &sb); /* Exit on error. */ if (rc) break; /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (rc) { skip = 1; } else { setFileState(fs, rpmfiFX(fi)); } if (!skip) { int setmeta = 1; /* Directories replacing something need early backup */ if (!suffix) { rc = fsmBackup(fi, action); } /* Assume file does't exist when tmp suffix is in use */ if (!suffix) { rc = fsmVerify(fpath, fi); } else { rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT; } if (S_ISREG(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMkfile(fi, fpath, files, psm, nodigest, &setmeta, &firsthardlink); } } else if (S_ISDIR(sb.st_mode)) { if (rc == RPMERR_ENOENT) { mode_t mode = sb.st_mode; mode &= ~07777; mode |= 00700; rc = fsmMkdir(fpath, mode); } } else if (S_ISLNK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmSymlink(rpmfiFLink(fi), fpath); } } else if (S_ISFIFO(sb.st_mode)) { /* This mimics cpio S_ISSOCK() behavior but probably isn't right */ if (rc == RPMERR_ENOENT) { rc = fsmMkfifo(fpath, 0000); } } else if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode) || S_ISSOCK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev); } } else { /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!IS_DEV_LOG(fpath)) rc = RPMERR_UNKNOWN_FILETYPE; } /* Set permissions, timestamps etc for non-hardlink entries */ if (!rc && setmeta) { rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps); } } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) { /* we skip the hard linked file containing the content */ /* write the content to the first used instead */ char *fn = rpmfilesFN(files, firsthardlink); rc = expandRegular(fi, fn, psm, nodigest, 0); firsthardlink = -1; free(fn); } if (rc) { if (!skip) { /* XXX only erase if temp fn w suffix is in use */ if (suffix && (action != FA_TOUCH)) { (void) fsmRemove(fpath, sb.st_mode); } errno = saveerrno; } } else { /* Notify on success. */ rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi)); if (!skip) { /* Backup file if needed. Directories are handled earlier */ if (suffix) rc = fsmBackup(fi, action); if (!rc) rc = fsmCommit(&fpath, fi, action, suffix); } } if (rc) *failedFile = xstrdup(fpath); /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); fpath = _free(fpath); } rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ)); rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST)); exit: /* No need to bother with close errors on read */ rpmfiArchiveClose(fi); rpmfiFree(fi); Fclose(payload); free(tid); free(fpath); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'Don't follow symlinks on file creation (CVE-2017-7501) Open newly created files with O_EXCL to prevent symlink tricks. When reopening hardlinks for writing the actual content, use append mode instead. This is compatible with the write-only permissions but is not destructive in case we got redirected to somebody elses file, verify the target before actually writing anything. As these are files with the temporary suffix, errors mean a local user with sufficient privileges to break the installation of the package anyway is trying to goof us on purpose, don't bother trying to mend it (we couldn't fix the hardlink case anyhow) but just bail out. Based on a patch by Florian Festi.'</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 sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-241'], 'message': 'ipv6/dccp: do not inherit ipv6_mc_list from parent Like commit 657831ffc38e ("dccp/tcp: do not inherit mc_list from parent") we should clear ipv6_mc_list etc. for IPv6 sockets too. Cc: Eric Dumazet <edumazet@google.com> Signed-off-by: Cong Wang <xiyou.wangcong@gmail.com> Acked-by: Eric Dumazet <edumazet@google.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: run_cmd(int fd, ...) { pid_t pid; sigset_t sigm, sigm_old; /* block signals, let child establish its own handlers */ sigemptyset(&sigm); sigaddset(&sigm, SIGTERM); sigprocmask(SIG_BLOCK, &sigm, &sigm_old); pid = fork(); if ( pid < 0 ) { sigprocmask(SIG_SETMASK, &sigm_old, NULL); fd_printf(STO, "*** cannot fork: %s ***\r\n", strerror(errno)); return -1; } else if ( pid ) { /* father: picocom */ int status, r; /* reset the mask */ sigprocmask(SIG_SETMASK, &sigm_old, NULL); /* wait for child to finish */ do { r = waitpid(pid, &status, 0); } while ( r < 0 && errno == EINTR ); /* reset terminal (back to raw mode) */ term_apply(STI); /* check and report child return status */ if ( WIFEXITED(status) ) { fd_printf(STO, "\r\n*** exit status: %d ***\r\n", WEXITSTATUS(status)); return WEXITSTATUS(status); } else if ( WIFSIGNALED(status) ) { fd_printf(STO, "\r\n*** killed by signal: %d ***\r\n", WTERMSIG(status)); return -1; } else { fd_printf(STO, "\r\n*** abnormal termination: 0x%x ***\r\n", r); return -1; } } else { /* child: external program */ long fl; char cmd[512]; /* unmanage terminal, and reset it to canonical mode */ term_remove(STI); /* unmanage serial port fd, without reset */ term_erase(fd); /* set serial port fd to blocking mode */ fl = fcntl(fd, F_GETFL); fl &= ~O_NONBLOCK; fcntl(fd, F_SETFL, fl); /* connect stdin and stdout to serial port */ close(STI); close(STO); dup2(fd, STI); dup2(fd, STO); { /* build command-line */ char *c, *ce; const char *s; int n; va_list vls; strcpy(cmd, EXEC); c = &cmd[sizeof(EXEC)- 1]; ce = cmd + sizeof(cmd) - 1; va_start(vls, fd); while ( (s = va_arg(vls, const char *)) ) { n = strlen(s); if ( c + n + 1 >= ce ) break; memcpy(c, s, n); c += n; *c++ = ' '; } va_end(vls); *c = '\0'; } /* run extenral command */ fd_printf(STDERR_FILENO, "%s\n", &cmd[sizeof(EXEC) - 1]); establish_child_signal_handlers(); sigprocmask(SIG_SETMASK, &sigm_old, NULL); execl("/bin/sh", "sh", "-c", cmd, NULL); exit(42); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-77', 'CWE-125'], 'message': 'Do not use "/bin/sh" to run external commands. Picocom no longer uses /bin/sh to run external commands for file-transfer operations. Parsing the command line and spliting it into arguments is now performed internally by picocom, using quoting rules very similar to those of the Unix shell. Hopefully, this makes it impossible to inject shell-commands when supplying filenames or extra arguments to the send- and receive-file commands.'</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: bool Inflator::DecodeBody() { bool blockEnd = false; switch (m_blockType) { case 0: // stored CRYPTOPP_ASSERT(m_reader.BitsBuffered() == 0); while (!m_inQueue.IsEmpty() && !blockEnd) { size_t size; const byte *block = m_inQueue.Spy(size); size = UnsignedMin(m_storedLen, size); CRYPTOPP_ASSERT(size <= 0xffff); OutputString(block, size); m_inQueue.Skip(size); m_storedLen = m_storedLen - (word16)size; if (m_storedLen == 0) blockEnd = true; } break; case 1: // fixed codes case 2: // dynamic codes static const unsigned int lengthStarts[] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; static const unsigned int lengthExtraBits[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; static const unsigned int distanceStarts[] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; static const unsigned int distanceExtraBits[] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; const HuffmanDecoder& literalDecoder = GetLiteralDecoder(); const HuffmanDecoder& distanceDecoder = GetDistanceDecoder(); switch (m_nextDecode) { case LITERAL: while (true) { if (!literalDecoder.Decode(m_reader, m_literal)) { m_nextDecode = LITERAL; break; } if (m_literal < 256) OutputByte((byte)m_literal); else if (m_literal == 256) // end of block { blockEnd = true; break; } else { if (m_literal > 285) throw BadBlockErr(); unsigned int bits; case LENGTH_BITS: bits = lengthExtraBits[m_literal-257]; if (!m_reader.FillBuffer(bits)) { m_nextDecode = LENGTH_BITS; break; } m_literal = m_reader.GetBits(bits) + lengthStarts[m_literal-257]; case DISTANCE: if (!distanceDecoder.Decode(m_reader, m_distance)) { m_nextDecode = DISTANCE; break; } case DISTANCE_BITS: // TODO: this surfaced during fuzzing. What do we do??? CRYPTOPP_ASSERT(m_distance < COUNTOF(distanceExtraBits)); bits = (m_distance >= COUNTOF(distanceExtraBits)) ? distanceExtraBits[29] : distanceExtraBits[m_distance]; if (!m_reader.FillBuffer(bits)) { m_nextDecode = DISTANCE_BITS; break; } m_distance = m_reader.GetBits(bits) + distanceStarts[m_distance]; OutputPast(m_literal, m_distance); } } break; default: CRYPTOPP_ASSERT(0); } } if (blockEnd) { if (m_eof) { FlushOutput(); m_reader.SkipBits(m_reader.BitsBuffered()%8); if (m_reader.BitsBuffered()) { // undo too much lookahead SecBlockWithHint<byte, 4> buffer(m_reader.BitsBuffered() / 8); for (unsigned int i=0; i<buffer.size(); i++) buffer[i] = (byte)m_reader.GetBits(8); m_inQueue.Unget(buffer, buffer.size()); } m_state = POST_STREAM; } else m_state = WAIT_HEADER; } return blockEnd; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Add Inflator::BadDistanceErr exception (Issue 414) The improved validation and excpetion clears the Address Sanitizer and Undefined Behavior Sanitizer findings'</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: connection_exit_begin_conn(cell_t *cell, circuit_t *circ) { edge_connection_t *n_stream; relay_header_t rh; char *address = NULL; uint16_t port = 0; or_circuit_t *or_circ = NULL; const or_options_t *options = get_options(); begin_cell_t bcell; int rv; uint8_t end_reason=0; assert_circuit_ok(circ); if (!CIRCUIT_IS_ORIGIN(circ)) or_circ = TO_OR_CIRCUIT(circ); relay_header_unpack(&rh, cell->payload); if (rh.length > RELAY_PAYLOAD_SIZE) return -END_CIRC_REASON_TORPROTOCOL; /* Note: we have to use relay_send_command_from_edge here, not * connection_edge_end or connection_edge_send_command, since those require * that we have a stream connected to a circuit, and we don't connect to a * circuit until we have a pending/successful resolve. */ if (!server_mode(options) && circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Relay begin cell at non-server. Closing."); relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_EXITPOLICY, NULL); return 0; } rv = begin_cell_parse(cell, &bcell, &end_reason); if (rv < -1) { return -END_CIRC_REASON_TORPROTOCOL; } else if (rv == -1) { tor_free(bcell.address); relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, NULL); return 0; } if (! bcell.is_begindir) { /* Steal reference */ address = bcell.address; port = bcell.port; if (or_circ && or_circ->p_chan) { if (!options->AllowSingleHopExits && (or_circ->is_first_hop || (!connection_or_digest_is_known_relay( or_circ->p_chan->identity_digest) && should_refuse_unknown_exits(options)))) { /* Don't let clients use us as a single-hop proxy, unless the user * has explicitly allowed that in the config. It attracts attackers * and users who'd be better off with, well, single-hop proxies. */ log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Attempt by %s to open a stream %s. Closing.", safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)), or_circ->is_first_hop ? "on first hop of circuit" : "from unknown relay"); relay_send_end_cell_from_edge(rh.stream_id, circ, or_circ->is_first_hop ? END_STREAM_REASON_TORPROTOCOL : END_STREAM_REASON_MISC, NULL); tor_free(address); return 0; } } } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) { if (!directory_permits_begindir_requests(options) || circ->purpose != CIRCUIT_PURPOSE_OR) { relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_NOTDIRECTORY, NULL); return 0; } /* Make sure to get the 'real' address of the previous hop: the * caller might want to know whether the remote IP address has changed, * and we might already have corrected base_.addr[ess] for the relay's * canonical IP address. */ if (or_circ && or_circ->p_chan) address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan)); else address = tor_strdup("127.0.0.1"); port = 1; /* XXXX This value is never actually used anywhere, and there * isn't "really" a connection here. But we * need to set it to something nonzero. */ } else { log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command); relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_INTERNAL, NULL); return 0; } if (! options->IPv6Exit) { /* I don't care if you prefer IPv6; I can't give you any. */ bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED; /* If you don't want IPv4, I can't help. */ if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) { tor_free(address); relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_EXITPOLICY, NULL); return 0; } } log_debug(LD_EXIT,"Creating new exit connection."); /* The 'AF_INET' here is temporary; we might need to change it later in * connection_exit_connect(). */ n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET); /* Remember the tunneled request ID in the new edge connection, so that * we can measure download times. */ n_stream->dirreq_id = circ->dirreq_id; n_stream->base_.purpose = EXIT_PURPOSE_CONNECT; n_stream->begincell_flags = bcell.flags; n_stream->stream_id = rh.stream_id; n_stream->base_.port = port; /* leave n_stream->s at -1, because it's not yet valid */ n_stream->package_window = STREAMWINDOW_START; n_stream->deliver_window = STREAMWINDOW_START; if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) { origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ); log_info(LD_REND,"begin is for rendezvous. configuring stream."); n_stream->base_.address = tor_strdup("(rendezvous)"); n_stream->base_.state = EXIT_CONN_STATE_CONNECTING; n_stream->rend_data = rend_data_dup(origin_circ->rend_data); tor_assert(connection_edge_is_rendezvous_stream(n_stream)); assert_circuit_ok(circ); const int r = rend_service_set_connection_addr_port(n_stream, origin_circ); if (r < 0) { log_info(LD_REND,"Didn't find rendezvous service (port %d)", n_stream->base_.port); /* Send back reason DONE because we want to make hidden service port * scanning harder thus instead of returning that the exit policy * didn't match, which makes it obvious that the port is closed, * return DONE and kill the circuit. That way, a user (malicious or * not) needs one circuit per bad port unless it matches the policy of * the hidden service. */ relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_DONE, origin_circ->cpath->prev); connection_free(TO_CONN(n_stream)); tor_free(address); /* Drop the circuit here since it might be someone deliberately * scanning the hidden service ports. Note that this mitigates port * scanning by adding more work on the attacker side to successfully * scan but does not fully solve it. */ if (r < -1) return END_CIRC_AT_ORIGIN; else return 0; } assert_circuit_ok(circ); log_debug(LD_REND,"Finished assigning addr/port"); n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */ /* add it into the linked list of p_streams on this circuit */ n_stream->next_stream = origin_circ->p_streams; n_stream->on_circuit = circ; origin_circ->p_streams = n_stream; assert_circuit_ok(circ); origin_circ->rend_data->nr_streams++; connection_exit_connect(n_stream); /* For path bias: This circuit was used successfully */ pathbias_mark_use_success(origin_circ); tor_free(address); return 0; } tor_strlower(address); n_stream->base_.address = address; n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED; /* default to failed, change in dns_resolve if it turns out not to fail */ if (we_are_hibernating()) { relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_HIBERNATING, NULL); connection_free(TO_CONN(n_stream)); return 0; } n_stream->on_circuit = circ; if (rh.command == RELAY_COMMAND_BEGIN_DIR) { tor_addr_t tmp_addr; tor_assert(or_circ); if (or_circ->p_chan && channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) { tor_addr_copy(&n_stream->base_.addr, &tmp_addr); } return connection_exit_connect_dir(n_stream); } log_debug(LD_EXIT,"about to start the dns_resolve()."); /* send it off to the gethostbyname farm */ switch (dns_resolve(n_stream)) { case 1: /* resolve worked; now n_stream is attached to circ. */ assert_circuit_ok(circ); log_debug(LD_EXIT,"about to call connection_exit_connect()."); connection_exit_connect(n_stream); return 0; case -1: /* resolve failed */ relay_send_end_cell_from_edge(rh.stream_id, circ, END_STREAM_REASON_RESOLVEFAILED, NULL); /* n_stream got freed. don't touch it. */ break; case 0: /* resolve added to pending list */ assert_circuit_ok(circ); break; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-617'], 'message': 'TROVE-2017-004: Fix assertion failure in relay_send_end_cell_from_edge_ This fixes an assertion failure in relay_send_end_cell_from_edge_() when an origin circuit and a cpath_layer = NULL were passed. A service rendezvous circuit could do such a thing when a malformed BEGIN cell is received but shouldn't in the first place because the service needs to send an END cell on the circuit for which it can not do without a cpath_layer. Fixes #22493 Reported-by: Roger Dingledine <arma@torproject.org> Signed-off-by: David Goulet <dgoulet@torproject.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: arch_get_unmapped_area(struct file *filp, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags) { struct mm_struct *mm = current->mm; struct vm_area_struct *vma; struct vm_unmapped_area_info info; if (len > TASK_SIZE - mmap_min_addr) return -ENOMEM; if (flags & MAP_FIXED) return addr; if (addr) { addr = PAGE_ALIGN(addr); vma = find_vma(mm, addr); if (TASK_SIZE - len >= addr && addr >= mmap_min_addr && (!vma || addr + len <= vma->vm_start)) return addr; } info.flags = 0; info.length = len; info.low_limit = mm->mmap_base; info.high_limit = TASK_SIZE; info.align_mask = 0; return vm_unmapped_area(&info); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas Stack guard page is a useful feature to reduce a risk of stack smashing into a different mapping. We have been using a single page gap which is sufficient to prevent having stack adjacent to a different mapping. But this seems to be insufficient in the light of the stack usage in userspace. E.g. glibc uses as large as 64kB alloca() in many commonly used functions. Others use constructs liks gid_t buffer[NGROUPS_MAX] which is 256kB or stack strings with MAX_ARG_STRLEN. This will become especially dangerous for suid binaries and the default no limit for the stack size limit because those applications can be tricked to consume a large portion of the stack and a single glibc call could jump over the guard page. These attacks are not theoretical, unfortunatelly. Make those attacks less probable by increasing the stack guard gap to 1MB (on systems with 4k pages; but make it depend on the page size because systems with larger base pages might cap stack allocations in the PAGE_SIZE units) which should cover larger alloca() and VLA stack allocations. It is obviously not a full fix because the problem is somehow inherent, but it should reduce attack space a lot. One could argue that the gap size should be configurable from userspace, but that can be done later when somebody finds that the new 1MB is wrong for some special case applications. For now, add a kernel command line option (stack_guard_gap) to specify the stack gap size (in page units). Implementation wise, first delete all the old code for stack guard page: because although we could get away with accounting one extra page in a stack vma, accounting a larger gap can break userspace - case in point, a program run with "ulimit -S -v 20000" failed when the 1MB gap was counted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK and strict non-overcommit mode. Instead of keeping gap inside the stack vma, maintain the stack guard gap as a gap between vmas: using vm_start_gap() in place of vm_start (or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few places which need to respect the gap - mainly arch_get_unmapped_area(), and and the vma tree's subtree_gap support for that. Original-patch-by: Oleg Nesterov <oleg@redhat.com> Original-patch-by: Michal Hocko <mhocko@suse.com> Signed-off-by: Hugh Dickins <hughd@google.com> Acked-by: Michal Hocko <mhocko@suse.com> Tested-by: Helge Deller <deller@gmx.de> # parisc 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: radix__arch_get_unmapped_area(struct file *filp, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags) { struct mm_struct *mm = current->mm; struct vm_area_struct *vma; struct vm_unmapped_area_info info; if (unlikely(addr > mm->context.addr_limit && mm->context.addr_limit != TASK_SIZE)) mm->context.addr_limit = TASK_SIZE; if (len > mm->task_size - mmap_min_addr) return -ENOMEM; if (flags & MAP_FIXED) return addr; if (addr) { addr = PAGE_ALIGN(addr); vma = find_vma(mm, addr); if (mm->task_size - len >= addr && addr >= mmap_min_addr && (!vma || addr + len <= vma->vm_start)) return addr; } info.flags = 0; info.length = len; info.low_limit = mm->mmap_base; info.align_mask = 0; if (unlikely(addr > DEFAULT_MAP_WINDOW)) info.high_limit = mm->context.addr_limit; else info.high_limit = DEFAULT_MAP_WINDOW; return vm_unmapped_area(&info); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas Stack guard page is a useful feature to reduce a risk of stack smashing into a different mapping. We have been using a single page gap which is sufficient to prevent having stack adjacent to a different mapping. But this seems to be insufficient in the light of the stack usage in userspace. E.g. glibc uses as large as 64kB alloca() in many commonly used functions. Others use constructs liks gid_t buffer[NGROUPS_MAX] which is 256kB or stack strings with MAX_ARG_STRLEN. This will become especially dangerous for suid binaries and the default no limit for the stack size limit because those applications can be tricked to consume a large portion of the stack and a single glibc call could jump over the guard page. These attacks are not theoretical, unfortunatelly. Make those attacks less probable by increasing the stack guard gap to 1MB (on systems with 4k pages; but make it depend on the page size because systems with larger base pages might cap stack allocations in the PAGE_SIZE units) which should cover larger alloca() and VLA stack allocations. It is obviously not a full fix because the problem is somehow inherent, but it should reduce attack space a lot. One could argue that the gap size should be configurable from userspace, but that can be done later when somebody finds that the new 1MB is wrong for some special case applications. For now, add a kernel command line option (stack_guard_gap) to specify the stack gap size (in page units). Implementation wise, first delete all the old code for stack guard page: because although we could get away with accounting one extra page in a stack vma, accounting a larger gap can break userspace - case in point, a program run with "ulimit -S -v 20000" failed when the 1MB gap was counted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK and strict non-overcommit mode. Instead of keeping gap inside the stack vma, maintain the stack guard gap as a gap between vmas: using vm_start_gap() in place of vm_start (or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few places which need to respect the gap - mainly arch_get_unmapped_area(), and and the vma tree's subtree_gap support for that. Original-patch-by: Oleg Nesterov <oleg@redhat.com> Original-patch-by: Michal Hocko <mhocko@suse.com> Signed-off-by: Hugh Dickins <hughd@google.com> Acked-by: Michal Hocko <mhocko@suse.com> Tested-by: Helge Deller <deller@gmx.de> # parisc 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: arch_get_unmapped_area_topdown(struct file *filp, const unsigned long addr0, const unsigned long len, const unsigned long pgoff, const unsigned long flags) { struct vm_area_struct *vma; struct mm_struct *mm = current->mm; unsigned long addr = addr0; struct vm_unmapped_area_info info; /* requested length too big for entire address space */ if (len > TASK_SIZE - mmap_min_addr) return -ENOMEM; if (flags & MAP_FIXED) return addr; /* requesting a specific address */ if (addr) { addr = PAGE_ALIGN(addr); vma = find_vma(mm, addr); if (TASK_SIZE - len >= addr && addr >= mmap_min_addr && (!vma || addr + len <= vma->vm_start)) return addr; } info.flags = VM_UNMAPPED_AREA_TOPDOWN; info.length = len; info.low_limit = max(PAGE_SIZE, mmap_min_addr); info.high_limit = mm->mmap_base; info.align_mask = 0; addr = vm_unmapped_area(&info); /* * A failed mmap() very likely causes application failure, * so fall back to the bottom-up function here. This scenario * can happen with large stack limits and large mmap() * allocations. */ if (offset_in_page(addr)) { VM_BUG_ON(addr != -ENOMEM); info.flags = 0; info.low_limit = TASK_UNMAPPED_BASE; info.high_limit = TASK_SIZE; addr = vm_unmapped_area(&info); } return addr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas Stack guard page is a useful feature to reduce a risk of stack smashing into a different mapping. We have been using a single page gap which is sufficient to prevent having stack adjacent to a different mapping. But this seems to be insufficient in the light of the stack usage in userspace. E.g. glibc uses as large as 64kB alloca() in many commonly used functions. Others use constructs liks gid_t buffer[NGROUPS_MAX] which is 256kB or stack strings with MAX_ARG_STRLEN. This will become especially dangerous for suid binaries and the default no limit for the stack size limit because those applications can be tricked to consume a large portion of the stack and a single glibc call could jump over the guard page. These attacks are not theoretical, unfortunatelly. Make those attacks less probable by increasing the stack guard gap to 1MB (on systems with 4k pages; but make it depend on the page size because systems with larger base pages might cap stack allocations in the PAGE_SIZE units) which should cover larger alloca() and VLA stack allocations. It is obviously not a full fix because the problem is somehow inherent, but it should reduce attack space a lot. One could argue that the gap size should be configurable from userspace, but that can be done later when somebody finds that the new 1MB is wrong for some special case applications. For now, add a kernel command line option (stack_guard_gap) to specify the stack gap size (in page units). Implementation wise, first delete all the old code for stack guard page: because although we could get away with accounting one extra page in a stack vma, accounting a larger gap can break userspace - case in point, a program run with "ulimit -S -v 20000" failed when the 1MB gap was counted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK and strict non-overcommit mode. Instead of keeping gap inside the stack vma, maintain the stack guard gap as a gap between vmas: using vm_start_gap() in place of vm_start (or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few places which need to respect the gap - mainly arch_get_unmapped_area(), and and the vma tree's subtree_gap support for that. Original-patch-by: Oleg Nesterov <oleg@redhat.com> Original-patch-by: Michal Hocko <mhocko@suse.com> Signed-off-by: Hugh Dickins <hughd@google.com> Acked-by: Michal Hocko <mhocko@suse.com> Tested-by: Helge Deller <deller@gmx.de> # parisc Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int expand_downwards(struct vm_area_struct *vma, unsigned long address) { struct mm_struct *mm = vma->vm_mm; int error; address &= PAGE_MASK; error = security_mmap_addr(address); if (error) return error; /* We must make sure the anon_vma is allocated. */ if (unlikely(anon_vma_prepare(vma))) return -ENOMEM; /* * vma->vm_start/vm_end cannot change under us because the caller * is required to hold the mmap_sem in read mode. We need the * anon_vma lock to serialize against concurrent expand_stacks. */ anon_vma_lock_write(vma->anon_vma); /* Somebody else might have raced and expanded it already */ if (address < vma->vm_start) { unsigned long size, grow; size = vma->vm_end - address; grow = (vma->vm_start - address) >> PAGE_SHIFT; error = -ENOMEM; if (grow <= vma->vm_pgoff) { error = acct_stack_growth(vma, size, grow); if (!error) { /* * vma_gap_update() doesn't support concurrent * updates, but we only hold a shared mmap_sem * lock here, so we need to protect against * concurrent vma expansions. * anon_vma_lock_write() doesn't help here, as * we don't guarantee that all growable vmas * in a mm share the same root anon vma. * So, we reuse mm->page_table_lock to guard * against concurrent vma expansions. */ spin_lock(&mm->page_table_lock); if (vma->vm_flags & VM_LOCKED) mm->locked_vm += grow; vm_stat_account(mm, vma->vm_flags, grow); anon_vma_interval_tree_pre_update_vma(vma); vma->vm_start = address; vma->vm_pgoff -= grow; anon_vma_interval_tree_post_update_vma(vma); vma_gap_update(vma); spin_unlock(&mm->page_table_lock); perf_event_mmap(vma); } } } anon_vma_unlock_write(vma->anon_vma); khugepaged_enter_vma_merge(vma, vma->vm_flags); validate_mm(mm); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'mm: larger stack guard gap, between vmas Stack guard page is a useful feature to reduce a risk of stack smashing into a different mapping. We have been using a single page gap which is sufficient to prevent having stack adjacent to a different mapping. But this seems to be insufficient in the light of the stack usage in userspace. E.g. glibc uses as large as 64kB alloca() in many commonly used functions. Others use constructs liks gid_t buffer[NGROUPS_MAX] which is 256kB or stack strings with MAX_ARG_STRLEN. This will become especially dangerous for suid binaries and the default no limit for the stack size limit because those applications can be tricked to consume a large portion of the stack and a single glibc call could jump over the guard page. These attacks are not theoretical, unfortunatelly. Make those attacks less probable by increasing the stack guard gap to 1MB (on systems with 4k pages; but make it depend on the page size because systems with larger base pages might cap stack allocations in the PAGE_SIZE units) which should cover larger alloca() and VLA stack allocations. It is obviously not a full fix because the problem is somehow inherent, but it should reduce attack space a lot. One could argue that the gap size should be configurable from userspace, but that can be done later when somebody finds that the new 1MB is wrong for some special case applications. For now, add a kernel command line option (stack_guard_gap) to specify the stack gap size (in page units). Implementation wise, first delete all the old code for stack guard page: because although we could get away with accounting one extra page in a stack vma, accounting a larger gap can break userspace - case in point, a program run with "ulimit -S -v 20000" failed when the 1MB gap was counted for RLIMIT_AS; similar problems could come with RLIMIT_MLOCK and strict non-overcommit mode. Instead of keeping gap inside the stack vma, maintain the stack guard gap as a gap between vmas: using vm_start_gap() in place of vm_start (or vm_end_gap() in place of vm_end if VM_GROWSUP) in just those few places which need to respect the gap - mainly arch_get_unmapped_area(), and and the vma tree's subtree_gap support for that. Original-patch-by: Oleg Nesterov <oleg@redhat.com> Original-patch-by: Michal Hocko <mhocko@suse.com> Signed-off-by: Hugh Dickins <hughd@google.com> Acked-by: Michal Hocko <mhocko@suse.com> Tested-by: Helge Deller <deller@gmx.de> # parisc 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 Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MagickPathExtent], id[MagickPathExtent], keyword[MagickPathExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register ssize_t i; size_t depth, length; ssize_t count; StringInfo *profile; unsigned int signature; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(cache_filename,image->filename,MagickPathExtent); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ profiles=(LinkedListInfo *) NULL; length=MagickPathExtent; options=AcquireString((char *) NULL); signature=GetMagickSignature((const StringInfo *) NULL); image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MagickPathExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MagickPathExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ length=MagickPathExtent; p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MagickPathExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'a': case 'A': { if (LocaleCompare(keyword,"alpha-trait") == 0) { ssize_t alpha_trait; alpha_trait=ParseCommandOption(MagickPixelTraitOptions, MagickFalse,options); if (alpha_trait < 0) break; image->alpha_trait=(PixelTrait) alpha_trait; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->background_color,exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->border_color,exception); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=StringToDouble(options, (char **) NULL); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MagickPathExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"magick-signature") == 0) { signature=(unsigned int) StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"mattecolor") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->matte_color,exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=StringToDouble( options,(char **) NULL); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=StringToDouble(options, (char **) NULL); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'n': case 'N': { if (LocaleCompare(keyword,"number-channels") == 0) { image->number_channels=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"number-meta-channels") == 0) { image->number_meta_channels=StringToUnsignedLong(options); break; } break; } case 'o': case 'O': { if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=BlobToStringInfo((const void *) NULL,(size_t) StringToLong(options)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); (void) SetImageProfile(image,keyword+8,profile,exception); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions, MagickFalse,options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options,exception); break; } default: { (void) SetImageProperty(image,keyword,options,exception); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (signature != GetMagickSignature((const StringInfo *) NULL)) ThrowReaderException(CacheError,"IncompatibleAPI"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MagickPathExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MagickPathExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MagickPathExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; register unsigned char *p; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); count=ReadBlob(image,GetStringInfoLength(profile),p); } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ image->colormap=(PixelInfo *) AcquireQuantumMemory(image->colors+1, sizeof(*image->colormap)); if (image->colormap == (PixelInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=colormap; switch (depth) { default: colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) ThrowReaderException(CacheError,"UnableToPersistPixelCache"); /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-617'], 'message': 'Added check for incorrect number of meta channels report in #492.'</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: uint32_t skip(Protocol_& prot, TType type) { switch (type) { case T_BOOL: { bool boolv; return prot.readBool(boolv); } case T_BYTE: { int8_t bytev; return prot.readByte(bytev); } case T_I16: { int16_t i16; return prot.readI16(i16); } case T_I32: { int32_t i32; return prot.readI32(i32); } case T_I64: { int64_t i64; return prot.readI64(i64); } case T_DOUBLE: { double dub; return prot.readDouble(dub); } case T_STRING: { std::string str; return prot.readBinary(str); } case T_STRUCT: { uint32_t result = 0; std::string name; int16_t fid; TType ftype; result += prot.readStructBegin(name); while (true) { result += prot.readFieldBegin(name, ftype, fid); if (ftype == T_STOP) { break; } result += skip(prot, ftype); result += prot.readFieldEnd(); } result += prot.readStructEnd(); return result; } case T_MAP: { uint32_t result = 0; TType keyType; TType valType; uint32_t i, size; result += prot.readMapBegin(keyType, valType, size); for (i = 0; i < size; i++) { result += skip(prot, keyType); result += skip(prot, valType); } result += prot.readMapEnd(); return result; } case T_SET: { uint32_t result = 0; TType elemType; uint32_t i, size; result += prot.readSetBegin(elemType, size); for (i = 0; i < size; i++) { result += skip(prot, elemType); } result += prot.readSetEnd(); return result; } case T_LIST: { uint32_t result = 0; TType elemType; uint32_t i, size; result += prot.readListBegin(elemType, size); for (i = 0; i < size; i++) { result += skip(prot, elemType); } result += prot.readListEnd(); return result; } case T_STOP: case T_VOID: case T_U64: case T_UTF8: case T_UTF16: break; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'THRIFT-3231 CPP: Limit recursion depth to 64 Client: cpp Patch: Ben Craig <bencraig@apache.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: aiff_read_chanmap (SF_PRIVATE * psf, unsigned dword) { const AIFF_CAF_CHANNEL_MAP * map_info ; unsigned channel_bitmap, channel_decriptions, bytesread ; int layout_tag ; bytesread = psf_binheader_readf (psf, "444", &layout_tag, &channel_bitmap, &channel_decriptions) ; if ((map_info = aiff_caf_of_channel_layout_tag (layout_tag)) == NULL) return 0 ; psf_log_printf (psf, " Tag : %x\n", layout_tag) ; if (map_info) psf_log_printf (psf, " Layout : %s\n", map_info->name) ; if (bytesread < dword) psf_binheader_readf (psf, "j", dword - bytesread) ; if (map_info->channel_map != NULL) { size_t chanmap_size = psf->sf.channels * sizeof (psf->channel_map [0]) ; free (psf->channel_map) ; if ((psf->channel_map = malloc (chanmap_size)) == NULL) return SFE_MALLOC_FAILED ; memcpy (psf->channel_map, map_info->channel_map, chanmap_size) ; } ; return 0 ; } /* aiff_read_chanmap */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/aiff.c: Fix a buffer read overflow Secunia Advisory SA76717. Found by: Laurent Delosieres, Secunia Research at Flexera Software'</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: _gcry_mpi_powm (gcry_mpi_t res, gcry_mpi_t base, gcry_mpi_t expo, gcry_mpi_t mod) { /* Pointer to the limbs of the arguments, their size and signs. */ mpi_ptr_t rp, ep, mp, bp; mpi_size_t esize, msize, bsize, rsize; int msign, bsign, rsign; /* Flags telling the secure allocation status of the arguments. */ int esec, msec, bsec; /* Size of the result including space for temporary values. */ mpi_size_t size; /* Helper. */ int mod_shift_cnt; int negative_result; mpi_ptr_t mp_marker = NULL; mpi_ptr_t bp_marker = NULL; mpi_ptr_t ep_marker = NULL; mpi_ptr_t xp_marker = NULL; unsigned int mp_nlimbs = 0; unsigned int bp_nlimbs = 0; unsigned int ep_nlimbs = 0; unsigned int xp_nlimbs = 0; mpi_ptr_t tspace = NULL; mpi_size_t tsize = 0; esize = expo->nlimbs; msize = mod->nlimbs; size = 2 * msize; msign = mod->sign; esec = mpi_is_secure(expo); msec = mpi_is_secure(mod); bsec = mpi_is_secure(base); rp = res->d; ep = expo->d; MPN_NORMALIZE(ep, esize); if (!msize) _gcry_divide_by_zero(); if (!esize) { /* Exponent is zero, result is 1 mod MOD, i.e., 1 or 0 depending on if MOD equals 1. */ res->nlimbs = (msize == 1 && mod->d[0] == 1) ? 0 : 1; if (res->nlimbs) { RESIZE_IF_NEEDED (res, 1); rp = res->d; rp[0] = 1; } res->sign = 0; goto leave; } /* Normalize MOD (i.e. make its most significant bit set) as required by mpn_divrem. This will make the intermediate values in the calculation slightly larger, but the correct result is obtained after a final reduction using the original MOD value. */ mp_nlimbs = msec? msize:0; mp = mp_marker = mpi_alloc_limb_space(msize, msec); count_leading_zeros (mod_shift_cnt, mod->d[msize-1]); if (mod_shift_cnt) _gcry_mpih_lshift (mp, mod->d, msize, mod_shift_cnt); else MPN_COPY( mp, mod->d, msize ); bsize = base->nlimbs; bsign = base->sign; if (bsize > msize) { /* The base is larger than the module. Reduce it. Allocate (BSIZE + 1) with space for remainder and quotient. (The quotient is (bsize - msize + 1) limbs.) */ bp_nlimbs = bsec ? (bsize + 1):0; bp = bp_marker = mpi_alloc_limb_space( bsize + 1, bsec ); MPN_COPY ( bp, base->d, bsize ); /* We don't care about the quotient, store it above the * remainder, at BP + MSIZE. */ _gcry_mpih_divrem( bp + msize, 0, bp, bsize, mp, msize ); bsize = msize; /* Canonicalize the base, since we are going to multiply with it quite a few times. */ MPN_NORMALIZE( bp, bsize ); } else bp = base->d; if (!bsize) { res->nlimbs = 0; res->sign = 0; goto leave; } /* Make BASE, EXPO and MOD not overlap with RES. */ if ( rp == bp ) { /* RES and BASE are identical. Allocate temp. space for BASE. */ gcry_assert (!bp_marker); bp_nlimbs = bsec? bsize:0; bp = bp_marker = mpi_alloc_limb_space( bsize, bsec ); MPN_COPY(bp, rp, bsize); } if ( rp == ep ) { /* RES and EXPO are identical. Allocate temp. space for EXPO. */ ep_nlimbs = esec? esize:0; ep = ep_marker = mpi_alloc_limb_space( esize, esec ); MPN_COPY(ep, rp, esize); } if ( rp == mp ) { /* RES and MOD are identical. Allocate temporary space for MOD.*/ gcry_assert (!mp_marker); mp_nlimbs = msec?msize:0; mp = mp_marker = mpi_alloc_limb_space( msize, msec ); MPN_COPY(mp, rp, msize); } /* Copy base to the result. */ if (res->alloced < size) { mpi_resize (res, size); rp = res->d; } MPN_COPY ( rp, bp, bsize ); rsize = bsize; rsign = 0; /* Main processing. */ { mpi_size_t i; mpi_ptr_t xp; int c; mpi_limb_t e; mpi_limb_t carry_limb; struct karatsuba_ctx karactx; xp_nlimbs = msec? (2 * (msize + 1)):0; xp = xp_marker = mpi_alloc_limb_space( 2 * (msize + 1), msec ); memset( &karactx, 0, sizeof karactx ); negative_result = (ep[0] & 1) && bsign; i = esize - 1; e = ep[i]; count_leading_zeros (c, e); e = (e << c) << 1; /* Shift the expo bits to the left, lose msb. */ c = BITS_PER_MPI_LIMB - 1 - c; /* Main loop. Make the result be pointed to alternately by XP and RP. This helps us avoid block copying, which would otherwise be necessary with the overlap restrictions of _gcry_mpih_divmod. With 50% probability the result after this loop will be in the area originally pointed by RP (==RES->d), and with 50% probability in the area originally pointed to by XP. */ for (;;) { while (c) { mpi_ptr_t tp; mpi_size_t xsize; /*mpih_mul_n(xp, rp, rp, rsize);*/ if ( rsize < KARATSUBA_THRESHOLD ) _gcry_mpih_sqr_n_basecase( xp, rp, rsize ); else { if ( !tspace ) { tsize = 2 * rsize; tspace = mpi_alloc_limb_space( tsize, 0 ); } else if ( tsize < (2*rsize) ) { _gcry_mpi_free_limb_space (tspace, 0); tsize = 2 * rsize; tspace = mpi_alloc_limb_space (tsize, 0 ); } _gcry_mpih_sqr_n (xp, rp, rsize, tspace); } xsize = 2 * rsize; if ( xsize > msize ) { _gcry_mpih_divrem(xp + msize, 0, xp, xsize, mp, msize); xsize = msize; } tp = rp; rp = xp; xp = tp; rsize = xsize; /* To mitigate the Yarom/Falkner flush+reload cache * side-channel attack on the RSA secret exponent, we do * the multiplication regardless of the value of the * high-bit of E. But to avoid this performance penalty * we do it only if the exponent has been stored in secure * memory and we can thus assume it is a secret exponent. */ if (esec || (mpi_limb_signed_t)e < 0) { /*mpih_mul( xp, rp, rsize, bp, bsize );*/ if( bsize < KARATSUBA_THRESHOLD ) _gcry_mpih_mul ( xp, rp, rsize, bp, bsize ); else _gcry_mpih_mul_karatsuba_case (xp, rp, rsize, bp, bsize, &karactx); xsize = rsize + bsize; if ( xsize > msize ) { _gcry_mpih_divrem(xp + msize, 0, xp, xsize, mp, msize); xsize = msize; } } if ( (mpi_limb_signed_t)e < 0 ) { tp = rp; rp = xp; xp = tp; rsize = xsize; } e <<= 1; c--; } i--; if ( i < 0 ) break; e = ep[i]; c = BITS_PER_MPI_LIMB; } /* We shifted MOD, the modulo reduction argument, left MOD_SHIFT_CNT steps. Adjust the result by reducing it with the original MOD. Also make sure the result is put in RES->d (where it already might be, see above). */ if ( mod_shift_cnt ) { carry_limb = _gcry_mpih_lshift( res->d, rp, rsize, mod_shift_cnt); rp = res->d; if ( carry_limb ) { rp[rsize] = carry_limb; rsize++; } } else if (res->d != rp) { MPN_COPY (res->d, rp, rsize); rp = res->d; } if ( rsize >= msize ) { _gcry_mpih_divrem(rp + msize, 0, rp, rsize, mp, msize); rsize = msize; } /* Remove any leading zero words from the result. */ if ( mod_shift_cnt ) _gcry_mpih_rshift( rp, rp, rsize, mod_shift_cnt); MPN_NORMALIZE (rp, rsize); _gcry_mpih_release_karatsuba_ctx (&karactx ); } /* Fixup for negative results. */ if ( negative_result && rsize ) { if ( mod_shift_cnt ) _gcry_mpih_rshift( mp, mp, msize, mod_shift_cnt); _gcry_mpih_sub( rp, mp, msize, rp, rsize); rsize = msize; rsign = msign; MPN_NORMALIZE(rp, rsize); } gcry_assert (res->d == rp); res->nlimbs = rsize; res->sign = rsign; leave: if (mp_marker) _gcry_mpi_free_limb_space( mp_marker, mp_nlimbs ); if (bp_marker) _gcry_mpi_free_limb_space( bp_marker, bp_nlimbs ); if (ep_marker) _gcry_mpi_free_limb_space( ep_marker, ep_nlimbs ); if (xp_marker) _gcry_mpi_free_limb_space( xp_marker, xp_nlimbs ); if (tspace) _gcry_mpi_free_limb_space( tspace, 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Same computation for square and multiply. * mpi/mpi-pow.c (_gcry_mpi_powm): Compare msize for max_u_size. Move the assignment to base_u into the loop. Copy content refered by RP to BASE_U except the last of the loop. -- Signed-off-by: NIIBE Yutaka <gniibe@fsij.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: fetch_token_in_cc(OnigToken* tok, UChar** src, UChar* end, ScanEnv* env) { int num; OnigCodePoint c, c2; OnigSyntaxType* syn = env->syntax; OnigEncoding enc = env->enc; UChar* prev; UChar* p = *src; PFETCH_READY; if (PEND) { tok->type = TK_EOT; return tok->type; } PFETCH(c); tok->type = TK_CHAR; tok->base = 0; tok->u.c = c; tok->escaped = 0; if (c == ']') { tok->type = TK_CC_CLOSE; } else if (c == '-') { tok->type = TK_CC_RANGE; } else if (c == MC_ESC(syn)) { if (! IS_SYNTAX_BV(syn, ONIG_SYN_BACKSLASH_ESCAPE_IN_CC)) goto end; if (PEND) return ONIGERR_END_PATTERN_AT_ESCAPE; PFETCH(c); tok->escaped = 1; tok->u.c = c; switch (c) { case 'w': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 0; break; case 'W': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_WORD; tok->u.prop.not = 1; break; case 'd': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 0; break; case 'D': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_DIGIT; tok->u.prop.not = 1; break; case 's': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 0; break; case 'S': tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_SPACE; tok->u.prop.not = 1; break; case 'h': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 0; break; case 'H': if (! IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_H_XDIGIT)) break; tok->type = TK_CHAR_TYPE; tok->u.prop.ctype = ONIGENC_CTYPE_XDIGIT; tok->u.prop.not = 1; break; case 'p': case 'P': if (PEND) break; c2 = PPEEK; if (c2 == '{' && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CHAR_PROPERTY)) { PINC; tok->type = TK_CHAR_PROPERTY; tok->u.prop.not = (c == 'P' ? 1 : 0); if (!PEND && IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_P_BRACE_CIRCUMFLEX_NOT)) { PFETCH(c2); if (c2 == '^') { tok->u.prop.not = (tok->u.prop.not == 0 ? 1 : 0); } else PUNFETCH; } } break; case 'x': if (PEND) break; prev = p; if (PPEEK_IS('{') && IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_BRACE_HEX8)) { PINC; num = scan_unsigned_hexadecimal_number(&p, end, 8, enc); if (num < 0) return ONIGERR_TOO_BIG_WIDE_CHAR_VALUE; if (!PEND) { c2 = PPEEK; if (ONIGENC_IS_CODE_XDIGIT(enc, c2)) return ONIGERR_TOO_LONG_WIDE_CHAR_VALUE; } if (p > prev + enclen(enc, prev) && !PEND && (PPEEK_IS('}'))) { PINC; tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } else { /* can't read nothing or invalid format */ p = prev; } } else if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_X_HEX2)) { num = scan_unsigned_hexadecimal_number(&p, end, 2, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 16; tok->u.c = num; } break; case 'u': if (PEND) break; prev = p; if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_ESC_U_HEX4)) { num = scan_unsigned_hexadecimal_number(&p, end, 4, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_CODE_POINT; tok->base = 16; tok->u.code = (OnigCodePoint )num; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_ESC_OCTAL3)) { PUNFETCH; prev = p; num = scan_unsigned_octal_number(&p, end, 3, enc); if (num < 0) return ONIGERR_TOO_BIG_NUMBER; if (p == prev) { /* can't read nothing. */ num = 0; /* but, it's not error */ } tok->type = TK_RAW_BYTE; tok->base = 8; tok->u.c = num; } break; default: PUNFETCH; num = fetch_escaped_value(&p, end, env, &c2); if (num < 0) return num; if (tok->u.c != c2) { tok->u.code = c2; tok->type = TK_CODE_POINT; } break; } } else if (c == '[') { if (IS_SYNTAX_OP(syn, ONIG_SYN_OP_POSIX_BRACKET) && (PPEEK_IS(':'))) { OnigCodePoint send[] = { (OnigCodePoint )':', (OnigCodePoint )']' }; tok->backp = p; /* point at '[' is read */ PINC; if (str_exist_check_with_esc(send, 2, p, end, (OnigCodePoint )']', enc, syn)) { tok->type = TK_POSIX_BRACKET_OPEN; } else { PUNFETCH; goto cc_in_cc; } } else { cc_in_cc: if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP)) { tok->type = TK_CC_CC_OPEN; } else { CC_ESC_WARN(env, (UChar* )"["); } } } else if (c == '&') { if (IS_SYNTAX_OP2(syn, ONIG_SYN_OP2_CCLASS_SET_OP) && !PEND && (PPEEK_IS('&'))) { PINC; tok->type = TK_CC_AND; } } end: *src = p; return tok->type; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'fix #55 : Byte value expressed in octal must be smaller than 256'</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 vfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, struct inode **delegated_inode, unsigned int flags) { int error; bool is_dir = d_is_dir(old_dentry); const unsigned char *old_name; struct inode *source = old_dentry->d_inode; struct inode *target = new_dentry->d_inode; bool new_is_dir = false; unsigned max_links = new_dir->i_sb->s_max_links; if (source == target) return 0; error = may_delete(old_dir, old_dentry, is_dir); if (error) return error; if (!target) { error = may_create(new_dir, new_dentry); } else { new_is_dir = d_is_dir(new_dentry); if (!(flags & RENAME_EXCHANGE)) error = may_delete(new_dir, new_dentry, is_dir); else error = may_delete(new_dir, new_dentry, new_is_dir); } if (error) return error; if (!old_dir->i_op->rename) return -EPERM; /* * If we are going to change the parent - check write permissions, * we'll need to flip '..'. */ if (new_dir != old_dir) { if (is_dir) { error = inode_permission(source, MAY_WRITE); if (error) return error; } if ((flags & RENAME_EXCHANGE) && new_is_dir) { error = inode_permission(target, MAY_WRITE); if (error) return error; } } error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry, flags); if (error) return error; old_name = fsnotify_oldname_init(old_dentry->d_name.name); dget(new_dentry); if (!is_dir || (flags & RENAME_EXCHANGE)) lock_two_nondirectories(source, target); else if (target) inode_lock(target); error = -EBUSY; if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry)) goto out; if (max_links && new_dir != old_dir) { error = -EMLINK; if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links) goto out; if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir && old_dir->i_nlink >= max_links) goto out; } if (is_dir && !(flags & RENAME_EXCHANGE) && target) shrink_dcache_parent(new_dentry); if (!is_dir) { error = try_break_deleg(source, delegated_inode); if (error) goto out; } if (target && !new_is_dir) { error = try_break_deleg(target, delegated_inode); if (error) goto out; } error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry, flags); if (error) goto out; if (!(flags & RENAME_EXCHANGE) && target) { if (is_dir) target->i_flags |= S_DEAD; dont_mount(new_dentry); detach_mounts(new_dentry); } if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) { if (!(flags & RENAME_EXCHANGE)) d_move(old_dentry, new_dentry); else d_exchange(old_dentry, new_dentry); } out: if (!is_dir || (flags & RENAME_EXCHANGE)) unlock_two_nondirectories(source, target); else if (target) inode_unlock(target); dput(new_dentry); if (!error) { fsnotify_move(old_dir, new_dir, old_name, is_dir, !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); if (flags & RENAME_EXCHANGE) { fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, new_is_dir, NULL, new_dentry); } } fsnotify_oldname_free(old_name); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-399'], 'message': 'dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. 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: accept_ice_connection (GIOChannel *source, GIOCondition condition, GsmIceConnectionData *data) { IceListenObj listener; IceConn ice_conn; IceAcceptStatus status; GsmClient *client; GsmXsmpServer *server; listener = data->listener; server = data->server; g_debug ("GsmXsmpServer: accept_ice_connection()"); ice_conn = IceAcceptConnection (listener, &status); if (status != IceAcceptSuccess) { g_debug ("GsmXsmpServer: IceAcceptConnection returned %d", status); return TRUE; } client = gsm_xsmp_client_new (ice_conn); ice_conn->context = client; gsm_store_add (server->priv->client_store, gsm_client_peek_id (client), G_OBJECT (client)); /* the store will own the ref */ g_object_unref (client); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-835'], 'message': '[gsm] Delay the creation of the GsmXSMPClient until it really exists We used to create the GsmXSMPClient before the XSMP connection is really accepted. This can lead to some issues, though. An example is: https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting: "What is happening is that a new client (probably metacity in your case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION phase, which causes a new GsmXSMPClient to be added to the client store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client has had a chance to establish a xsmp connection, which means that client->priv->conn will not be initialized at the point that xsmp_stop is called on the new unregistered client." The fix is to create the GsmXSMPClient object when there's a real XSMP connection. This implies moving the timeout that makes sure we don't have an empty client to the XSMP server. https://bugzilla.gnome.org/show_bug.cgi?id=598211'</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 __init mp_override_legacy_irq(u8 bus_irq, u8 polarity, u8 trigger, u32 gsi) { int ioapic; int pin; struct mpc_intsrc mp_irq; /* * Convert 'gsi' to 'ioapic.pin'. */ ioapic = mp_find_ioapic(gsi); if (ioapic < 0) return; pin = mp_find_ioapic_pin(ioapic, gsi); /* * TBD: This check is for faulty timer entries, where the override * erroneously sets the trigger to level, resulting in a HUGE * increase of timer interrupts! */ if ((bus_irq == 0) && (trigger == 3)) trigger = 1; mp_irq.type = MP_INTSRC; mp_irq.irqtype = mp_INT; mp_irq.irqflag = (trigger << 2) | polarity; mp_irq.srcbus = MP_ISA_BUS; mp_irq.srcbusirq = bus_irq; /* IRQ */ mp_irq.dstapic = mpc_ioapic_id(ioapic); /* APIC ID */ mp_irq.dstirq = pin; /* INTIN# */ mp_save_irq(&mp_irq); /* * Reset default identity mapping if gsi is also an legacy IRQ, * otherwise there will be more than one entry with the same GSI * and acpi_isa_irq_to_gsi() may give wrong result. */ if (gsi < nr_legacy_irqs() && isa_irq_to_gsi[gsi] == gsi) isa_irq_to_gsi[gsi] = ACPI_INVALID_GSI; isa_irq_to_gsi[bus_irq] = gsi; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'x86/acpi: Prevent out of bound access caused by broken ACPI tables The bus_irq argument of mp_override_legacy_irq() is used as the index into the isa_irq_to_gsi[] array. The bus_irq argument originates from ACPI_MADT_TYPE_IO_APIC and ACPI_MADT_TYPE_INTERRUPT items in the ACPI tables, but is nowhere sanity checked. That allows broken or malicious ACPI tables to overwrite memory, which might cause malfunction, panic or arbitrary code execution. Add a sanity check and emit a warning when that triggers. [ tglx: Added warning and rewrote changelog ] Signed-off-by: Seunghun Han <kkamagui@gmail.com> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Cc: security@kernel.org Cc: "Rafael J. Wysocki" <rjw@rjwysocki.net> Cc: stable@vger.kernel.org Signed-off-by: Ingo Molnar <mingo@kernel.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 QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client, uint32_t length) { QIOChannel *ioc; QIOChannelTLS *tioc; struct NBDTLSHandshakeData data = { 0 }; TRACE("Setting up TLS"); ioc = client->ioc; if (length) { if (nbd_negotiate_drop_sync(ioc, length) < 0) { return NULL; } nbd_negotiate_send_rep_err(ioc, NBD_REP_ERR_INVALID, NBD_OPT_STARTTLS, "OPT_STARTTLS should not have length"); return NULL; } if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_STARTTLS) < 0) { return NULL; } tioc = qio_channel_tls_new_server(ioc, client->tlscreds, client->tlsaclname, NULL); if (!tioc) { return NULL; } qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls"); TRACE("Starting TLS handshake"); data.loop = g_main_loop_new(g_main_context_default(), FALSE); qio_channel_tls_handshake(tioc, nbd_tls_handshake, &data, NULL); if (!data.complete) { g_main_loop_run(data.loop); } g_main_loop_unref(data.loop); if (data.error) { object_unref(OBJECT(tioc)); error_free(data.error); return NULL; } return QIO_CHANNEL(tioc); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'nbd/server: get rid of nbd_negotiate_read and friends Functions nbd_negotiate_{read,write,drop_sync} were introduced in 1a6245a5b, when nbd_rwv (was nbd_wr_sync) was working through qemu_co_sendv_recvv (the path is nbd_wr_sync -> qemu_co_{recv/send} -> qemu_co_send_recv -> qemu_co_sendv_recvv), which just yields, without setting any handlers. But starting from ff82911cd nbd_rwv (was nbd_wr_syncv) works through qio_channel_yield() which sets handlers, so watchers are redundant in nbd_negotiate_{read,write,drop_sync}, then, let's just use nbd_{read,write,drop} functions. Functions nbd_{read,write,drop} has errp parameter, which is unused in this patch. This will be fixed later. Signed-off-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com> Reviewed-by: Eric Blake <eblake@redhat.com> Message-Id: <20170602150150.258222-4-vsementsov@virtuozzo.com> Signed-off-by: Paolo Bonzini <pbonzini@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 Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 #define ThrowRLEException(exception,message) \ { \ if (colormap != (unsigned char *) NULL) \ colormap=(unsigned char *) RelinquishMagickMemory(colormap); \ if (pixel_info != (MemoryInfo *) NULL) \ pixel_info=RelinquishVirtualMemory(pixel_info); \ ThrowReaderException((exception),(message)); \ } char magick[12]; Image *image; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, pixel_info_length; ssize_t count, offset, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ colormap=(unsigned char *) NULL; pixel_info=(MemoryInfo *) NULL; count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=(ssize_t) ReadBlobLSBShort(image); image->page.y=(ssize_t) ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 22) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) { *p++=(unsigned char) ScaleQuantumToChar(ScaleShortToQuantum( ReadBlobLSBShort(image))); if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if (EOFBlob(image) != MagickFalse) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate RLE pixels. */ if (image->alpha_trait != UndefinedPixelTrait) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* MagickMax(number_planes_filled,4)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows* MagickMax(number_planes_filled,4); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,pixel_info_length); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->alpha_trait == UndefinedPixelTrait) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane); operand++; if ((offset < 0) || ((offset+operand*number_planes) > (ssize_t) pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); if (opcode & 0x40) { operand=ReadBlobLSBSignedShort(image); if (operand == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); offset=(ssize_t) (((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane); operand++; if ((offset < 0) || ((offset+operand*number_planes) > (ssize_t) pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); if (opcode == EOF) ThrowRLEException(CorruptImageError,"UnexpectedEndOfFile"); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { ValidateColormapValue(image,(ssize_t) (*p & mask),&index,exception); *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { ValidateColormapValue(image,(ssize_t) (x*map_length+ (*p & mask)),&index,exception); *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->alpha_trait == UndefinedPixelTrait) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,(Quantum) *p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) index].red),q); ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) index].green),q); ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) index].blue),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-834'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/518'</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 Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; register Quantum *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info,exception); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ quantum_info=(QuantumInfo *) NULL; clone_info=(ImageInfo *) NULL; if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) { MATLAB_KO: clone_info=DestroyImageInfo(clone_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image)) goto MATLAB_KO; filepos += MATLAB_HDR.ObjectSize + 4 + 4; clone_info=CloneImageInfo(image_info); image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ (void) ReadBlobXXXLong(image2); if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); if (Frames == 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; if((unsigned long)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { image->type=GrayscaleType; SetImageColorspace(image,GRAYColorspace,exception); } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(BImgBuff,0,ldblk*sizeof(double)); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (Quantum *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(image,q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, exception); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, exception); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if ((image2!=NULL) && (image2!=image)) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } } RelinquishMagickMemory(BImgBuff); if (quantum_info != (QuantumInfo *) NULL) quantum_info=DestroyQuantumInfo(quantum_info); END_OF_READING: if (clone_info) clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/587'</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: xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font) { int code = 0; font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, "xps_font type42"); if (!font->font) return gs_throw(gs_error_VMerror, "out of memory"); /* no shortage of things to initialize */ { gs_font_type42 *p42 = (gs_font_type42*) font->font; /* Common to all fonts: */ p42->next = 0; p42->prev = 0; p42->memory = ctx->memory; p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */ p42->base = font->font; /* NB also set by gs_definefont later */ p42->is_resource = false; gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory)); p42->id = gs_next_ids(ctx->memory, 1); p42->client_data = font; /* that's us */ /* this is overwritten in grid_fit() */ gs_make_identity(&p42->FontMatrix); gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */ p42->FontType = ft_TrueType; p42->BitmapWidths = false; p42->ExactSize = fbit_use_outlines; p42->InBetweenSize = fbit_use_outlines; p42->TransformedChar = fbit_use_outlines; p42->WMode = 0; p42->PaintType = 0; p42->StrokeWidth = 0; p42->is_cached = 0; p42->procs.define_font = gs_no_define_font; p42->procs.make_font = gs_no_make_font; p42->procs.font_info = gs_type42_font_info; p42->procs.same_font = gs_default_same_font; p42->procs.encode_char = xps_true_callback_encode_char; p42->procs.decode_glyph = xps_true_callback_decode_glyph; p42->procs.enumerate_glyph = gs_type42_enumerate_glyph; p42->procs.glyph_info = gs_type42_glyph_info; p42->procs.glyph_outline = gs_type42_glyph_outline; p42->procs.glyph_name = xps_true_callback_glyph_name; p42->procs.init_fstack = gs_default_init_fstack; p42->procs.next_char_glyph = gs_default_next_char_glyph; p42->procs.build_char = xps_true_callback_build_char; memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars)); xps_load_sfnt_name(font, (char*)p42->font_name.chars); p42->font_name.size = strlen((char*)p42->font_name.chars); memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars)); strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars); p42->key_name.size = strlen((char*)p42->key_name.chars); /* Base font specific: */ p42->FontBBox.p.x = 0; p42->FontBBox.p.y = 0; p42->FontBBox.q.x = 0; p42->FontBBox.q.y = 0; uid_set_UniqueID(&p42->UID, p42->id); p42->encoding_index = ENCODING_INDEX_UNKNOWN; p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1; p42->FAPI = 0; p42->FAPI_font_data = 0; /* Type 42 specific: */ p42->data.string_proc = xps_true_callback_string_proc; p42->data.proc_data = font; gs_type42_font_init(p42, font->subfontid); p42->data.get_glyph_index = xps_true_get_glyph_index; } if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) { return(code); } code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length); return code; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Bug 698044: restrict font name length to the buffer size.'</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: i_alloc_struct_array_immovable(gs_memory_t * mem, uint num_elements, gs_memory_type_ptr_t pstype, client_name_t cname) { gs_ref_memory_t * const imem = (gs_ref_memory_t *)mem; obj_header_t *obj; #ifdef MEMENTO if (Memento_failThisEvent()) return NULL; #endif ALLOC_CHECK_SIZE(mem,pstype); obj = alloc_obj(imem, (ulong) num_elements * pstype->ssize, pstype, ALLOC_IMMOVABLE | ALLOC_DIRECT, cname); if_debug7m('A', mem, "[a%d|+<.]%s %s*(%lu=%u*%u) = 0x%lx\n", alloc_trace_space(imem), client_name_string(cname), struct_type_name_string(pstype), (ulong) num_elements * pstype->ssize, num_elements, pstype->ssize, (ulong) obj); return (char *)obj; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Bug 697985: bounds check the array allocations methods The clump allocator has four allocation functions that use 'number of elements' and 'size of elements' parameters (rather than a simple 'number of bytes'). Those need specific bounds checking.'</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 send(node_t *node, node_t *child, byte *fout) { if (node->parent) { send(node->parent, node, fout); } if (child) { if (node->right == child) { add_bit(1, fout); } else { add_bit(0, fout); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits Prevent reading past end of message in MSG_ReadBits. If read past end of msg->data buffer (16348 bytes) the engine could SEGFAULT. Make MSG_WriteBits use an exact buffer overflow check instead of possibly failing with a few bytes left.'</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 timerfd_setup_cancel(struct timerfd_ctx *ctx, int flags) { if ((ctx->clockid == CLOCK_REALTIME || ctx->clockid == CLOCK_REALTIME_ALARM) && (flags & TFD_TIMER_ABSTIME) && (flags & TFD_TIMER_CANCEL_ON_SET)) { if (!ctx->might_cancel) { ctx->might_cancel = true; spin_lock(&cancel_lock); list_add_rcu(&ctx->clist, &cancel_list); spin_unlock(&cancel_lock); } } else if (ctx->might_cancel) { timerfd_remove_cancel(ctx); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'timerfd: Protect the might cancel mechanism proper The handling of the might_cancel queueing is not properly protected, so parallel operations on the file descriptor can race with each other and lead to list corruptions or use after free. Protect the context for these operations with a seperate lock. The wait queue lock cannot be reused for this because that would create a lock inversion scenario vs. the cancel lock. Replacing might_cancel with an atomic (atomic_t or atomic bit) does not help either because it still can race vs. the actual list operation. Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Cc: "linux-fsdevel@vger.kernel.org" Cc: syzkaller <syzkaller@googlegroups.com> Cc: Al Viro <viro@zeniv.linux.org.uk> Cc: linux-fsdevel@vger.kernel.org Link: http://lkml.kernel.org/r/alpine.DEB.2.20.1701311521430.3457@nanos 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: static Image *ReadMIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define BZipMaxExtent(x) ((x)+((x)/100)+600) #define LZMAMaxExtent(x) ((x)+((x)/3)+128) #define ZipMaxExtent(x) ((x)+(((x)+7) >> 3)+(((x)+63) >> 6)+11) #if defined(MAGICKCORE_BZLIB_DELEGATE) bz_stream bzip_info; #endif char id[MagickPathExtent], keyword[MagickPathExtent], *options; const unsigned char *p; double version; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; #if defined(MAGICKCORE_LZMA_DELEGATE) lzma_stream initialize_lzma = LZMA_STREAM_INIT, lzma_info; lzma_allocator allocator; #endif MagickBooleanType status; PixelInfo pixel; MagickStatusType flags; QuantumFormatType quantum_format; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; size_t compress_extent, length, packet_size; ssize_t count; unsigned char *compress_pixels, *pixels; size_t colors; ssize_t y; #if defined(MAGICKCORE_ZLIB_DELEGATE) z_stream zip_info; #endif /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header; header terminates one character beyond a ':'. */ c=ReadBlobByte(image); if (c == EOF) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); version=0.0; (void) version; do { /* Decode image header; header terminates one character beyond a ':'. */ length=MagickPathExtent; options=AcquireString((char *) NULL); quantum_format=UndefinedQuantumFormat; profiles=(LinkedListInfo *) NULL; colors=0; image->depth=8UL; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MagickPathExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MagickPathExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ length=MagickPathExtent; p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while ((isspace((int) ((unsigned char) c)) != 0) && (c != EOF)) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MagickPathExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'a': case 'A': { if (LocaleCompare(keyword,"alpha-trait") == 0) { ssize_t alpha_trait; alpha_trait=ParseCommandOption(MagickPixelTraitOptions, MagickFalse,options); if (alpha_trait < 0) break; image->alpha_trait=(PixelTrait) alpha_trait; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->background_color,exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->border_color,exception); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"gravity") == 0) { ssize_t gravity; gravity=ParseCommandOption(MagickGravityOptions,MagickFalse, options); if (gravity < 0) break; image->gravity=(GravityType) gravity; break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MagickPathExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"matte") == 0) { ssize_t matte; matte=ParseCommandOption(MagickBooleanOptions,MagickFalse, options); if (matte < 0) break; image->alpha_trait=matte == 0 ? UndefinedPixelTrait : BlendPixelTrait; break; } if (LocaleCompare(keyword,"mattecolor") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->matte_color,exception); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'o': case 'O': { if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { StringInfo *profile; if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=BlobToStringInfo((const void *) NULL,(size_t) StringToLong(options)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); (void) SetImageProfile(image,keyword+8,profile,exception); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } if ((LocaleCompare(keyword,"quantum-format") == 0) || (LocaleCompare(keyword,"quantum:format") == 0)) { ssize_t format; format=ParseCommandOption(MagickQuantumFormatOptions, MagickFalse,options); if (format < 0) break; quantum_format=(QuantumFormatType) format; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; image->chromaticity.red_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.red_primary.y= image->chromaticity.red_primary.x; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions, MagickFalse,options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'v': case 'V': { if (LocaleCompare(keyword,"version") == 0) { version=StringToDouble(options,(char **) NULL); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options,exception); break; } default: { (void) SetImageProperty(image,keyword,options,exception); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"ImageMagick") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->colorspace == UndefinedColorspace) || (image->columns == 0) || (image->rows == 0)) { if (image->previous == (Image *) NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); DeleteImageFromList(&image); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"ImproperImageHeader","`%s'",image->filename); break; } if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MagickPathExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MagickPathExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MagickPathExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { register unsigned char *p; p=GetStringInfoDatum(profile); count=ReadBlob(image,GetStringInfoLength(profile),p); (void) count; } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } image->depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ if ((colors*image->depth/8) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); status=AcquireImageColormap(image,colors != 0 ? colors : 256,exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*image->depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); p=colormap; switch (image->depth) { default: ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate image pixels. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (quantum_format != UndefinedQuantumFormat) { status=SetQuantumFormat(image,quantum_info,quantum_format); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } packet_size=(size_t) (quantum_info->depth/8); if (image->storage_class == DirectClass) packet_size=(size_t) (3*quantum_info->depth/8); if (IsGrayColorspace(image->colorspace) != MagickFalse) packet_size=quantum_info->depth/8; if (image->alpha_trait != UndefinedPixelTrait) packet_size+=quantum_info->depth/8; if (image->colorspace == CMYKColorspace) packet_size+=quantum_info->depth/8; if (image->compression == RLECompression) packet_size++; compress_extent=MagickMax(MagickMax(BZipMaxExtent(packet_size* image->columns),LZMAMaxExtent(packet_size*image->columns)), ZipMaxExtent(packet_size*image->columns)); compress_pixels=(unsigned char *) AcquireQuantumMemory(compress_extent, sizeof(*compress_pixels)); if (compress_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Read image pixels. */ quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; } if (IsGrayColorspace(image->colorspace) != MagickFalse) { quantum_type=GrayQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=GrayAlphaQuantum; } if (image->storage_class == PseudoClass) { quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=IndexAlphaQuantum; } status=MagickTrue; GetPixelInfo(image,&pixel); #if defined(MAGICKCORE_BZLIB_DELEGATE) (void) ResetMagickMemory(&bzip_info,0,sizeof(bzip_info)); #endif #if defined(MAGICKCORE_LZMA_DELEGATE) (void) ResetMagickMemory(&allocator,0,sizeof(allocator)); #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) (void) ResetMagickMemory(&zip_info,0,sizeof(zip_info)); #endif switch (image->compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { int code; bzip_info.bzalloc=AcquireBZIPMemory; bzip_info.bzfree=RelinquishBZIPMemory; bzip_info.opaque=(void *) NULL; code=BZ2_bzDecompressInit(&bzip_info,(int) image_info->verbose, MagickFalse); if (code != BZ_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { int code; allocator.alloc=AcquireLZMAMemory; allocator.free=RelinquishLZMAMemory; lzma_info=initialize_lzma; lzma_info.allocator=(&allocator); code=lzma_auto_decoder(&lzma_info,-1,0); if (code != LZMA_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { int code; zip_info.zalloc=AcquireZIPMemory; zip_info.zfree=RelinquishZIPMemory; zip_info.opaque=(voidpf) NULL; code=inflateInit(&zip_info); if (code != Z_OK) status=MagickFalse; break; } #endif case RLECompression: break; default: break; } pixels=(unsigned char *) GetQuantumPixels(quantum_info); length=0; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; switch (image->compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { bzip_info.next_out=(char *) pixels; bzip_info.avail_out=(unsigned int) (packet_size*image->columns); do { int code; if (bzip_info.avail_in == 0) { bzip_info.next_in=(char *) compress_pixels; length=(size_t) BZipMaxExtent(packet_size*image->columns); if (version != 0.0) length=(size_t) ReadBlobMSBLong(image); if (length > compress_extent) { (void) BZ2_bzDecompressEnd(&bzip_info); ThrowReaderException(CorruptImageError, "UnableToReadImageData"); } bzip_info.avail_in=(unsigned int) ReadBlob(image,length, (unsigned char *) bzip_info.next_in); } code=BZ2_bzDecompress(&bzip_info); if (code < 0) { status=MagickFalse; break; } if (code == BZ_STREAM_END) break; } while (bzip_info.avail_out != 0); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { lzma_info.next_out=pixels; lzma_info.avail_out=packet_size*image->columns; do { int code; if (lzma_info.avail_in == 0) { lzma_info.next_in=compress_pixels; length=(size_t) ReadBlobMSBLong(image); if (length > compress_extent) { lzma_end(&lzma_info); ThrowReaderException(CorruptImageError, "UnableToReadImageData"); } lzma_info.avail_in=(unsigned int) ReadBlob(image,length, (unsigned char *) lzma_info.next_in); } code=lzma_code(&lzma_info,LZMA_RUN); if (code < 0) { status=MagickFalse; break; } if (code == LZMA_STREAM_END) break; } while (lzma_info.avail_out != 0); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { zip_info.next_out=pixels; zip_info.avail_out=(uInt) (packet_size*image->columns); do { int code; if (zip_info.avail_in == 0) { zip_info.next_in=compress_pixels; length=(size_t) ZipMaxExtent(packet_size*image->columns); if (version != 0.0) length=(size_t) ReadBlobMSBLong(image); if (length > compress_extent) { (void) inflateEnd(&zip_info); ThrowReaderException(CorruptImageError, "UnableToReadImageData"); } zip_info.avail_in=(unsigned int) ReadBlob(image,length, zip_info.next_in); } code=inflate(&zip_info,Z_SYNC_FLUSH); if (code < 0) { status=MagickFalse; break; } if (code == Z_STREAM_END) break; } while (zip_info.avail_out != 0); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } #endif case RLECompression: { for (x=0; x < (ssize_t) image->columns; x++) { if (length == 0) { count=ReadBlob(image,packet_size,pixels); PushRunlengthPacket(image,pixels,&length,&pixel,exception); } length--; if (image->storage_class == PseudoClass) SetPixelIndex(image,ClampToQuantum(pixel.index),q); else { SetPixelRed(image,ClampToQuantum(pixel.red),q); SetPixelGreen(image,ClampToQuantum(pixel.green),q); SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (image->colorspace == CMYKColorspace) SetPixelBlack(image,ClampToQuantum(pixel.black),q); } if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } break; } default: { count=ReadBlob(image,packet_size*image->columns,pixels); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } SetQuantumImageType(image,quantum_type); switch (image->compression) { #if defined(MAGICKCORE_BZLIB_DELEGATE) case BZipCompression: { int code; if (version == 0.0) { MagickOffsetType offset; offset=SeekBlob(image,-((MagickOffsetType) bzip_info.avail_in),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } code=BZ2_bzDecompressEnd(&bzip_info); if (code != BZ_OK) status=MagickFalse; break; } #endif #if defined(MAGICKCORE_LZMA_DELEGATE) case LZMACompression: { int code; code=lzma_code(&lzma_info,LZMA_FINISH); if ((code != LZMA_STREAM_END) && (code != LZMA_OK)) status=MagickFalse; lzma_end(&lzma_info); break; } #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) case LZWCompression: case ZipCompression: { int code; if (version == 0.0) { MagickOffsetType offset; offset=SeekBlob(image,-((MagickOffsetType) zip_info.avail_in), SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } code=inflateEnd(&zip_info); if (code != LZMA_OK) status=MagickFalse; break; } #endif default: break; } quantum_info=DestroyQuantumInfo(quantum_info); compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels); if (((y != (ssize_t) image->rows)) || (status == MagickFalse)) { image=DestroyImageList(image); return((Image *) NULL); } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/546'</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 parse_response(unsigned char *buf, int buflen, char *question, int qlen, uint16_t *type, uint16_t *class, int *ttl, unsigned char *response, unsigned int *response_len, uint16_t *answers) { struct domain_hdr *hdr = (void *) buf; struct domain_question *q; unsigned char *ptr; uint16_t qdcount = ntohs(hdr->qdcount); uint16_t ancount = ntohs(hdr->ancount); int err, i; uint16_t qtype, qclass; unsigned char *next = NULL; unsigned int maxlen = *response_len; GSList *aliases = NULL, *list; char name[NS_MAXDNAME + 1]; if (buflen < 12) return -EINVAL; debug("qr %d qdcount %d", hdr->qr, qdcount); /* We currently only cache responses where question count is 1 */ if (hdr->qr != 1 || qdcount != 1) return -EINVAL; ptr = buf + sizeof(struct domain_hdr); strncpy(question, (char *) ptr, qlen); qlen = strlen(question); ptr += qlen + 1; /* skip \0 */ q = (void *) ptr; qtype = ntohs(q->type); /* We cache only A and AAAA records */ if (qtype != 1 && qtype != 28) return -ENOMSG; qclass = ntohs(q->class); ptr += 2 + 2; /* ptr points now to answers */ err = -ENOMSG; *response_len = 0; *answers = 0; memset(name, 0, sizeof(name)); /* * We have a bunch of answers (like A, AAAA, CNAME etc) to * A or AAAA question. We traverse the answers and parse the * resource records. Only A and AAAA records are cached, all * the other records in answers are skipped. */ for (i = 0; i < ancount; i++) { /* * Get one address at a time to this buffer. * The max size of the answer is * 2 (pointer) + 2 (type) + 2 (class) + * 4 (ttl) + 2 (rdlen) + addr (16 or 4) = 28 * for A or AAAA record. * For CNAME the size can be bigger. */ unsigned char rsp[NS_MAXCDNAME]; unsigned int rsp_len = sizeof(rsp) - 1; int ret, rdlen; memset(rsp, 0, sizeof(rsp)); ret = parse_rr(buf, ptr, buf + buflen, rsp, &rsp_len, type, class, ttl, &rdlen, &next, name); if (ret != 0) { err = ret; goto out; } /* * Now rsp contains compressed or uncompressed resource * record. Next we check if this record answers the question. * The name var contains the uncompressed label. * One tricky bit is the CNAME records as they alias * the name we might be interested in. */ /* * Go to next answer if the class is not the one we are * looking for. */ if (*class != qclass) { ptr = next; next = NULL; continue; } /* * Try to resolve aliases also, type is CNAME(5). * This is important as otherwise the aliased names would not * be cached at all as the cache would not contain the aliased * question. * * If any CNAME is found in DNS packet, then we cache the alias * IP address instead of the question (as the server * said that question has only an alias). * This means in practice that if e.g., ipv6.google.com is * queried, DNS server returns CNAME of that name which is * ipv6.l.google.com. We then cache the address of the CNAME * but return the question name to client. So the alias * status of the name is not saved in cache and thus not * returned to the client. We do not return DNS packets from * cache to client saying that ipv6.google.com is an alias to * ipv6.l.google.com but we return instead a DNS packet that * says ipv6.google.com has address xxx which is in fact the * address of ipv6.l.google.com. For caching purposes this * should not cause any issues. */ if (*type == 5 && strncmp(question, name, qlen) == 0) { /* * So now the alias answered the question. This is * not very useful from caching point of view as * the following A or AAAA records will not match the * question. We need to find the real A/AAAA record * of the alias and cache that. */ unsigned char *end = NULL; int name_len = 0, output_len = 0; memset(rsp, 0, sizeof(rsp)); rsp_len = sizeof(rsp) - 1; /* * Alias is in rdata part of the message, * and next-rdlen points to it. So we need to get * the real name of the alias. */ ret = get_name(0, buf, next - rdlen, buf + buflen, rsp, rsp_len, &output_len, &end, name, &name_len); if (ret != 0) { /* just ignore the error at this point */ ptr = next; next = NULL; continue; } /* * We should now have the alias of the entry we might * want to cache. Just remember it for a while. * We check the alias list when we have parsed the * A or AAAA record. */ aliases = g_slist_prepend(aliases, g_strdup(name)); ptr = next; next = NULL; continue; } if (*type == qtype) { /* * We found correct type (A or AAAA) */ if (check_alias(aliases, name) || (!aliases && strncmp(question, name, qlen) == 0)) { /* * We found an alias or the name of the rr * matches the question. If so, we append * the compressed label to the cache. * The end result is a response buffer that * will contain one or more cached and * compressed resource records. */ if (*response_len + rsp_len > maxlen) { err = -ENOBUFS; goto out; } memcpy(response + *response_len, rsp, rsp_len); *response_len += rsp_len; (*answers)++; err = 0; } } ptr = next; next = NULL; } out: for (list = aliases; list; list = list->next) g_free(list->data); g_slist_free(aliases); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'dnsproxy: Fix crash on malformed DNS response If the response query string is malformed, we might access memory pass the end of "name" variable in parse_response().'</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: std::string controller::bookmark( const std::string& url, const std::string& title, const std::string& description, const std::string& feed_title) { std::string bookmark_cmd = cfg.get_configvalue("bookmark-cmd"); bool is_interactive = cfg.get_configvalue_as_bool("bookmark-interactive"); if (bookmark_cmd.length() > 0) { std::string cmdline = strprintf::fmt("%s '%s' %s %s %s", bookmark_cmd, utils::replace_all(url,"'", "%27"), quote_empty(stfl::quote(title)), quote_empty(stfl::quote(description)), quote_empty(stfl::quote(feed_title))); LOG(level::DEBUG, "controller::bookmark: cmd = %s", cmdline); if (is_interactive) { v->push_empty_formaction(); stfl::reset(); utils::run_interactively(cmdline, "controller::bookmark"); v->pop_current_formaction(); return ""; } else { char * my_argv[4]; my_argv[0] = const_cast<char *>("/bin/sh"); my_argv[1] = const_cast<char *>("-c"); my_argv[2] = const_cast<char *>(cmdline.c_str()); my_argv[3] = nullptr; return utils::run_program(my_argv, ""); } } else { return _("bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly."); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-943', 'CWE-787'], 'message': 'Sanitize inputs to bookmark-cmd (#591) Newsbeuter didn't properly shell-escape the arguments passed to bookmarking command, which allows a remote attacker to perform remote code execution by crafting an RSS item whose title and/or URL contain something interpretable by the shell (most notably subshell invocations.) This has been reported by Jeriko One <jeriko.one@gmx.us>, complete with PoC and a patch. This vulnerability was assigned CVE-2017-12904.'</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: ec_p_init (mpi_ec_t ctx, enum gcry_mpi_ec_models model, enum ecc_dialects dialect, int flags, gcry_mpi_t p, gcry_mpi_t a, gcry_mpi_t b) { int i; static int use_barrett; if (!use_barrett) { if (getenv ("GCRYPT_BARRETT")) use_barrett = 1; else use_barrett = -1; } /* Fixme: Do we want to check some constraints? e.g. a < p */ ctx->model = model; ctx->dialect = dialect; ctx->flags = flags; if (dialect == ECC_DIALECT_ED25519) ctx->nbits = 256; else ctx->nbits = mpi_get_nbits (p); ctx->p = mpi_copy (p); ctx->a = mpi_copy (a); ctx->b = mpi_copy (b); ctx->t.p_barrett = use_barrett > 0? _gcry_mpi_barrett_init (ctx->p, 0):NULL; _gcry_mpi_ec_get_reset (ctx); /* Allocate scratch variables. */ for (i=0; i< DIM(ctx->t.scratch); i++) ctx->t.scratch[i] = mpi_alloc_like (ctx->p); /* Prepare for fast reduction. */ /* FIXME: need a test for NIST values. However it does not gain us any real advantage, for 384 bits it is actually slower than using mpi_mulm. */ /* ctx->nist_nbits = mpi_get_nbits (ctx->p); */ /* if (ctx->nist_nbits == 192) */ /* { */ /* for (i=0; i < 4; i++) */ /* ctx->s[i] = mpi_new (192); */ /* ctx->c = mpi_new (192*2); */ /* } */ /* else if (ctx->nist_nbits == 384) */ /* { */ /* for (i=0; i < 10; i++) */ /* ctx->s[i] = mpi_new (384); */ /* ctx->c = mpi_new (384*2); */ /* } */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'ecc: Add input validation for X25519. * cipher/ecc.c (ecc_decrypt_raw): Add input validation. * mpi/ec.c (ec_p_init): Use scratch buffer for bad points. (_gcry_mpi_ec_bad_point): New. -- Following is the paper describing the attack: May the Fourth Be With You: A Microarchitectural Side Channel Attack on Real-World Applications of Curve25519 by Daniel Genkin, Luke Valenta, and Yuval Yarom In the current implementation, we do output checking and it results an error for those bad points. However, when attacked, the computation will done with leak of private key, even it will results errors. To mitigate leak, we added input validation. Note that we only list bad points with MSB=0. By X25519, MSB is always cleared. In future, we should implement constant-time field computation. Then, this input validation could be removed, if performance is important and we are sure for no leak. CVE-id: CVE-2017-0379 Signed-off-by: NIIBE Yutaka <gniibe@fsij.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 bool glfs_check_config(const char *cfgstring, char **reason) { char *path; glfs_t *fs = NULL; glfs_fd_t *gfd = NULL; gluster_server *hosts = NULL; /* gluster server defination */ bool result = true; path = strchr(cfgstring, '/'); if (!path) { if (asprintf(reason, "No path found") == -1) *reason = NULL; result = false; goto done; } path += 1; /* get past '/' */ fs = tcmu_create_glfs_object(path, &hosts); if (!fs) { tcmu_err("tcmu_create_glfs_object failed\n"); goto done; } gfd = glfs_open(fs, hosts->path, ALLOWED_BSOFLAGS); if (!gfd) { if (asprintf(reason, "glfs_open failed: %m") == -1) *reason = NULL; result = false; goto unref; } if (glfs_access(fs, hosts->path, R_OK|W_OK) == -1) { if (asprintf(reason, "glfs_access file not present, or not writable") == -1) *reason = NULL; result = false; goto unref; } goto done; unref: gluster_cache_refresh(fs, path); done: if (gfd) glfs_close(gfd); gluster_free_server(&hosts); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-119'], 'message': 'glfs: discard glfs_check_config Signed-off-by: Prasanna Kumar Kalever <prasanna.kalever@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 bool fbo_check_config(const char *cfgstring, char **reason) { char *options; char *path; int fd; tcmu_dbg("check: cfgstring %s\n", cfgstring); options = strchr(cfgstring, '/'); if (!options) { if (asprintf(reason, "Invalid cfgstring") == -1) *reason = NULL; return false; } options += 1; /* get past '/' */ while (options[0] != '/') { if (strncasecmp(options, "ro/", 3)) { if (asprintf(reason, "Unknown option %s\n", options) == -1) *reason = NULL; return false; } options = strchr(options, '/'); if (!options) { if (asprintf(reason, "Invalid cfgstring") == -1) *reason = NULL; return false; } options += 1; } path = options; if (!path) { if (asprintf(reason, "No path found") == -1) *reason = NULL; return false; } if (access(path, R_OK) != -1) return true; /* File exists */ /* We also support creating the file, so see if we can create it */ /* NB: If we're creating it, then we'll need write permission */ fd = creat(path, S_IRUSR | S_IWUSR); if (fd == -1) { if (asprintf(reason, "Could not create file") == -1) *reason = NULL; return false; } unlink(path); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'removed all check_config callback implementations to avoid security issues see github issue #194 qcow.c contained an information leak, could test for existance of any file in the system file_example.c and file_optical.c allow also to test for existance of any file, plus to temporarily create empty new files anywhere in the file system. This also involves a race condition, if a file didn't exist in the first place, but would be created in-between by some other process, then the file would be deleted by the check_config implementation.'</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 opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters, opj_image_t *image, opj_event_mgr_t *p_manager) { /* Configure cinema parameters */ int i; /* No tiling */ parameters->tile_size_on = OPJ_FALSE; parameters->cp_tdx = 1; parameters->cp_tdy = 1; /* One tile part for each component */ parameters->tp_flag = 'C'; parameters->tp_on = 1; /* Tile and Image shall be at (0,0) */ parameters->cp_tx0 = 0; parameters->cp_ty0 = 0; parameters->image_offset_x0 = 0; parameters->image_offset_y0 = 0; /* Codeblock size= 32*32 */ parameters->cblockw_init = 32; parameters->cblockh_init = 32; /* Codeblock style: no mode switch enabled */ parameters->mode = 0; /* No ROI */ parameters->roi_compno = -1; /* No subsampling */ parameters->subsampling_dx = 1; parameters->subsampling_dy = 1; /* 9-7 transform */ parameters->irreversible = 1; /* Number of layers */ if (parameters->tcp_numlayers > 1) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "1 single quality layer" "-> Number of layers forced to 1 (rather than %d)\n" "-> Rate of the last layer (%3.1f) will be used", parameters->tcp_numlayers, parameters->tcp_rates[parameters->tcp_numlayers - 1]); parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1]; parameters->tcp_numlayers = 1; } /* Resolution levels */ switch (parameters->rsiz) { case OPJ_PROFILE_CINEMA_2K: if (parameters->numresolution > 6) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 (2k dc profile) requires:\n" "Number of decomposition levels <= 5\n" "-> Number of decomposition levels forced to 5 (rather than %d)\n", parameters->numresolution + 1); parameters->numresolution = 6; } break; case OPJ_PROFILE_CINEMA_4K: if (parameters->numresolution < 2) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-4 (4k dc profile) requires:\n" "Number of decomposition levels >= 1 && <= 6\n" "-> Number of decomposition levels forced to 1 (rather than %d)\n", parameters->numresolution + 1); parameters->numresolution = 1; } else if (parameters->numresolution > 7) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-4 (4k dc profile) requires:\n" "Number of decomposition levels >= 1 && <= 6\n" "-> Number of decomposition levels forced to 6 (rather than %d)\n", parameters->numresolution + 1); parameters->numresolution = 7; } break; default : break; } /* Precincts */ parameters->csty |= 0x01; parameters->res_spec = parameters->numresolution - 1; for (i = 0; i < parameters->res_spec; i++) { parameters->prcw_init[i] = 256; parameters->prch_init[i] = 256; } /* The progression order shall be CPRL */ parameters->prog_order = OPJ_CPRL; /* Progression order changes for 4K, disallowed for 2K */ if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) { parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC, parameters->numresolution); } else { parameters->numpocs = 0; } /* Limited bit-rate */ parameters->cp_disto_alloc = 1; if (parameters->max_cs_size <= 0) { /* No rate has been introduced, 24 fps is assumed */ parameters->max_cs_size = OPJ_CINEMA_24_CS; opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1302083 compressed bytes @ 24fps\n" "As no rate has been given, this limit will be used.\n"); } else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1302083 compressed bytes @ 24fps\n" "-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n"); parameters->max_cs_size = OPJ_CINEMA_24_CS; } if (parameters->max_comp_size <= 0) { /* No rate has been introduced, 24 fps is assumed */ parameters->max_comp_size = OPJ_CINEMA_24_COMP; opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1041666 compressed bytes @ 24fps\n" "As no rate has been given, this limit will be used.\n"); } else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) { opj_event_msg(p_manager, EVT_WARNING, "JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n" "Maximum 1041666 compressed bytes @ 24fps\n" "-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n"); parameters->max_comp_size = OPJ_CINEMA_24_COMP; } parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec) / (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx * image->comps[0].dy); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-787'], 'message': 'Fix assertion in debug mode / heap-based buffer overflow in opj_write_bytes_LE for Cinema profiles with numresolutions = 1 (#985)'</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 OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k, opj_tcd_t * p_tile_coder, OPJ_BYTE * p_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_total_data_size, const opj_stream_private_t *p_stream, opj_event_mgr_t * p_manager ) { opj_codestream_info_t *l_cstr_info = 00; OPJ_UINT32 l_remaining_data; /* preconditions */ assert(p_j2k != 00); assert(p_manager != 00); assert(p_stream != 00); OPJ_UNUSED(p_stream); opj_write_bytes(p_data, J2K_MS_SOD, 2); /* SOD */ p_data += 2; /* make room for the EOF marker */ l_remaining_data = p_total_data_size - 4; /* update tile coder */ p_tile_coder->tp_num = p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ; p_tile_coder->cur_tp_num = p_j2k->m_specific_param.m_encoder.m_current_tile_part_number; /* INDEX >> */ /* TODO mergeV2: check this part which use cstr_info */ /*l_cstr_info = p_j2k->cstr_info; if (l_cstr_info) { if (!p_j2k->m_specific_param.m_encoder.m_current_tile_part_number ) { //TODO cstr_info->tile[p_j2k->m_current_tile_number].end_header = p_stream_tell(p_stream) + p_j2k->pos_correction - 1; l_cstr_info->tile[p_j2k->m_current_tile_number].tileno = p_j2k->m_current_tile_number; } else {*/ /* TODO if (cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno - 1].end_pos < p_stream_tell(p_stream)) { cstr_info->tile[p_j2k->m_current_tile_number].packet[cstr_info->packno].start_pos = p_stream_tell(p_stream); }*/ /*}*/ /* UniPG>> */ #ifdef USE_JPWL /* update markers struct */ /*OPJ_BOOL res = j2k_add_marker(p_j2k->cstr_info, J2K_MS_SOD, p_j2k->sod_start, 2); */ assert(0 && "TODO"); #endif /* USE_JPWL */ /* <<UniPG */ /*}*/ /* << INDEX */ if (p_j2k->m_specific_param.m_encoder.m_current_tile_part_number == 0) { p_tile_coder->tcd_image->tiles->packno = 0; if (l_cstr_info) { l_cstr_info->packno = 0; } } *p_data_written = 0; if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data, p_data_written, l_remaining_data, l_cstr_info, p_manager)) { opj_event_msg(p_manager, EVT_ERROR, "Cannot encode tile\n"); return OPJ_FALSE; } *p_data_written += 2; return OPJ_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-787'], 'message': 'opj_t2_encode_packet(): fix potential write heap buffer overflow (#992)'</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: gss_wrap_aead (minor_status, context_handle, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer) OM_uint32 * minor_status; gss_ctx_id_t context_handle; int conf_req_flag; gss_qop_t qop_req; gss_buffer_t input_assoc_buffer; gss_buffer_t input_payload_buffer; int * conf_state; gss_buffer_t output_message_buffer; { OM_uint32 status; gss_mechanism mech; gss_union_ctx_id_t ctx; status = val_wrap_aead_args(minor_status, context_handle, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t)context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (!mech) return (GSS_S_BAD_MECH); return gssint_wrap_aead(mech, minor_status, ctx, conf_req_flag, qop_req, input_assoc_buffer, input_payload_buffer, conf_state, output_message_buffer); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup'</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: gss_unwrap_iov (minor_status, context_handle, conf_state, qop_state, iov, iov_count) OM_uint32 * minor_status; gss_ctx_id_t context_handle; int * conf_state; gss_qop_t *qop_state; gss_iov_buffer_desc * iov; int iov_count; { /* EXPORT DELETE START */ OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_unwrap_iov_args(minor_status, context_handle, conf_state, qop_state, iov, iov_count); if (status != GSS_S_COMPLETE) return (status); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_unwrap_iov) { status = mech->gss_unwrap_iov( minor_status, ctx->internal_ctx_id, conf_state, qop_state, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } /* EXPORT DELETE END */ return (GSS_S_BAD_MECH); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup'</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 jpc_dec_destroy(jpc_dec_t *dec) { if (dec->cstate) { jpc_cstate_destroy(dec->cstate); } if (dec->pkthdrstreams) { jpc_streamlist_destroy(dec->pkthdrstreams); } if (dec->image) { jas_image_destroy(dec->image); } if (dec->cp) { jpc_dec_cp_destroy(dec->cp); } if (dec->cmpts) { jas_free(dec->cmpts); } if (dec->tiles) { jas_free(dec->tiles); } jas_free(dec); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'jpc_dec: fix tile memory leak after decoder failure The function jpc_dec_tilefini() is only called for tiles which have completed successfully. If there is one decoder error, all unfinished tiles leak lots of memory. This change adds jpc_dec_tilefini() calls to jpc_dec_destroy() for each tile which is not marked "done" (state!=JPC_TILE_DONE). This however crashes when the tile initialization loop in jpc_dec_process_siz() fails, because the rest of the array has not yet been initialized; to work around this, I added a loop which initializes all states with JPC_TILE_DONE before doing the real initialization. Fixes CVE-2017-13748 Closes https://github.com/mdadams/jasper/issues/168'</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 l2cap_chan *l2cap_connect(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data, u8 rsp_code, u8 amp_id) { struct l2cap_conn_req *req = (struct l2cap_conn_req *) data; struct l2cap_conn_rsp rsp; struct l2cap_chan *chan = NULL, *pchan; int result, status = L2CAP_CS_NO_INFO; u16 dcid = 0, scid = __le16_to_cpu(req->scid); __le16 psm = req->psm; BT_DBG("psm 0x%2.2x scid 0x%4.4x", __le16_to_cpu(psm), scid); /* Check if we have socket listening on psm */ pchan = l2cap_global_chan_by_psm(BT_LISTEN, psm, &conn->hcon->src, &conn->hcon->dst, ACL_LINK); if (!pchan) { result = L2CAP_CR_BAD_PSM; goto sendresp; } mutex_lock(&conn->chan_lock); l2cap_chan_lock(pchan); /* Check if the ACL is secure enough (if not SDP) */ if (psm != cpu_to_le16(L2CAP_PSM_SDP) && !hci_conn_check_link_mode(conn->hcon)) { conn->disc_reason = HCI_ERROR_AUTH_FAILURE; result = L2CAP_CR_SEC_BLOCK; goto response; } result = L2CAP_CR_NO_MEM; /* Check if we already have channel with that dcid */ if (__l2cap_get_chan_by_dcid(conn, scid)) goto response; chan = pchan->ops->new_connection(pchan); if (!chan) goto response; /* For certain devices (ex: HID mouse), support for authentication, * pairing and bonding is optional. For such devices, inorder to avoid * the ACL alive for too long after L2CAP disconnection, reset the ACL * disc_timeout back to HCI_DISCONN_TIMEOUT during L2CAP connect. */ conn->hcon->disc_timeout = HCI_DISCONN_TIMEOUT; bacpy(&chan->src, &conn->hcon->src); bacpy(&chan->dst, &conn->hcon->dst); chan->src_type = bdaddr_src_type(conn->hcon); chan->dst_type = bdaddr_dst_type(conn->hcon); chan->psm = psm; chan->dcid = scid; chan->local_amp_id = amp_id; __l2cap_chan_add(conn, chan); dcid = chan->scid; __set_chan_timer(chan, chan->ops->get_sndtimeo(chan)); chan->ident = cmd->ident; if (conn->info_state & L2CAP_INFO_FEAT_MASK_REQ_DONE) { if (l2cap_chan_check_security(chan, false)) { if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) { l2cap_state_change(chan, BT_CONNECT2); result = L2CAP_CR_PEND; status = L2CAP_CS_AUTHOR_PEND; chan->ops->defer(chan); } else { /* Force pending result for AMP controllers. * The connection will succeed after the * physical link is up. */ if (amp_id == AMP_ID_BREDR) { l2cap_state_change(chan, BT_CONFIG); result = L2CAP_CR_SUCCESS; } else { l2cap_state_change(chan, BT_CONNECT2); result = L2CAP_CR_PEND; } status = L2CAP_CS_NO_INFO; } } else { l2cap_state_change(chan, BT_CONNECT2); result = L2CAP_CR_PEND; status = L2CAP_CS_AUTHEN_PEND; } } else { l2cap_state_change(chan, BT_CONNECT2); result = L2CAP_CR_PEND; status = L2CAP_CS_NO_INFO; } response: l2cap_chan_unlock(pchan); mutex_unlock(&conn->chan_lock); l2cap_chan_put(pchan); sendresp: rsp.scid = cpu_to_le16(scid); rsp.dcid = cpu_to_le16(dcid); rsp.result = cpu_to_le16(result); rsp.status = cpu_to_le16(status); l2cap_send_cmd(conn, cmd->ident, rsp_code, sizeof(rsp), &rsp); if (result == L2CAP_CR_PEND && status == L2CAP_CS_NO_INFO) { struct l2cap_info_req info; info.type = cpu_to_le16(L2CAP_IT_FEAT_MASK); conn->info_state |= L2CAP_INFO_FEAT_MASK_REQ_SENT; conn->info_ident = l2cap_get_ident(conn); schedule_delayed_work(&conn->info_timer, L2CAP_INFO_TIMEOUT); l2cap_send_cmd(conn, conn->info_ident, L2CAP_INFO_REQ, sizeof(info), &info); } if (chan && !test_bit(CONF_REQ_SENT, &chan->conf_state) && result == L2CAP_CR_SUCCESS) { u8 buf[128]; set_bit(CONF_REQ_SENT, &chan->conf_state); l2cap_send_cmd(conn, l2cap_get_ident(conn), L2CAP_CONF_REQ, l2cap_build_conf_req(chan, buf), buf); chan->num_conf_req++; } return chan; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: Properly check L2CAP config option output buffer length Validate the output buffer length for L2CAP config requests and responses to avoid overflowing the stack buffer used for building the option blocks. Cc: stable@vger.kernel.org Signed-off-by: Ben Seri <ben@armis.com> Signed-off-by: Marcel Holtmann <marcel@holtmann.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 l2cap_parse_conf_rsp(struct l2cap_chan *chan, void *rsp, int len, void *data, u16 *result) { struct l2cap_conf_req *req = data; void *ptr = req->data; int type, olen; unsigned long val; struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC }; struct l2cap_conf_efs efs; BT_DBG("chan %p, rsp %p, len %d, req %p", chan, rsp, len, data); while (len >= L2CAP_CONF_OPT_SIZE) { len -= l2cap_get_conf_opt(&rsp, &type, &olen, &val); switch (type) { case L2CAP_CONF_MTU: if (val < L2CAP_DEFAULT_MIN_MTU) { *result = L2CAP_CONF_UNACCEPT; chan->imtu = L2CAP_DEFAULT_MIN_MTU; } else chan->imtu = val; l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, chan->imtu); break; case L2CAP_CONF_FLUSH_TO: chan->flush_to = val; l2cap_add_conf_opt(&ptr, L2CAP_CONF_FLUSH_TO, 2, chan->flush_to); break; case L2CAP_CONF_RFC: if (olen == sizeof(rfc)) memcpy(&rfc, (void *)val, olen); if (test_bit(CONF_STATE2_DEVICE, &chan->conf_state) && rfc.mode != chan->mode) return -ECONNREFUSED; chan->fcs = 0; l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc), (unsigned long) &rfc); break; case L2CAP_CONF_EWS: chan->ack_win = min_t(u16, val, chan->ack_win); l2cap_add_conf_opt(&ptr, L2CAP_CONF_EWS, 2, chan->tx_win); break; case L2CAP_CONF_EFS: if (olen == sizeof(efs)) memcpy(&efs, (void *)val, olen); if (chan->local_stype != L2CAP_SERV_NOTRAFIC && efs.stype != L2CAP_SERV_NOTRAFIC && efs.stype != chan->local_stype) return -ECONNREFUSED; l2cap_add_conf_opt(&ptr, L2CAP_CONF_EFS, sizeof(efs), (unsigned long) &efs); break; case L2CAP_CONF_FCS: if (*result == L2CAP_CONF_PENDING) if (val == L2CAP_FCS_NONE) set_bit(CONF_RECV_NO_FCS, &chan->conf_state); break; } } if (chan->mode == L2CAP_MODE_BASIC && chan->mode != rfc.mode) return -ECONNREFUSED; chan->mode = rfc.mode; if (*result == L2CAP_CONF_SUCCESS || *result == L2CAP_CONF_PENDING) { switch (rfc.mode) { case L2CAP_MODE_ERTM: chan->retrans_timeout = le16_to_cpu(rfc.retrans_timeout); chan->monitor_timeout = le16_to_cpu(rfc.monitor_timeout); chan->mps = le16_to_cpu(rfc.max_pdu_size); if (!test_bit(FLAG_EXT_CTRL, &chan->flags)) chan->ack_win = min_t(u16, chan->ack_win, rfc.txwin_size); if (test_bit(FLAG_EFS_ENABLE, &chan->flags)) { chan->local_msdu = le16_to_cpu(efs.msdu); chan->local_sdu_itime = le32_to_cpu(efs.sdu_itime); chan->local_acc_lat = le32_to_cpu(efs.acc_lat); chan->local_flush_to = le32_to_cpu(efs.flush_to); } break; case L2CAP_MODE_STREAMING: chan->mps = le16_to_cpu(rfc.max_pdu_size); } } req->dcid = cpu_to_le16(chan->dcid); req->flags = cpu_to_le16(0); return ptr - data; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: Properly check L2CAP config option output buffer length Validate the output buffer length for L2CAP config requests and responses to avoid overflowing the stack buffer used for building the option blocks. Cc: stable@vger.kernel.org Signed-off-by: Ben Seri <ben@armis.com> Signed-off-by: Marcel Holtmann <marcel@holtmann.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 mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns) { const char *userid = rock->userid; int isadmin = rock->isadmin; int crossdomains = config_getswitch(IMAPOPT_CROSSDOMAINS); char inbox[MAX_MAILBOX_BUFFER]; size_t inboxlen = 0; size_t prefixlen, len; size_t domainlen = 0; size_t userlen = userid ? strlen(userid) : 0; char domainpat[MAX_MAILBOX_BUFFER]; /* do intra-domain fetches only */ char commonpat[MAX_MAILBOX_BUFFER]; int r = 0; int i; const char *p; if (patterns->count < 1) return 0; /* nothing to do */ for (i = 0; i < patterns->count; i++) { glob *g = glob_init(strarray_nth(patterns, i), rock->namespace->hier_sep); ptrarray_append(&rock->globs, g); } if (config_virtdomains && userid && (p = strchr(userid, '@'))) { userlen = p - userid; domainlen = strlen(p); /* includes separator */ snprintf(domainpat, sizeof(domainpat), "%s!", p+1); } else domainpat[0] = '\0'; /* calculate the inbox (with trailing .INBOX. for later use) */ if (userid && (!(p = strchr(userid, rock->namespace->hier_sep)) || ((p - userid) > (int)userlen)) && strlen(userid)+7 < MAX_MAILBOX_BUFFER) { char *t, *tmpuser = NULL; const char *inboxuser; if (domainlen) snprintf(inbox, sizeof(inbox), "%s!", userid+userlen+1); if (rock->namespace->hier_sep == '/' && (p = strchr(userid, '.'))) { tmpuser = xmalloc(userlen); memcpy(tmpuser, userid, userlen); t = tmpuser + (p - userid); while(t < (tmpuser + userlen)) { if (*t == '.') *t = '^'; t++; } inboxuser = tmpuser; } else inboxuser = userid; snprintf(inbox+domainlen, sizeof(inbox)-domainlen, "user.%.*s.INBOX.", (int)userlen, inboxuser); free(tmpuser); inboxlen = strlen(inbox) - 7; } else { userid = 0; } /* Find the common search prefix of all patterns */ const char *firstpat = strarray_nth(patterns, 0); for (prefixlen = 0; firstpat[prefixlen]; prefixlen++) { if (prefixlen >= MAX_MAILBOX_NAME) { r = IMAP_MAILBOX_BADNAME; goto done; } char c = firstpat[prefixlen]; for (i = 1; i < patterns->count; i++) { const char *pat = strarray_nth(patterns, i); if (pat[prefixlen] != c) break; } if (i < patterns->count) break; if (c == '*' || c == '%' || c == '?') break; commonpat[prefixlen] = c; } commonpat[prefixlen] = '\0'; if (patterns->count == 1) { /* Skip pattern which matches shared namespace prefix */ if (!strcmp(firstpat+prefixlen, "%")) rock->singlepercent = 2; /* output prefix regardless */ if (!strcmp(firstpat+prefixlen, "*%")) rock->singlepercent = 1; } /* * Personal (INBOX) namespace (only if not admin) */ if (userid && !isadmin) { /* first the INBOX */ rock->mb_category = MBNAME_INBOX; r = cyrusdb_forone(rock->db, inbox, inboxlen, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; if (rock->namespace->isalt) { /* do exact INBOX subs before resetting the namebuffer */ rock->mb_category = MBNAME_INBOXSUB; r = cyrusdb_foreach(rock->db, inbox, inboxlen+7, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; } /* iterate through all the mailboxes under the user's inbox */ rock->mb_category = MBNAME_OWNER; r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; /* "Alt Prefix" folders */ if (rock->namespace->isalt) { /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; rock->mb_category = MBNAME_ALTINBOX; /* special case user.foo.INBOX. If we're singlepercent == 2, this could return DONE, in which case we don't need to foreach the rest of the altprefix space */ r = cyrusdb_forone(rock->db, inbox, inboxlen+6, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) goto skipalt; if (r) goto done; /* special case any other altprefix stuff */ rock->mb_category = MBNAME_ALTPREFIX; r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); skipalt: /* we got a done, so skip out of the foreach early */ if (r == CYRUSDB_DONE) r = 0; if (r) goto done; } } /* * Other Users namespace * * If "Other Users*" can match pattern, search for those mailboxes next */ if (isadmin || rock->namespace->accessible[NAMESPACE_USER]) { len = strlen(rock->namespace->prefix[NAMESPACE_USER]); if (len) len--; // trailing separator if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) { if (prefixlen < len) { /* we match all users */ strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen); } else { /* just those in this prefix */ strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen); strlcpy(domainpat+domainlen+5, commonpat+len+1, sizeof(domainpat)-domainlen-5); } rock->mb_category = MBNAME_OTHERUSER; /* because of how domains work, with crossdomains or admin you can't prefix at all :( */ size_t thislen = (isadmin || crossdomains) ? 0 : strlen(domainpat); /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; r = mboxlist_find_category(rock, domainpat, thislen); if (r) goto done; } } /* * Shared namespace * * search for all remaining mailboxes. * just bother looking at the ones that have the same pattern prefix. */ if (isadmin || rock->namespace->accessible[NAMESPACE_SHARED]) { len = strlen(rock->namespace->prefix[NAMESPACE_SHARED]); if (len) len--; // trailing separator if (!strncmp(rock->namespace->prefix[NAMESPACE_SHARED], commonpat, MIN(len, prefixlen))) { rock->mb_category = MBNAME_SHARED; /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; /* iterate through all the non-user folders on the server */ r = mboxlist_find_category(rock, domainpat, domainlen); if (r) goto done; } } /* finish with a reset call always */ r = (*rock->proc)(NULL, rock->procrock); done: for (i = 0; i < rock->globs.count; i++) { glob *g = ptrarray_nth(&rock->globs, i); glob_free(&g); } ptrarray_fini(&rock->globs); return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'mboxlist: fix uninitialised memory use where pattern is "Other Users"'</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 CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if(len > 8 && pos+len > 2* fsize) continue; tag |= uptag << 16; if(len > 100*1024*1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(len); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes (tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len,ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp (model, "E-300", 5) && strncmp (model, "E-330", 5) && strncmp (model, "E-400", 5) && strncmp (model, "E-500", 5) && strncmp (model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || ( ((type == 3) || (type == 8)) && (len > 2)) || ( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp)<<16 | (unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens,len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment,len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 65535) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'processCanonCameraInfo possible buffer overrun on damaged file'</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: bson_iter_codewscope (const bson_iter_t *iter, /* IN */ uint32_t *length, /* OUT */ uint32_t *scope_len, /* OUT */ const uint8_t **scope) /* OUT */ { uint32_t len; BSON_ASSERT (iter); if (ITER_TYPE (iter) == BSON_TYPE_CODEWSCOPE) { if (length) { memcpy (&len, iter->raw + iter->d2, sizeof (len)); *length = BSON_UINT32_FROM_LE (len) - 1; } memcpy (&len, iter->raw + iter->d4, sizeof (len)); *scope_len = BSON_UINT32_FROM_LE (len); *scope = iter->raw + iter->d4; return (const char *) (iter->raw + iter->d3); } if (length) { *length = 0; } if (scope_len) { *scope_len = 0; } if (scope) { *scope = NULL; } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'CDRIVER-2269 Check for zero string length in codewscope'</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: read_header(struct archive_read *a, struct archive_entry *entry, char head_type) { const void *h; const char *p, *endp; struct rar *rar; struct rar_header rar_header; struct rar_file_header file_header; int64_t header_size; unsigned filename_size, end; char *filename; char *strp; char packed_size[8]; char unp_size[8]; int ttime; struct archive_string_conv *sconv, *fn_sconv; unsigned long crc32_val; int ret = (ARCHIVE_OK), ret2; rar = (struct rar *)(a->format->data); /* Setup a string conversion object for non-rar-unicode filenames. */ sconv = rar->opt_sconv; if (sconv == NULL) { if (!rar->init_default_conversion) { rar->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); rar->init_default_conversion = 1; } sconv = rar->sconv_default; } if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; memcpy(&rar_header, p, sizeof(rar_header)); rar->file_flags = archive_le16dec(rar_header.flags); header_size = archive_le16dec(rar_header.size); if (header_size < (int64_t)sizeof(file_header) + 7) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2); __archive_read_consume(a, 7); if (!(rar->file_flags & FHD_SOLID)) { rar->compression_method = 0; rar->packed_size = 0; rar->unp_size = 0; rar->mtime = 0; rar->ctime = 0; rar->atime = 0; rar->arctime = 0; rar->mode = 0; memset(&rar->salt, 0, sizeof(rar->salt)); rar->atime = 0; rar->ansec = 0; rar->ctime = 0; rar->cnsec = 0; rar->mtime = 0; rar->mnsec = 0; rar->arctime = 0; rar->arcnsec = 0; } else { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR solid archive support unavailable."); return (ARCHIVE_FATAL); } if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); /* File Header CRC check. */ crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7)); if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Header CRC error"); return (ARCHIVE_FATAL); } /* If no CRC error, Go on parsing File Header. */ p = h; endp = p + header_size - 7; memcpy(&file_header, p, sizeof(file_header)); p += sizeof(file_header); rar->compression_method = file_header.method; ttime = archive_le32dec(file_header.file_time); rar->mtime = get_time(ttime); rar->file_crc = archive_le32dec(file_header.file_crc); if (rar->file_flags & FHD_PASSWORD) { archive_entry_set_is_data_encrypted(entry, 1); rar->has_encrypted_entries = 1; archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "RAR encryption support unavailable."); /* Since it is only the data part itself that is encrypted we can at least extract information about the currently processed entry and don't need to return ARCHIVE_FATAL here. */ /*return (ARCHIVE_FATAL);*/ } if (rar->file_flags & FHD_LARGE) { memcpy(packed_size, file_header.pack_size, 4); memcpy(packed_size + 4, p, 4); /* High pack size */ p += 4; memcpy(unp_size, file_header.unp_size, 4); memcpy(unp_size + 4, p, 4); /* High unpack size */ p += 4; rar->packed_size = archive_le64dec(&packed_size); rar->unp_size = archive_le64dec(&unp_size); } else { rar->packed_size = archive_le32dec(file_header.pack_size); rar->unp_size = archive_le32dec(file_header.unp_size); } if (rar->packed_size < 0 || rar->unp_size < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid sizes specified."); return (ARCHIVE_FATAL); } rar->bytes_remaining = rar->packed_size; /* TODO: RARv3 subblocks contain comments. For now the complete block is * consumed at the end. */ if (head_type == NEWSUB_HEAD) { size_t distance = p - (const char *)h; header_size += rar->packed_size; /* Make sure we have the extended data. */ if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) return (ARCHIVE_FATAL); p = h; endp = p + header_size - 7; p += distance; } filename_size = archive_le16dec(file_header.name_size); if (p + filename_size > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename size"); return (ARCHIVE_FATAL); } if (rar->filename_allocated < filename_size * 2 + 2) { char *newptr; size_t newsize = filename_size * 2 + 2; newptr = realloc(rar->filename, newsize); if (newptr == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->filename = newptr; rar->filename_allocated = newsize; } filename = rar->filename; memcpy(filename, p, filename_size); filename[filename_size] = '\0'; if (rar->file_flags & FHD_UNICODE) { if (filename_size != strlen(filename)) { unsigned char highbyte, flagbits, flagbyte; unsigned fn_end, offset; end = filename_size; fn_end = filename_size * 2; filename_size = 0; offset = (unsigned)strlen(filename) + 1; highbyte = *(p + offset++); flagbits = 0; flagbyte = 0; while (offset < end && filename_size < fn_end) { if (!flagbits) { flagbyte = *(p + offset++); flagbits = 8; } flagbits -= 2; switch((flagbyte >> flagbits) & 3) { case 0: filename[filename_size++] = '\0'; filename[filename_size++] = *(p + offset++); break; case 1: filename[filename_size++] = highbyte; filename[filename_size++] = *(p + offset++); break; case 2: filename[filename_size++] = *(p + offset + 1); filename[filename_size++] = *(p + offset); offset += 2; break; case 3: { char extra, high; uint8_t length = *(p + offset++); if (length & 0x80) { extra = *(p + offset++); high = (char)highbyte; } else extra = high = 0; length = (length & 0x7f) + 2; while (length && filename_size < fn_end) { unsigned cp = filename_size >> 1; filename[filename_size++] = high; filename[filename_size++] = p[cp] + extra; length--; } } break; } } if (filename_size > fn_end) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid filename"); return (ARCHIVE_FATAL); } filename[filename_size++] = '\0'; filename[filename_size++] = '\0'; /* Decoded unicode form is UTF-16BE, so we have to update a string * conversion object for it. */ if (rar->sconv_utf16be == NULL) { rar->sconv_utf16be = archive_string_conversion_from_charset( &a->archive, "UTF-16BE", 1); if (rar->sconv_utf16be == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf16be; strp = filename; while (memcmp(strp, "\x00\x00", 2)) { if (!memcmp(strp, "\x00\\", 2)) *(strp + 1) = '/'; strp += 2; } p += offset; } else { /* * If FHD_UNICODE is set but no unicode data, this file name form * is UTF-8, so we have to update a string conversion object for * it accordingly. */ if (rar->sconv_utf8 == NULL) { rar->sconv_utf8 = archive_string_conversion_from_charset( &a->archive, "UTF-8", 1); if (rar->sconv_utf8 == NULL) return (ARCHIVE_FATAL); } fn_sconv = rar->sconv_utf8; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } } else { fn_sconv = sconv; while ((strp = strchr(filename, '\\')) != NULL) *strp = '/'; p += filename_size; } /* Split file in multivolume RAR. No more need to process header. */ if (rar->filename_save && filename_size == rar->filename_save_size && !memcmp(rar->filename, rar->filename_save, filename_size + 1)) { __archive_read_consume(a, header_size - 7); rar->cursor++; if (rar->cursor >= rar->nodes) { rar->nodes++; if ((rar->dbo = realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[rar->cursor].header_size = header_size; rar->dbo[rar->cursor].start_offset = -1; rar->dbo[rar->cursor].end_offset = -1; } if (rar->dbo[rar->cursor].start_offset < 0) { rar->dbo[rar->cursor].start_offset = a->filter->position; rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset + rar->packed_size; } return ret; } rar->filename_save = (char*)realloc(rar->filename_save, filename_size + 1); memcpy(rar->filename_save, rar->filename, filename_size + 1); rar->filename_save_size = filename_size; /* Set info for seeking */ free(rar->dbo); if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL) { archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory."); return (ARCHIVE_FATAL); } rar->dbo[0].header_size = header_size; rar->dbo[0].start_offset = -1; rar->dbo[0].end_offset = -1; rar->cursor = 0; rar->nodes = 1; if (rar->file_flags & FHD_SALT) { if (p + 8 > endp) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } memcpy(rar->salt, p, 8); p += 8; } if (rar->file_flags & FHD_EXTTIME) { if (read_exttime(p, rar, endp) < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid header size"); return (ARCHIVE_FATAL); } } __archive_read_consume(a, header_size - 7); rar->dbo[0].start_offset = a->filter->position; rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size; switch(file_header.host_os) { case OS_MSDOS: case OS_OS2: case OS_WIN32: rar->mode = archive_le32dec(file_header.file_attr); if (rar->mode & FILE_ATTRIBUTE_DIRECTORY) rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH; else rar->mode = AE_IFREG; rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; break; case OS_UNIX: case OS_MAC_OS: case OS_BEOS: rar->mode = archive_le32dec(file_header.file_attr); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unknown file attributes from RAR file's host OS"); return (ARCHIVE_FATAL); } rar->bytes_uncopied = rar->bytes_unconsumed = 0; rar->lzss.position = rar->offset = 0; rar->offset_seek = 0; rar->dictionary_size = 0; rar->offset_outgoing = 0; rar->br.cache_avail = 0; rar->br.avail_in = 0; rar->crc_calculated = 0; rar->entry_eof = 0; rar->valid = 1; rar->is_ppmd_block = 0; rar->start_new_table = 1; free(rar->unp_buffer); rar->unp_buffer = NULL; rar->unp_offset = 0; rar->unp_buffer_size = UNP_BUFFER_SIZE; memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->ppmd_valid = rar->ppmd_eod = 0; /* Don't set any archive entries for non-file header types */ if (head_type == NEWSUB_HEAD) return ret; archive_entry_set_mtime(entry, rar->mtime, rar->mnsec); archive_entry_set_ctime(entry, rar->ctime, rar->cnsec); archive_entry_set_atime(entry, rar->atime, rar->ansec); archive_entry_set_size(entry, rar->unp_size); archive_entry_set_mode(entry, rar->mode); if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted from %s to current locale.", archive_string_conversion_charset_name(fn_sconv)); ret = (ARCHIVE_WARN); } if (((rar->mode) & AE_IFMT) == AE_IFLNK) { /* Make sure a symbolic-link file does not have its body. */ rar->bytes_remaining = 0; archive_entry_set_size(entry, 0); /* Read a symbolic-link name. */ if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN)) return ret2; if (ret > ret2) ret = ret2; } if (rar->bytes_remaining == 0) rar->entry_eof = 1; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-193'], 'message': 'Avoid a read off-by-one error for UTF16 names in RAR archives. Reported-By: OSS-Fuzz issue 573'</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: ofputil_pull_ofp15_group_mod(struct ofpbuf *msg, enum ofp_version ofp_version, struct ofputil_group_mod *gm) { const struct ofp15_group_mod *ogm; uint16_t bucket_list_len; enum ofperr error = OFPERR_OFPGMFC_BAD_BUCKET; ogm = ofpbuf_pull(msg, sizeof *ogm); gm->command = ntohs(ogm->command); gm->type = ogm->type; gm->group_id = ntohl(ogm->group_id); gm->command_bucket_id = ntohl(ogm->command_bucket_id); switch (gm->command) { case OFPGC15_REMOVE_BUCKET: if (gm->command_bucket_id == OFPG15_BUCKET_ALL) { error = 0; } /* Fall through */ case OFPGC15_INSERT_BUCKET: if (gm->command_bucket_id <= OFPG15_BUCKET_MAX || gm->command_bucket_id == OFPG15_BUCKET_FIRST || gm->command_bucket_id == OFPG15_BUCKET_LAST) { error = 0; } break; case OFPGC11_ADD: case OFPGC11_MODIFY: case OFPGC11_ADD_OR_MOD: case OFPGC11_DELETE: default: if (gm->command_bucket_id == OFPG15_BUCKET_ALL) { error = 0; } break; } if (error) { VLOG_WARN_RL(&bad_ofmsg_rl, "group command bucket id (%u) is out of range", gm->command_bucket_id); return OFPERR_OFPGMFC_BAD_BUCKET; } bucket_list_len = ntohs(ogm->bucket_array_len); if (bucket_list_len > msg->size) { return OFPERR_OFPBRC_BAD_LEN; } error = ofputil_pull_ofp15_buckets(msg, bucket_list_len, ofp_version, gm->type, &gm->buckets); if (error) { return error; } return parse_ofp15_group_properties(msg, gm->type, gm->command, &gm->props, msg->size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'ofp-util: Fix memory leaks when parsing OF1.5 group properties. Found by libFuzzer. Reported-by: Bhargava Shastry <bshastry@sec.t-labs.tu-berlin.de> Signed-off-by: Ben Pfaff <blp@ovn.org> Acked-by: Justin Pettit <jpettit@ovn.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 Image *ReadVIPSImage(const ImageInfo *image_info, ExceptionInfo *exception) { char buffer[MagickPathExtent], *metadata; Image *image; MagickBooleanType status; ssize_t n; unsigned int channels, marker; VIPSBandFormat format; VIPSCoding coding; VIPSType type; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } marker=ReadBlobLSBLong(image); if (marker == VIPS_MAGIC_LSB) image->endian=LSBEndian; else if (marker == VIPS_MAGIC_MSB) image->endian=MSBEndian; else ThrowReaderException(CorruptImageError,"ImproperImageHeader"); image->columns=(size_t) ReadBlobLong(image); image->rows=(size_t) ReadBlobLong(image); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); channels=ReadBlobLong(image); (void) ReadBlobLong(image); /* Legacy */ format=(VIPSBandFormat) ReadBlobLong(image); switch(format) { case VIPSBandFormatUCHAR: case VIPSBandFormatCHAR: image->depth=8; break; case VIPSBandFormatUSHORT: case VIPSBandFormatSHORT: image->depth=16; break; case VIPSBandFormatUINT: case VIPSBandFormatINT: case VIPSBandFormatFLOAT: image->depth=32; break; case VIPSBandFormatDOUBLE: image->depth=64; break; default: case VIPSBandFormatCOMPLEX: case VIPSBandFormatDPCOMPLEX: case VIPSBandFormatNOTSET: ThrowReaderException(CoderError,"Unsupported band format"); } coding=(VIPSCoding) ReadBlobLong(image); type=(VIPSType) ReadBlobLong(image); switch(type) { case VIPSTypeCMYK: SetImageColorspace(image,CMYKColorspace,exception); if (channels == 5) image->alpha_trait=BlendPixelTrait; break; case VIPSTypeB_W: case VIPSTypeGREY16: SetImageColorspace(image,GRAYColorspace,exception); if (channels == 2) image->alpha_trait=BlendPixelTrait; break; case VIPSTypeRGB: case VIPSTypeRGB16: SetImageColorspace(image,RGBColorspace,exception); if (channels == 4) image->alpha_trait=BlendPixelTrait; break; case VIPSTypesRGB: SetImageColorspace(image,sRGBColorspace,exception); if (channels == 4) image->alpha_trait=BlendPixelTrait; break; default: case VIPSTypeFOURIER: case VIPSTypeHISTOGRAM: case VIPSTypeLAB: case VIPSTypeLABS: case VIPSTypeLABQ: case VIPSTypeLCH: case VIPSTypeMULTIBAND: case VIPSTypeUCS: case VIPSTypeXYZ: case VIPSTypeYXY: ThrowReaderException(CoderError,"Unsupported colorspace"); } image->units=PixelsPerCentimeterResolution; image->resolution.x=ReadBlobFloat(image)*10; image->resolution.y=ReadBlobFloat(image)*10; /* Legacy, offsets, future */ (void) ReadBlobLongLong(image); (void) ReadBlobLongLong(image); (void) ReadBlobLongLong(image); if (image_info->ping != MagickFalse) return(image); if (IsSupportedCombination(format,type) == MagickFalse) ThrowReaderException(CoderError, "Unsupported combination of band format and colorspace"); if (channels == 0 || channels > 5) ThrowReaderException(CoderError,"Unsupported number of channels"); if (coding == VIPSCodingNONE) status=ReadVIPSPixelsNONE(image,format,type,channels,exception); else ThrowReaderException(CoderError,"Unsupported coding"); metadata=(char *) NULL; while ((n=ReadBlob(image,MagickPathExtent-1,(unsigned char *) buffer)) != 0) { buffer[n]='\0'; if (metadata == (char *) NULL) metadata=ConstantString(buffer); else (void) ConcatenateString(&metadata,buffer); } if (metadata != (char *) NULL) SetImageProperty(image,"vips:metadata",metadata,exception); (void) CloseBlob(image); if (status == MagickFalse) return((Image *) NULL); return(image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/770'</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 Image *ReadYUVImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *chroma_image, *image, *resize_image; InterlaceType interlace; MagickBooleanType status; register const Quantum *chroma_pixels; register ssize_t x; register Quantum *q; register unsigned char *p; ssize_t count, horizontal_factor, vertical_factor, y; size_t length, quantum; unsigned char *scanline; /* Allocate image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); quantum=(ssize_t) (image->depth <= 8 ? 1 : 2); interlace=image_info->interlace; horizontal_factor=2; vertical_factor=2; if (image_info->sampling_factor != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(image_info->sampling_factor,&geometry_info); horizontal_factor=(ssize_t) geometry_info.rho; vertical_factor=(ssize_t) geometry_info.sigma; if ((flags & SigmaValue) == 0) vertical_factor=horizontal_factor; if ((horizontal_factor != 1) && (horizontal_factor != 2) && (vertical_factor != 1) && (vertical_factor != 2)) ThrowReaderException(CorruptImageError,"UnexpectedSamplingFactor"); } if ((interlace == UndefinedInterlace) || ((interlace == NoInterlace) && (vertical_factor == 2))) { interlace=NoInterlace; /* CCIR 4:2:2 */ if (vertical_factor == 2) interlace=PlaneInterlace; /* CCIR 4:1:1 */ } if (interlace != PartitionInterlace) { /* Open image file. */ status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Allocate memory for a scanline. */ if (interlace == NoInterlace) scanline=(unsigned char *) AcquireQuantumMemory((size_t) (2UL* image->columns+2UL),(size_t) quantum*sizeof(*scanline)); else scanline=(unsigned char *) AcquireQuantumMemory(image->columns, (size_t) quantum*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); status=MagickTrue; do { chroma_image=CloneImage(image,(image->columns+horizontal_factor-1)/ horizontal_factor,(image->rows+vertical_factor-1)/vertical_factor, MagickTrue,exception); if (chroma_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Convert raster image to pixel packets. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; if (interlace == PartitionInterlace) { AppendImageFormat("Y",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } } for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *chroma_pixels; if (interlace == NoInterlace) { if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL)) { length=2*quantum*image->columns; count=ReadBlob(image,length,scanline); if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } p=scanline; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; chroma_pixels=QueueAuthenticPixels(chroma_image,0,y, chroma_image->columns,1,exception); if (chroma_pixels == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x+=2) { SetPixelRed(chroma_image,0,chroma_pixels); if (quantum == 1) SetPixelGreen(chroma_image,ScaleCharToQuantum(*p++), chroma_pixels); else { SetPixelGreen(chroma_image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),chroma_pixels); p+=2; } if (quantum == 1) SetPixelRed(image,ScaleCharToQuantum(*p++),q); else { SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q); p+=2; } SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); q+=GetPixelChannels(image); SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); if (quantum == 1) SetPixelBlue(chroma_image,ScaleCharToQuantum(*p++),chroma_pixels); else { SetPixelBlue(chroma_image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),chroma_pixels); p+=2; } if (quantum == 1) SetPixelRed(image,ScaleCharToQuantum(*p++),q); else { SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q); p+=2; } chroma_pixels+=GetPixelChannels(chroma_image); q+=GetPixelChannels(image); } } else { if ((y > 0) || (GetPreviousImageInList(image) == (Image *) NULL)) { length=quantum*image->columns; count=ReadBlob(image,length,scanline); if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } p=scanline; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (quantum == 1) SetPixelRed(image,ScaleCharToQuantum(*p++),q); else { SetPixelRed(image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q); p+=2; } SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); q+=GetPixelChannels(image); } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (interlace == NoInterlace) if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (interlace == PartitionInterlace) { (void) CloseBlob(image); AppendImageFormat("U",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } } if (interlace != NoInterlace) { for (y=0; y < (ssize_t) chroma_image->rows; y++) { length=quantum*chroma_image->columns; count=ReadBlob(image,length,scanline); if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } p=scanline; q=QueueAuthenticPixels(chroma_image,0,y,chroma_image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) chroma_image->columns; x++) { SetPixelRed(chroma_image,0,q); if (quantum == 1) SetPixelGreen(chroma_image,ScaleCharToQuantum(*p++),q); else { SetPixelGreen(chroma_image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q); p+=2; } SetPixelBlue(chroma_image,0,q); q+=GetPixelChannels(chroma_image); } if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse) break; } if (interlace == PartitionInterlace) { (void) CloseBlob(image); AppendImageFormat("V",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } } for (y=0; y < (ssize_t) chroma_image->rows; y++) { length=quantum*chroma_image->columns; count=ReadBlob(image,length,scanline); if (count != (ssize_t) length) { status=MagickFalse; ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } p=scanline; q=GetAuthenticPixels(chroma_image,0,y,chroma_image->columns,1, exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) chroma_image->columns; x++) { if (quantum == 1) SetPixelBlue(chroma_image,ScaleCharToQuantum(*p++),q); else { SetPixelBlue(chroma_image,ScaleShortToQuantum(((*p) << 8) | *(p+1)),q); p+=2; } q+=GetPixelChannels(chroma_image); } if (SyncAuthenticPixels(chroma_image,exception) == MagickFalse) break; } } /* Scale image. */ resize_image=ResizeImage(chroma_image,image->columns,image->rows, TriangleFilter,exception); chroma_image=DestroyImage(chroma_image); if (resize_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); chroma_pixels=GetVirtualPixels(resize_image,0,y,resize_image->columns,1, exception); if ((q == (Quantum *) NULL) || (chroma_pixels == (const Quantum *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(image,GetPixelGreen(resize_image,chroma_pixels),q); SetPixelBlue(image,GetPixelBlue(resize_image,chroma_pixels),q); chroma_pixels+=GetPixelChannels(resize_image); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } resize_image=DestroyImage(resize_image); if (SetImageColorspace(image,YCbCrColorspace,exception) == MagickFalse) break; if (interlace == PartitionInterlace) (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (interlace == NoInterlace) count=ReadBlob(image,(size_t) (2*quantum*image->columns),scanline); else count=ReadBlob(image,(size_t) quantum*image->columns,scanline); if (count != 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (count != 0); scanline=(unsigned char *) RelinquishMagickMemory(scanline); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-772'], 'message': 'fix multiple memory leak in ReadYUVImage'</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: xmlMemStrdupLoc(const char *str, const char *file, int line) { char *s; size_t size = strlen(str) + 1; MEMHDR *p; if (!xmlMemInitialized) xmlInitMemory(); TEST_POINT p = (MEMHDR *) malloc(RESERVE_SIZE+size); if (!p) { goto error; } p->mh_tag = MEMTAG; p->mh_size = size; p->mh_type = STRDUP_TYPE; p->mh_file = file; p->mh_line = line; xmlMutexLock(xmlMemMutex); p->mh_number = ++block; debugMemSize += size; debugMemBlocks++; if (debugMemSize > debugMaxMemSize) debugMaxMemSize = debugMemSize; #ifdef MEM_LIST debugmem_list_add(p); #endif xmlMutexUnlock(xmlMemMutex); s = (char *) HDR_2_CLIENT(p); if (xmlMemStopAtBlock == p->mh_number) xmlMallocBreakpoint(); strcpy(s,str); TEST_POINT if (xmlMemTraceBlockAt == s) { xmlGenericError(xmlGenericErrorContext, "%p : Strdup() Ok\n", xmlMemTraceBlockAt); xmlMallocBreakpoint(); } return(s); error: return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Check for integer overflow in memory debug code Fixes bug 783026. Thanks to Pranjal Jumde for the report.'</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 fanout_add(struct sock *sk, u16 id, u16 type_flags) { struct packet_rollover *rollover = NULL; struct packet_sock *po = pkt_sk(sk); struct packet_fanout *f, *match; u8 type = type_flags & 0xff; u8 flags = type_flags >> 8; int err; switch (type) { case PACKET_FANOUT_ROLLOVER: if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER) return -EINVAL; case PACKET_FANOUT_HASH: case PACKET_FANOUT_LB: case PACKET_FANOUT_CPU: case PACKET_FANOUT_RND: case PACKET_FANOUT_QM: case PACKET_FANOUT_CBPF: case PACKET_FANOUT_EBPF: break; default: return -EINVAL; } mutex_lock(&fanout_mutex); err = -EINVAL; if (!po->running) goto out; err = -EALREADY; if (po->fanout) goto out; if (type == PACKET_FANOUT_ROLLOVER || (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) { err = -ENOMEM; rollover = kzalloc(sizeof(*rollover), GFP_KERNEL); if (!rollover) goto out; atomic_long_set(&rollover->num, 0); atomic_long_set(&rollover->num_huge, 0); atomic_long_set(&rollover->num_failed, 0); po->rollover = rollover; } match = NULL; list_for_each_entry(f, &fanout_list, list) { if (f->id == id && read_pnet(&f->net) == sock_net(sk)) { match = f; break; } } err = -EINVAL; if (match && match->flags != flags) goto out; if (!match) { err = -ENOMEM; match = kzalloc(sizeof(*match), GFP_KERNEL); if (!match) goto out; write_pnet(&match->net, sock_net(sk)); match->id = id; match->type = type; match->flags = flags; INIT_LIST_HEAD(&match->list); spin_lock_init(&match->lock); atomic_set(&match->sk_ref, 0); fanout_init_data(match); match->prot_hook.type = po->prot_hook.type; match->prot_hook.dev = po->prot_hook.dev; match->prot_hook.func = packet_rcv_fanout; match->prot_hook.af_packet_priv = match; match->prot_hook.id_match = match_fanout_group; dev_add_pack(&match->prot_hook); list_add(&match->list, &fanout_list); } err = -EINVAL; if (match->type == type && match->prot_hook.type == po->prot_hook.type && match->prot_hook.dev == po->prot_hook.dev) { err = -ENOSPC; if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) { __dev_remove_pack(&po->prot_hook); po->fanout = match; atomic_inc(&match->sk_ref); __fanout_link(sk, po); err = 0; } } out: if (err && rollover) { kfree(rollover); po->rollover = NULL; } mutex_unlock(&fanout_mutex); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'packet: Do not call fanout_release from atomic contexts Commit 6664498280cf ("packet: call fanout_release, while UNREGISTERING a netdev"), unfortunately, introduced the following issues. 1. calling mutex_lock(&fanout_mutex) (fanout_release()) from inside rcu_read-side critical section. rcu_read_lock disables preemption, most often, which prohibits calling sleeping functions. [ ] include/linux/rcupdate.h:560 Illegal context switch in RCU read-side critical section! [ ] [ ] rcu_scheduler_active = 1, debug_locks = 0 [ ] 4 locks held by ovs-vswitchd/1969: [ ] #0: (cb_lock){++++++}, at: [<ffffffff8158a6c9>] genl_rcv+0x19/0x40 [ ] #1: (ovs_mutex){+.+.+.}, at: [<ffffffffa04878ca>] ovs_vport_cmd_del+0x4a/0x100 [openvswitch] [ ] #2: (rtnl_mutex){+.+.+.}, at: [<ffffffff81564157>] rtnl_lock+0x17/0x20 [ ] #3: (rcu_read_lock){......}, at: [<ffffffff81614165>] packet_notifier+0x5/0x3f0 [ ] [ ] Call Trace: [ ] [<ffffffff813770c1>] dump_stack+0x85/0xc4 [ ] [<ffffffff810c9077>] lockdep_rcu_suspicious+0x107/0x110 [ ] [<ffffffff810a2da7>] ___might_sleep+0x57/0x210 [ ] [<ffffffff810a2fd0>] __might_sleep+0x70/0x90 [ ] [<ffffffff8162e80c>] mutex_lock_nested+0x3c/0x3a0 [ ] [<ffffffff810de93f>] ? vprintk_default+0x1f/0x30 [ ] [<ffffffff81186e88>] ? printk+0x4d/0x4f [ ] [<ffffffff816106dd>] fanout_release+0x1d/0xe0 [ ] [<ffffffff81614459>] packet_notifier+0x2f9/0x3f0 2. calling mutex_lock(&fanout_mutex) inside spin_lock(&po->bind_lock). "sleeping function called from invalid context" [ ] BUG: sleeping function called from invalid context at kernel/locking/mutex.c:620 [ ] in_atomic(): 1, irqs_disabled(): 0, pid: 1969, name: ovs-vswitchd [ ] INFO: lockdep is turned off. [ ] Call Trace: [ ] [<ffffffff813770c1>] dump_stack+0x85/0xc4 [ ] [<ffffffff810a2f52>] ___might_sleep+0x202/0x210 [ ] [<ffffffff810a2fd0>] __might_sleep+0x70/0x90 [ ] [<ffffffff8162e80c>] mutex_lock_nested+0x3c/0x3a0 [ ] [<ffffffff816106dd>] fanout_release+0x1d/0xe0 [ ] [<ffffffff81614459>] packet_notifier+0x2f9/0x3f0 3. calling dev_remove_pack(&fanout->prot_hook), from inside spin_lock(&po->bind_lock) or rcu_read-side critical-section. dev_remove_pack() -> synchronize_net(), which might sleep. [ ] BUG: scheduling while atomic: ovs-vswitchd/1969/0x00000002 [ ] INFO: lockdep is turned off. [ ] Call Trace: [ ] [<ffffffff813770c1>] dump_stack+0x85/0xc4 [ ] [<ffffffff81186274>] __schedule_bug+0x64/0x73 [ ] [<ffffffff8162b8cb>] __schedule+0x6b/0xd10 [ ] [<ffffffff8162c5db>] schedule+0x6b/0x80 [ ] [<ffffffff81630b1d>] schedule_timeout+0x38d/0x410 [ ] [<ffffffff810ea3fd>] synchronize_sched_expedited+0x53d/0x810 [ ] [<ffffffff810ea6de>] synchronize_rcu_expedited+0xe/0x10 [ ] [<ffffffff8154eab5>] synchronize_net+0x35/0x50 [ ] [<ffffffff8154eae3>] dev_remove_pack+0x13/0x20 [ ] [<ffffffff8161077e>] fanout_release+0xbe/0xe0 [ ] [<ffffffff81614459>] packet_notifier+0x2f9/0x3f0 4. fanout_release() races with calls from different CPU. To fix the above problems, remove the call to fanout_release() under rcu_read_lock(). Instead, call __dev_remove_pack(&fanout->prot_hook) and netdev_run_todo will be happy that &dev->ptype_specific list is empty. In order to achieve this, I moved dev_{add,remove}_pack() out of fanout_{add,release} to __fanout_{link,unlink}. So, call to {,__}unregister_prot_hook() will make sure fanout->prot_hook is removed as well. Fixes: 6664498280cf ("packet: call fanout_release, while UNREGISTERING a netdev") Reported-by: Eric Dumazet <edumazet@google.com> Signed-off-by: Anoob Soman <anoob.soman@citrix.com> Acked-by: Eric Dumazet <edumazet@google.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 key_update(key_ref_t key_ref, const void *payload, size_t plen) { struct key_preparsed_payload prep; struct key *key = key_ref_to_ptr(key_ref); int ret; key_check(key); /* the key must be writable */ ret = key_permission(key_ref, KEY_NEED_WRITE); if (ret < 0) return ret; /* attempt to update it if supported */ if (!key->type->update) return -EOPNOTSUPP; memset(&prep, 0, sizeof(prep)); prep.data = payload; prep.datalen = plen; prep.quotalen = key->type->def_datalen; prep.expiry = TIME_T_MAX; if (key->type->preparse) { ret = key->type->preparse(&prep); if (ret < 0) goto error; } down_write(&key->sem); ret = key->type->update(key, &prep); if (ret == 0) /* updating a negative key instantiates it */ clear_bit(KEY_FLAG_NEGATIVE, &key->flags); up_write(&key->sem); error: if (key->type->preparse) key->type->free_preparse(&prep); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: stable@vger.kernel.org # v4.4+ Reported-by: Eric Biggers <ebiggers@google.com> Signed-off-by: David Howells <dhowells@redhat.com> Reviewed-by: Eric Biggers <ebiggers@google.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 key_reject_and_link(struct key *key, unsigned timeout, unsigned error, struct key *keyring, struct key *authkey) { struct assoc_array_edit *edit; struct timespec now; int ret, awaken, link_ret = 0; key_check(key); key_check(keyring); awaken = 0; ret = -EBUSY; if (keyring) { if (keyring->restrict_link) return -EPERM; link_ret = __key_link_begin(keyring, &key->index_key, &edit); } mutex_lock(&key_construction_mutex); /* can't instantiate twice */ if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { /* mark the key as being negatively instantiated */ atomic_inc(&key->user->nikeys); key->reject_error = -error; smp_wmb(); set_bit(KEY_FLAG_NEGATIVE, &key->flags); set_bit(KEY_FLAG_INSTANTIATED, &key->flags); now = current_kernel_time(); key->expiry = now.tv_sec + timeout; key_schedule_gc(key->expiry + key_gc_delay); if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) awaken = 1; ret = 0; /* and link it into the destination keyring */ if (keyring && link_ret == 0) __key_link(key, &edit); /* disable the authorisation key */ if (authkey) key_revoke(authkey); } mutex_unlock(&key_construction_mutex); if (keyring && link_ret == 0) __key_link_end(keyring, &key->index_key, edit); /* wake up anyone waiting for a key to be constructed */ if (awaken) wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT); return ret == 0 ? link_ret : ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: stable@vger.kernel.org # v4.4+ Reported-by: Eric Biggers <ebiggers@google.com> Signed-off-by: David Howells <dhowells@redhat.com> Reviewed-by: Eric Biggers <ebiggers@google.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: aspath_put (struct stream *s, struct aspath *as, int use32bit ) { struct assegment *seg = as->segments; size_t bytes = 0; if (!seg || seg->length == 0) return 0; if (seg) { /* * Hey, what do we do when we have > STREAM_WRITABLE(s) here? * At the moment, we would write out a partial aspath, and our peer * will complain and drop the session :-/ * * The general assumption here is that many things tested will * never happen. And, in real live, up to now, they have not. */ while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s))) { struct assegment *next = seg->next; int written = 0; int asns_packed = 0; size_t lenp; /* Overlength segments have to be split up */ while ( (seg->length - written) > AS_SEGMENT_MAX) { assegment_header_put (s, seg->type, AS_SEGMENT_MAX); assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit); written += AS_SEGMENT_MAX; bytes += ASSEGMENT_SIZE (written, use32bit); } /* write the final segment, probably is also the first */ lenp = assegment_header_put (s, seg->type, seg->length - written); assegment_data_put (s, (seg->as + written), seg->length - written, use32bit); /* Sequence-type segments can be 'packed' together * Case of a segment which was overlength and split up * will be missed here, but that doesn't matter. */ while (next && ASSEGMENTS_PACKABLE (seg, next)) { /* NB: We should never normally get here given we * normalise aspath data when parse them. However, better * safe than sorry. We potentially could call * assegment_normalise here instead, but it's cheaper and * easier to do it on the fly here rather than go through * the segment list twice every time we write out * aspath's. */ /* Next segment's data can fit in this one */ assegment_data_put (s, next->as, next->length, use32bit); /* update the length of the segment header */ stream_putc_at (s, lenp, seg->length - written + next->length); asns_packed += next->length; next = next->next; } bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed, use32bit); seg = next; } } return bytes; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'bgpd: Fix AS_PATH size calculation for long paths If you have an AS_PATH with more entries than what can be written into a single AS_SEGMENT_MAX it needs to be broken up. The code that noticed that the AS_PATH needs to be broken up was not correctly calculating the size of the resulting message. This patch addresses this issue.'</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 cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr, struct usb_interface *intf, u8 *buffer, int buflen) { /* duplicates are ignored */ struct usb_cdc_union_desc *union_header = NULL; /* duplicates are not tolerated */ struct usb_cdc_header_desc *header = NULL; struct usb_cdc_ether_desc *ether = NULL; struct usb_cdc_mdlm_detail_desc *detail = NULL; struct usb_cdc_mdlm_desc *desc = NULL; unsigned int elength; int cnt = 0; memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header)); hdr->phonet_magic_present = false; while (buflen > 0) { elength = buffer[0]; if (!elength) { dev_err(&intf->dev, "skipping garbage byte\n"); elength = 1; goto next_desc; } if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, "skipping garbage\n"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (elength < sizeof(struct usb_cdc_union_desc)) goto next_desc; if (union_header) { dev_err(&intf->dev, "More than one union descriptor, skipping ...\n"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: if (elength < sizeof(struct usb_cdc_country_functional_desc)) goto next_desc; hdr->usb_cdc_country_functional_desc = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: if (elength != sizeof(struct usb_cdc_header_desc)) goto next_desc; if (header) return -EINVAL; header = (struct usb_cdc_header_desc *)buffer; break; case USB_CDC_ACM_TYPE: if (elength < sizeof(struct usb_cdc_acm_descriptor)) goto next_desc; hdr->usb_cdc_acm_descriptor = (struct usb_cdc_acm_descriptor *)buffer; break; case USB_CDC_ETHERNET_TYPE: if (elength != sizeof(struct usb_cdc_ether_desc)) goto next_desc; if (ether) return -EINVAL; ether = (struct usb_cdc_ether_desc *)buffer; break; case USB_CDC_CALL_MANAGEMENT_TYPE: if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor)) goto next_desc; hdr->usb_cdc_call_mgmt_descriptor = (struct usb_cdc_call_mgmt_descriptor *)buffer; break; case USB_CDC_DMM_TYPE: if (elength < sizeof(struct usb_cdc_dmm_desc)) goto next_desc; hdr->usb_cdc_dmm_desc = (struct usb_cdc_dmm_desc *)buffer; break; case USB_CDC_MDLM_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_desc *)) goto next_desc; if (desc) return -EINVAL; desc = (struct usb_cdc_mdlm_desc *)buffer; break; case USB_CDC_MDLM_DETAIL_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *)) goto next_desc; if (detail) return -EINVAL; detail = (struct usb_cdc_mdlm_detail_desc *)buffer; break; case USB_CDC_NCM_TYPE: if (elength < sizeof(struct usb_cdc_ncm_desc)) goto next_desc; hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer; break; case USB_CDC_MBIM_TYPE: if (elength < sizeof(struct usb_cdc_mbim_desc)) goto next_desc; hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer; break; case USB_CDC_MBIM_EXTENDED_TYPE: if (elength < sizeof(struct usb_cdc_mbim_extended_desc)) break; hdr->usb_cdc_mbim_extended_desc = (struct usb_cdc_mbim_extended_desc *)buffer; break; case CDC_PHONET_MAGIC_NUMBER: hdr->phonet_magic_present = true; break; default: /* * there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n", buffer[2], elength); goto next_desc; } cnt++; next_desc: buflen -= elength; buffer += elength; } hdr->usb_cdc_union_desc = union_header; hdr->usb_cdc_header_desc = header; hdr->usb_cdc_mdlm_detail_desc = detail; hdr->usb_cdc_mdlm_desc = desc; hdr->usb_cdc_ether_desc = ether; return cnt; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'USB: core: harden cdc_parse_cdc_header Andrey Konovalov reported a possible out-of-bounds problem for the cdc_parse_cdc_header function. He writes: It looks like cdc_parse_cdc_header() doesn't validate buflen before accessing buffer[1], buffer[2] and so on. The only check present is while (buflen > 0). So fix this issue up by properly validating the buffer length matches what the descriptor says it is. Reported-by: Andrey Konovalov <andreyknvl@google.com> Tested-by: Andrey Konovalov <andreyknvl@google.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.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 uas_switch_interface(struct usb_device *udev, struct usb_interface *intf) { int alt; alt = uas_find_uas_alt_setting(intf); if (alt < 0) return alt; return usb_set_interface(udev, intf->altsetting[0].desc.bInterfaceNumber, alt); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'USB: uas: fix bug in handling of alternate settings The uas driver has a subtle bug in the way it handles alternate settings. The uas_find_uas_alt_setting() routine returns an altsetting value (the bAlternateSetting number in the descriptor), but uas_use_uas_driver() then treats that value as an index to the intf->altsetting array, which it isn't. Normally this doesn't cause any problems because the various alternate settings have bAlternateSetting values 0, 1, 2, ..., so the value is equal to the index in the array. But this is not guaranteed, and Andrey Konovalov used the syzkaller fuzzer with KASAN to get a slab-out-of-bounds error by violating this assumption. This patch fixes the bug by making uas_find_uas_alt_setting() return a pointer to the altsetting entry rather than either the value or the index. Pointers are less subject to misinterpretation. Signed-off-by: Alan Stern <stern@rowland.harvard.edu> Reported-by: Andrey Konovalov <andreyknvl@google.com> Tested-by: Andrey Konovalov <andreyknvl@google.com> CC: Oliver Neukum <oneukum@suse.com> CC: <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.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 char *theme_format_compress_colors(THEME_REC *theme, const char *format) { GString *str; char *ret; char last_fg, last_bg; str = g_string_new(NULL); last_fg = last_bg = '\0'; while (*format != '\0') { if (*format == '$') { /* $variable, skrip it entirely */ theme_format_append_variable(str, &format); last_fg = last_bg = '\0'; } else if (*format != '%') { /* a normal character */ g_string_append_c(str, *format); format++; } else { /* %format */ format++; if (IS_OLD_FORMAT(*format, last_fg, last_bg)) { /* active color set again */ } else if (IS_FGCOLOR_FORMAT(*format) && format[1] == '%' && IS_FGCOLOR_FORMAT(format[2]) && (*format != 'n' || format[2] == 'n')) { /* two fg colors in a row. bg colors are so rare that we don't bother checking them */ } else { /* some format, add it */ g_string_append_c(str, '%'); g_string_append_c(str, *format); if (IS_FGCOLOR_FORMAT(*format)) last_fg = *format; else if (*format == 'Z' || *format == 'X') last_fg = '\0'; if (IS_BGCOLOR_FORMAT(*format)) last_bg = *format; else if (*format == 'z' || *format == 'x') last_bg = '\0'; } format++; } } ret = str->str; g_string_free(str, FALSE); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Merge branch 'security' into 'master' Security Closes GL#12, GL#13, GL#14, GL#15, GL#16 See merge request irssi/irssi!23'</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: ldns_rdf_new_frm_str(ldns_rdf_type type, const char *str) { ldns_rdf *rdf = NULL; ldns_status status; switch (type) { case LDNS_RDF_TYPE_DNAME: status = ldns_str2rdf_dname(&rdf, str); break; case LDNS_RDF_TYPE_INT8: status = ldns_str2rdf_int8(&rdf, str); break; case LDNS_RDF_TYPE_INT16: status = ldns_str2rdf_int16(&rdf, str); break; case LDNS_RDF_TYPE_INT32: status = ldns_str2rdf_int32(&rdf, str); break; case LDNS_RDF_TYPE_A: status = ldns_str2rdf_a(&rdf, str); break; case LDNS_RDF_TYPE_AAAA: status = ldns_str2rdf_aaaa(&rdf, str); break; case LDNS_RDF_TYPE_STR: status = ldns_str2rdf_str(&rdf, str); break; case LDNS_RDF_TYPE_APL: status = ldns_str2rdf_apl(&rdf, str); break; case LDNS_RDF_TYPE_B64: status = ldns_str2rdf_b64(&rdf, str); break; case LDNS_RDF_TYPE_B32_EXT: status = ldns_str2rdf_b32_ext(&rdf, str); break; case LDNS_RDF_TYPE_HEX: status = ldns_str2rdf_hex(&rdf, str); break; case LDNS_RDF_TYPE_NSEC: status = ldns_str2rdf_nsec(&rdf, str); break; case LDNS_RDF_TYPE_TYPE: status = ldns_str2rdf_type(&rdf, str); break; case LDNS_RDF_TYPE_CLASS: status = ldns_str2rdf_class(&rdf, str); break; case LDNS_RDF_TYPE_CERT_ALG: status = ldns_str2rdf_cert_alg(&rdf, str); break; case LDNS_RDF_TYPE_ALG: status = ldns_str2rdf_alg(&rdf, str); break; case LDNS_RDF_TYPE_UNKNOWN: status = ldns_str2rdf_unknown(&rdf, str); break; case LDNS_RDF_TYPE_TIME: status = ldns_str2rdf_time(&rdf, str); break; case LDNS_RDF_TYPE_PERIOD: status = ldns_str2rdf_period(&rdf, str); break; case LDNS_RDF_TYPE_TSIG: status = ldns_str2rdf_tsig(&rdf, str); break; case LDNS_RDF_TYPE_SERVICE: status = ldns_str2rdf_service(&rdf, str); break; case LDNS_RDF_TYPE_LOC: status = ldns_str2rdf_loc(&rdf, str); break; case LDNS_RDF_TYPE_WKS: status = ldns_str2rdf_wks(&rdf, str); break; case LDNS_RDF_TYPE_NSAP: status = ldns_str2rdf_nsap(&rdf, str); break; case LDNS_RDF_TYPE_ATMA: status = ldns_str2rdf_atma(&rdf, str); break; case LDNS_RDF_TYPE_IPSECKEY: status = ldns_str2rdf_ipseckey(&rdf, str); break; case LDNS_RDF_TYPE_NSEC3_SALT: status = ldns_str2rdf_nsec3_salt(&rdf, str); break; case LDNS_RDF_TYPE_NSEC3_NEXT_OWNER: status = ldns_str2rdf_b32_ext(&rdf, str); break; case LDNS_RDF_TYPE_ILNP64: status = ldns_str2rdf_ilnp64(&rdf, str); break; case LDNS_RDF_TYPE_EUI48: status = ldns_str2rdf_eui48(&rdf, str); break; case LDNS_RDF_TYPE_EUI64: status = ldns_str2rdf_eui64(&rdf, str); break; case LDNS_RDF_TYPE_NONE: default: /* default default ??? */ status = LDNS_STATUS_ERR; break; } if (LDNS_STATUS_OK == status) { ldns_rdf_set_type(rdf, type); return rdf; } if (rdf) { LDNS_FREE(rdf); } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'CAA and URI'</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: SpawnPreparationInfo prepareSpawn(const Options &options) { TRACE_POINT(); SpawnPreparationInfo info; prepareChroot(info, options); info.userSwitching = prepareUserSwitching(options); prepareSwitchingWorkingDirectory(info, options); inferApplicationInfo(info); return info; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-61'], 'message': 'Disable unused feature.'</s>