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: int __get_user_pages_fast(unsigned long start, int nr_pages, int write, struct page **pages) { unsigned long len, end; unsigned long flags; int nr_pinned = 0; /* * Internally (within mm/gup.c), gup fast variants must set FOLL_GET, * because gup fast is always a "pin with a +1 page refcount" request. */ unsigned int gup_flags = FOLL_GET; if (write) gup_flags |= FOLL_WRITE; start = untagged_addr(start) & PAGE_MASK; len = (unsigned long) nr_pages << PAGE_SHIFT; end = start + len; if (end <= start) return 0; if (unlikely(!access_ok((void __user *)start, len))) return 0; /* * Disable interrupts. We use the nested form as we can already have * interrupts disabled by get_futex_key. * * With interrupts disabled, we block page table pages from being * freed from under us. See struct mmu_table_batch comments in * include/asm-generic/tlb.h for more details. * * We do not adopt an rcu_read_lock(.) here as we also want to * block IPIs that come from THPs splitting. */ if (IS_ENABLED(CONFIG_HAVE_FAST_GUP) && gup_fast_permitted(start, end)) { local_irq_save(flags); gup_pgd_range(start, end, gup_flags, pages, &nr_pinned); local_irq_restore(flags); } return nr_pinned; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'gup: document and work around "COW can break either way" issue Doing a "get_user_pages()" on a copy-on-write page for reading can be ambiguous: the page can be COW'ed at any time afterwards, and the direction of a COW event isn't defined. Yes, whoever writes to it will generally do the COW, but if the thread that did the get_user_pages() unmapped the page before the write (and that could happen due to memory pressure in addition to any outright action), the writer could also just take over the old page instead. End result: the get_user_pages() call might result in a page pointer that is no longer associated with the original VM, and is associated with - and controlled by - another VM having taken it over instead. So when doing a get_user_pages() on a COW mapping, the only really safe thing to do would be to break the COW when getting the page, even when only getting it for reading. At the same time, some users simply don't even care. For example, the perf code wants to look up the page not because it cares about the page, but because the code simply wants to look up the physical address of the access for informational purposes, and doesn't really care about races when a page might be unmapped and remapped elsewhere. This adds logic to force a COW event by setting FOLL_WRITE on any copy-on-write mapping when FOLL_GET (or FOLL_PIN) is used to get a page pointer as a result. The current semantics end up being: - __get_user_pages_fast(): no change. If you don't ask for a write, you won't break COW. You'd better know what you're doing. - get_user_pages_fast(): the fast-case "look it up in the page tables without anything getting mmap_sem" now refuses to follow a read-only page, since it might need COW breaking. Which happens in the slow path - the fast path doesn't know if the memory might be COW or not. - get_user_pages() (including the slow-path fallback for gup_fast()): for a COW mapping, turn on FOLL_WRITE for FOLL_GET/FOLL_PIN, with very similar semantics to FOLL_FORCE. If it turns out that we want finer granularity (ie "only break COW when it might actually matter" - things like the zero page are special and don't need to be broken) we might need to push these semantics deeper into the lookup fault path. So if people care enough, it's possible that we might end up adding a new internal FOLL_BREAK_COW flag to go with the internal FOLL_COW flag we already have for tracking "I had a COW". Alternatively, if it turns out that different callers might want to explicitly control the forced COW break behavior, we might even want to make such a flag visible to the users of get_user_pages() instead of using the above default semantics. But for now, this is mostly commentary on the issue (this commit message being a lot bigger than the patch, and that patch in turn is almost all comments), with that minimal "enable COW breaking early" logic using the existing FOLL_WRITE behavior. [ It might be worth noting that we've always had this ambiguity, and it could arguably be seen as a user-space issue. You only get private COW mappings that could break either way in situations where user space is doing cooperative things (ie fork() before an execve() etc), but it _is_ surprising and very subtle, and fork() is supposed to give you independent address spaces. So let's treat this as a kernel issue and make the semantics of get_user_pages() easier to understand. Note that obviously a true shared mapping will still get a page that can change under us, so this does _not_ mean that get_user_pages() somehow returns any "stable" page ] Reported-by: Jann Horn <jannh@google.com> Tested-by: Christoph Hellwig <hch@lst.de> Acked-by: Oleg Nesterov <oleg@redhat.com> Acked-by: Kirill Shutemov <kirill@shutemov.name> Acked-by: Jan Kara <jack@suse.cz> Cc: Andrea Arcangeli <aarcange@redhat.com> Cc: Matthew Wilcox <willy@infradead.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: bucket_insert (index_bucket *bucket, CK_OBJECT_HANDLE handle) { unsigned int alloc; int at = 0; if (bucket->elem) { at = binary_search (bucket->elem, 0, bucket->num, handle); if (at < bucket->num && bucket->elem[at] == handle) return; } alloc = alloc_size (bucket->num); if (bucket->num + 1 > alloc) { CK_OBJECT_HANDLE *elem; alloc = alloc ? alloc * 2 : 1; return_if_fail (alloc != 0); elem = realloc (bucket->elem, alloc * sizeof (CK_OBJECT_HANDLE)); return_if_fail (elem != NULL); bucket->elem = elem; } return_if_fail (bucket->elem != NULL); memmove (bucket->elem + at + 1, bucket->elem + at, (bucket->num - at) * sizeof (CK_OBJECT_HANDLE)); bucket->elem[at] = handle; bucket->num++; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Check for arithmetic overflows before allocating'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: session_worker_child_watch (GPid pid, int status, GdmSessionWorker *worker) { g_debug ("GdmSessionWorker: child (pid:%d) done (%s:%d)", (int) pid, WIFEXITED (status) ? "status" : WIFSIGNALED (status) ? "signal" : "unknown", WIFEXITED (status) ? WEXITSTATUS (status) : WIFSIGNALED (status) ? WTERMSIG (status) : -1); gdm_session_worker_uninitialize_pam (worker, PAM_SUCCESS); gdm_dbus_worker_emit_session_exited (GDM_DBUS_WORKER (worker), worker->priv->service, status); killpg (pid, SIGHUP); worker->priv->child_pid = -1; worker->priv->child_watch_id = 0; run_script (worker, GDMCONFDIR "/PostSession"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'session-worker: Don't switch back VTs until session is fully exited There's a race condition on shutdown where the session worker is switching VTs back to the initial VT at the same time as the session exit is being processed. This means that manager may try to start a login screen (because of the VT switch) when autologin is enabled when there shouldn't be a login screen. This commit makes sure both the PostSession script, and session-exited signal emission are complete before initiating the VT switch back to the initial VT. https://gitlab.gnome.org/GNOME/gdm/-/issues/660'</s>
<s>[INST] Given the following code containing errors, provide 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_pi_iterator_t * opj_pi_create(const opj_image_t *image, const opj_cp_t *cp, OPJ_UINT32 tileno) { /* loop*/ OPJ_UINT32 pino, compno; /* number of poc in the p_pi*/ OPJ_UINT32 l_poc_bound; /* pointers to tile coding parameters and components.*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *tcp = 00; const opj_tccp_t *tccp = 00; /* current packet iterator being allocated*/ opj_pi_iterator_t *l_current_pi = 00; /* preconditions in debug*/ assert(cp != 00); assert(image != 00); assert(tileno < cp->tw * cp->th); /* initializations*/ tcp = &cp->tcps[tileno]; l_poc_bound = tcp->numpocs + 1; /* memory allocations*/ l_pi = (opj_pi_iterator_t*) opj_calloc((l_poc_bound), sizeof(opj_pi_iterator_t)); if (!l_pi) { return NULL; } l_current_pi = l_pi; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_pi->comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (! l_current_pi->comps) { opj_pi_destroy(l_pi, l_poc_bound); return NULL; } l_current_pi->numcomps = image->numcomps; for (compno = 0; compno < image->numcomps; ++compno) { opj_pi_comp_t *comp = &l_current_pi->comps[compno]; tccp = &tcp->tccps[compno]; comp->resolutions = (opj_pi_resolution_t*) opj_calloc(tccp->numresolutions, sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { opj_pi_destroy(l_pi, l_poc_bound); return 00; } comp->numresolutions = tccp->numresolutions; } ++l_current_pi; } return l_pi; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-122'], 'message': 'pi.c: avoid out of bounds access with POC (refs https://github.com/uclouvain/openjpeg/issues/1293#issuecomment-737122836)'</s>
<s>[INST] Given the following code containing errors, provide 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_UINT32 opj_j2k_get_specific_header_sizes(opj_j2k_t *p_j2k) { OPJ_UINT32 l_nb_bytes = 0; OPJ_UINT32 l_nb_comps; OPJ_UINT32 l_coc_bytes, l_qcc_bytes; l_nb_comps = p_j2k->m_private_image->numcomps - 1; l_nb_bytes += opj_j2k_get_max_toc_size(p_j2k); if (!(OPJ_IS_CINEMA(p_j2k->m_cp.rsiz))) { l_coc_bytes = opj_j2k_get_max_coc_size(p_j2k); l_nb_bytes += l_nb_comps * l_coc_bytes; l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k); l_nb_bytes += l_nb_comps * l_qcc_bytes; } l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k); /*** DEVELOPER CORNER, Add room for your headers ***/ return l_nb_bytes; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Add support for generation of PLT markers in encoder * -PLT switch added to opj_compress * Add a opj_encoder_set_extra_options() function that accepts a PLT=YES option, and could be expanded later for other uses. ------- Testing with a Sentinel2 10m band, T36JTT_20160914T074612_B02.jp2, coming from S2A_MSIL1C_20160914T074612_N0204_R135_T36JTT_20160914T081456.SAFE Decompress it to TIFF: ``` opj_uncompress -i T36JTT_20160914T074612_B02.jp2 -o T36JTT_20160914T074612_B02.tif ``` Recompress it with similar parameters as original: ``` opj_compress -n 5 -c [256,256],[256,256],[256,256],[256,256],[256,256] -t 1024,1024 -PLT -i T36JTT_20160914T074612_B02.tif -o T36JTT_20160914T074612_B02_PLT.jp2 ``` Dump codestream detail with GDAL dump_jp2.py utility (https://github.com/OSGeo/gdal/blob/master/gdal/swig/python/samples/dump_jp2.py) ``` python dump_jp2.py T36JTT_20160914T074612_B02.jp2 > /tmp/dump_sentinel2_ori.txt python dump_jp2.py T36JTT_20160914T074612_B02_PLT.jp2 > /tmp/dump_sentinel2_openjpeg_plt.txt ``` The diff between both show very similar structure, and identical number of packets in PLT markers Now testing with Kakadu (KDU803_Demo_Apps_for_Linux-x86-64_200210) Full file decompression: ``` kdu_expand -i T36JTT_20160914T074612_B02_PLT.jp2 -o tmp.tif Consumed 121 tile-part(s) from a total of 121 tile(s). Consumed 80,318,806 codestream bytes (excluding any file format) = 5.329697 bits/pel. Processed using the multi-threaded environment, with 8 parallel threads of execution ``` Partial decompresson (presumably using PLT markers): ``` kdu_expand -i T36JTT_20160914T074612_B02.jp2 -o tmp.pgm -region "{0.5,0.5},{0.01,0.01}" kdu_expand -i T36JTT_20160914T074612_B02_PLT.jp2 -o tmp2.pgm -region "{0.5,0.5},{0.01,0.01}" diff tmp.pgm tmp2.pgm && echo "same !" ``` ------- Funded by ESA for S2-MPC project'</s>
<s>[INST] Given the following code containing errors, provide 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 unix_stream_read_generic(struct unix_stream_read_state *state) { struct scm_cookie scm; struct socket *sock = state->socket; struct sock *sk = sock->sk; struct unix_sock *u = unix_sk(sk); int copied = 0; int flags = state->flags; int noblock = flags & MSG_DONTWAIT; bool check_creds = false; int target; int err = 0; long timeo; int skip; size_t size = state->size; unsigned int last_len; err = -EINVAL; if (sk->sk_state != TCP_ESTABLISHED) goto out; err = -EOPNOTSUPP; if (flags & MSG_OOB) goto out; target = sock_rcvlowat(sk, flags & MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, noblock); memset(&scm, 0, sizeof(scm)); /* Lock the socket to prevent queue disordering * while sleeps in memcpy_tomsg */ mutex_lock(&u->readlock); if (flags & MSG_PEEK) skip = sk_peek_offset(sk, flags); else skip = 0; do { int chunk; bool drop_skb; struct sk_buff *skb, *last; unix_state_lock(sk); if (sock_flag(sk, SOCK_DEAD)) { err = -ECONNRESET; goto unlock; } last = skb = skb_peek(&sk->sk_receive_queue); last_len = last ? last->len : 0; again: if (skb == NULL) { unix_sk(sk)->recursion_level = 0; if (copied >= target) goto unlock; /* * POSIX 1003.1g mandates this order. */ err = sock_error(sk); if (err) goto unlock; if (sk->sk_shutdown & RCV_SHUTDOWN) goto unlock; unix_state_unlock(sk); err = -EAGAIN; if (!timeo) break; mutex_unlock(&u->readlock); timeo = unix_stream_data_wait(sk, timeo, last, last_len); if (signal_pending(current)) { err = sock_intr_errno(timeo); goto out; } mutex_lock(&u->readlock); continue; unlock: unix_state_unlock(sk); break; } while (skip >= unix_skb_len(skb)) { skip -= unix_skb_len(skb); last = skb; last_len = skb->len; skb = skb_peek_next(skb, &sk->sk_receive_queue); if (!skb) goto again; } unix_state_unlock(sk); if (check_creds) { /* Never glue messages from different writers */ if (!unix_skb_scm_eq(skb, &scm)) break; } else if (test_bit(SOCK_PASSCRED, &sock->flags)) { /* Copy credentials */ scm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid); unix_set_secdata(&scm, skb); check_creds = true; } /* Copy address just once */ if (state->msg && state->msg->msg_name) { DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, state->msg->msg_name); unix_copy_addr(state->msg, skb->sk); sunaddr = NULL; } chunk = min_t(unsigned int, unix_skb_len(skb) - skip, size); skb_get(skb); chunk = state->recv_actor(skb, skip, chunk, state); drop_skb = !unix_skb_len(skb); /* skb is only safe to use if !drop_skb */ consume_skb(skb); if (chunk < 0) { if (copied == 0) copied = -EFAULT; break; } copied += chunk; size -= chunk; if (drop_skb) { /* the skb was touched by a concurrent reader; * we should not expect anything from this skb * anymore and assume it invalid - we can be * sure it was dropped from the socket queue * * let's report a short read */ err = 0; break; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { UNIXCB(skb).consumed += chunk; sk_peek_offset_bwd(sk, chunk); if (UNIXCB(skb).fp) unix_detach_fds(&scm, skb); if (unix_skb_len(skb)) break; skb_unlink(skb, &sk->sk_receive_queue); consume_skb(skb); if (scm.fp) break; } else { /* It is questionable, see note in unix_dgram_recvmsg. */ if (UNIXCB(skb).fp) scm.fp = scm_fp_dup(UNIXCB(skb).fp); sk_peek_offset_fwd(sk, chunk); if (UNIXCB(skb).fp) break; skip = 0; last = skb; last_len = skb->len; unix_state_lock(sk); skb = skb_peek_next(skb, &sk->sk_receive_queue); if (skb) goto again; unix_state_unlock(sk); break; } } while (size); mutex_unlock(&u->readlock); if (state->msg) scm_recv(sock, state->msg, &scm, flags); else scm_destroy(&scm); out: return copied ? : err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'af_unix: fix struct pid memory leak Dmitry reported a struct pid leak detected by a syzkaller program. Bug happens in unix_stream_recvmsg() when we break the loop when a signal is pending, without properly releasing scm. Fixes: b3ca9b02b007 ("net: fix multithreaded signal handling in unix recv routines") Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Cc: Rainer Weikusat <rweikusat@mobileactivedefense.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: miniflow_extract(struct dp_packet *packet, struct miniflow *dst) { const struct pkt_metadata *md = &packet->md; const void *data = dp_packet_data(packet); size_t size = dp_packet_size(packet); uint64_t *values = miniflow_values(dst); struct mf_ctx mf = { FLOWMAP_EMPTY_INITIALIZER, values, values + FLOW_U64S }; const char *l2; ovs_be16 dl_type; uint8_t nw_frag, nw_tos, nw_ttl, nw_proto; /* Metadata. */ if (flow_tnl_dst_is_set(&md->tunnel)) { miniflow_push_words(mf, tunnel, &md->tunnel, offsetof(struct flow_tnl, metadata) / sizeof(uint64_t)); if (!(md->tunnel.flags & FLOW_TNL_F_UDPIF)) { if (md->tunnel.metadata.present.map) { miniflow_push_words(mf, tunnel.metadata, &md->tunnel.metadata, sizeof md->tunnel.metadata / sizeof(uint64_t)); } } else { if (md->tunnel.metadata.present.len) { miniflow_push_words(mf, tunnel.metadata.present, &md->tunnel.metadata.present, 1); miniflow_push_words(mf, tunnel.metadata.opts.gnv, md->tunnel.metadata.opts.gnv, DIV_ROUND_UP(md->tunnel.metadata.present.len, sizeof(uint64_t))); } } } if (md->skb_priority || md->pkt_mark) { miniflow_push_uint32(mf, skb_priority, md->skb_priority); miniflow_push_uint32(mf, pkt_mark, md->pkt_mark); } miniflow_push_uint32(mf, dp_hash, md->dp_hash); miniflow_push_uint32(mf, in_port, odp_to_u32(md->in_port.odp_port)); if (md->recirc_id || md->ct_state) { miniflow_push_uint32(mf, recirc_id, md->recirc_id); miniflow_push_uint16(mf, ct_state, md->ct_state); miniflow_push_uint16(mf, ct_zone, md->ct_zone); } if (md->ct_state) { miniflow_push_uint32(mf, ct_mark, md->ct_mark); miniflow_pad_to_64(mf, pad1); if (!ovs_u128_is_zero(&md->ct_label)) { miniflow_push_words(mf, ct_label, &md->ct_label, sizeof md->ct_label / sizeof(uint64_t)); } } /* Initialize packet's layer pointer and offsets. */ l2 = data; dp_packet_reset_offsets(packet); /* Must have full Ethernet header to proceed. */ if (OVS_UNLIKELY(size < sizeof(struct eth_header))) { goto out; } else { ovs_be16 vlan_tci; /* Link layer. */ ASSERT_SEQUENTIAL(dl_dst, dl_src); miniflow_push_macs(mf, dl_dst, data); /* dl_type, vlan_tci. */ vlan_tci = parse_vlan(&data, &size); dl_type = parse_ethertype(&data, &size); miniflow_push_be16(mf, dl_type, dl_type); miniflow_push_be16(mf, vlan_tci, vlan_tci); } /* Parse mpls. */ if (OVS_UNLIKELY(eth_type_mpls(dl_type))) { int count; const void *mpls = data; packet->l2_5_ofs = (char *)data - l2; count = parse_mpls(&data, &size); miniflow_push_words_32(mf, mpls_lse, mpls, count); } /* Network layer. */ packet->l3_ofs = (char *)data - l2; nw_frag = 0; if (OVS_LIKELY(dl_type == htons(ETH_TYPE_IP))) { const struct ip_header *nh = data; int ip_len; uint16_t tot_len; if (OVS_UNLIKELY(size < IP_HEADER_LEN)) { goto out; } ip_len = IP_IHL(nh->ip_ihl_ver) * 4; if (OVS_UNLIKELY(ip_len < IP_HEADER_LEN)) { goto out; } if (OVS_UNLIKELY(size < ip_len)) { goto out; } tot_len = ntohs(nh->ip_tot_len); if (OVS_UNLIKELY(tot_len > size || ip_len > tot_len)) { goto out; } if (OVS_UNLIKELY(size - tot_len > UINT8_MAX)) { goto out; } dp_packet_set_l2_pad_size(packet, size - tot_len); size = tot_len; /* Never pull padding. */ /* Push both source and destination address at once. */ miniflow_push_words(mf, nw_src, &nh->ip_src, 1); miniflow_push_be32(mf, ipv6_label, 0); /* Padding for IPv4. */ nw_tos = nh->ip_tos; nw_ttl = nh->ip_ttl; nw_proto = nh->ip_proto; if (OVS_UNLIKELY(IP_IS_FRAGMENT(nh->ip_frag_off))) { nw_frag = FLOW_NW_FRAG_ANY; if (nh->ip_frag_off & htons(IP_FRAG_OFF_MASK)) { nw_frag |= FLOW_NW_FRAG_LATER; } } data_pull(&data, &size, ip_len); } else if (dl_type == htons(ETH_TYPE_IPV6)) { const struct ovs_16aligned_ip6_hdr *nh; ovs_be32 tc_flow; uint16_t plen; if (OVS_UNLIKELY(size < sizeof *nh)) { goto out; } nh = data_pull(&data, &size, sizeof *nh); plen = ntohs(nh->ip6_plen); if (OVS_UNLIKELY(plen > size)) { goto out; } /* Jumbo Payload option not supported yet. */ if (OVS_UNLIKELY(size - plen > UINT8_MAX)) { goto out; } dp_packet_set_l2_pad_size(packet, size - plen); size = plen; /* Never pull padding. */ miniflow_push_words(mf, ipv6_src, &nh->ip6_src, sizeof nh->ip6_src / 8); miniflow_push_words(mf, ipv6_dst, &nh->ip6_dst, sizeof nh->ip6_dst / 8); tc_flow = get_16aligned_be32(&nh->ip6_flow); nw_tos = ntohl(tc_flow) >> 20; nw_ttl = nh->ip6_hlim; nw_proto = nh->ip6_nxt; while (1) { if (OVS_LIKELY((nw_proto != IPPROTO_HOPOPTS) && (nw_proto != IPPROTO_ROUTING) && (nw_proto != IPPROTO_DSTOPTS) && (nw_proto != IPPROTO_AH) && (nw_proto != IPPROTO_FRAGMENT))) { /* It's either a terminal header (e.g., TCP, UDP) or one we * don't understand. In either case, we're done with the * packet, so use it to fill in 'nw_proto'. */ break; } /* We only verify that at least 8 bytes of the next header are * available, but many of these headers are longer. Ensure that * accesses within the extension header are within those first 8 * bytes. All extension headers are required to be at least 8 * bytes. */ if (OVS_UNLIKELY(size < 8)) { goto out; } if ((nw_proto == IPPROTO_HOPOPTS) || (nw_proto == IPPROTO_ROUTING) || (nw_proto == IPPROTO_DSTOPTS)) { /* These headers, while different, have the fields we care * about in the same location and with the same * interpretation. */ const struct ip6_ext *ext_hdr = data; nw_proto = ext_hdr->ip6e_nxt; if (OVS_UNLIKELY(!data_try_pull(&data, &size, (ext_hdr->ip6e_len + 1) * 8))) { goto out; } } else if (nw_proto == IPPROTO_AH) { /* A standard AH definition isn't available, but the fields * we care about are in the same location as the generic * option header--only the header length is calculated * differently. */ const struct ip6_ext *ext_hdr = data; nw_proto = ext_hdr->ip6e_nxt; if (OVS_UNLIKELY(!data_try_pull(&data, &size, (ext_hdr->ip6e_len + 2) * 4))) { goto out; } } else if (nw_proto == IPPROTO_FRAGMENT) { const struct ovs_16aligned_ip6_frag *frag_hdr = data; nw_proto = frag_hdr->ip6f_nxt; if (!data_try_pull(&data, &size, sizeof *frag_hdr)) { goto out; } /* We only process the first fragment. */ if (frag_hdr->ip6f_offlg != htons(0)) { nw_frag = FLOW_NW_FRAG_ANY; if ((frag_hdr->ip6f_offlg & IP6F_OFF_MASK) != htons(0)) { nw_frag |= FLOW_NW_FRAG_LATER; nw_proto = IPPROTO_FRAGMENT; break; } } } } /* This needs to be after the parse_ipv6_ext_hdrs__() call because it * leaves the nw_frag word uninitialized. */ ASSERT_SEQUENTIAL(ipv6_label, nw_frag); ovs_be32 label = tc_flow & htonl(IPV6_LABEL_MASK); miniflow_push_be32(mf, ipv6_label, label); } else { if (dl_type == htons(ETH_TYPE_ARP) || dl_type == htons(ETH_TYPE_RARP)) { struct eth_addr arp_buf[2]; const struct arp_eth_header *arp = (const struct arp_eth_header *) data_try_pull(&data, &size, ARP_ETH_HEADER_LEN); if (OVS_LIKELY(arp) && OVS_LIKELY(arp->ar_hrd == htons(1)) && OVS_LIKELY(arp->ar_pro == htons(ETH_TYPE_IP)) && OVS_LIKELY(arp->ar_hln == ETH_ADDR_LEN) && OVS_LIKELY(arp->ar_pln == 4)) { miniflow_push_be32(mf, nw_src, get_16aligned_be32(&arp->ar_spa)); miniflow_push_be32(mf, nw_dst, get_16aligned_be32(&arp->ar_tpa)); /* We only match on the lower 8 bits of the opcode. */ if (OVS_LIKELY(ntohs(arp->ar_op) <= 0xff)) { miniflow_push_be32(mf, ipv6_label, 0); /* Pad with ARP. */ miniflow_push_be32(mf, nw_frag, htonl(ntohs(arp->ar_op))); } /* Must be adjacent. */ ASSERT_SEQUENTIAL(arp_sha, arp_tha); arp_buf[0] = arp->ar_sha; arp_buf[1] = arp->ar_tha; miniflow_push_macs(mf, arp_sha, arp_buf); miniflow_pad_to_64(mf, tcp_flags); } } goto out; } packet->l4_ofs = (char *)data - l2; miniflow_push_be32(mf, nw_frag, BYTES_TO_BE32(nw_frag, nw_tos, nw_ttl, nw_proto)); if (OVS_LIKELY(!(nw_frag & FLOW_NW_FRAG_LATER))) { if (OVS_LIKELY(nw_proto == IPPROTO_TCP)) { if (OVS_LIKELY(size >= TCP_HEADER_LEN)) { const struct tcp_header *tcp = data; miniflow_push_be32(mf, arp_tha.ea[2], 0); miniflow_push_be32(mf, tcp_flags, TCP_FLAGS_BE32(tcp->tcp_ctl)); miniflow_push_be16(mf, tp_src, tcp->tcp_src); miniflow_push_be16(mf, tp_dst, tcp->tcp_dst); miniflow_pad_to_64(mf, igmp_group_ip4); } } else if (OVS_LIKELY(nw_proto == IPPROTO_UDP)) { if (OVS_LIKELY(size >= UDP_HEADER_LEN)) { const struct udp_header *udp = data; miniflow_push_be16(mf, tp_src, udp->udp_src); miniflow_push_be16(mf, tp_dst, udp->udp_dst); miniflow_pad_to_64(mf, igmp_group_ip4); } } else if (OVS_LIKELY(nw_proto == IPPROTO_SCTP)) { if (OVS_LIKELY(size >= SCTP_HEADER_LEN)) { const struct sctp_header *sctp = data; miniflow_push_be16(mf, tp_src, sctp->sctp_src); miniflow_push_be16(mf, tp_dst, sctp->sctp_dst); miniflow_pad_to_64(mf, igmp_group_ip4); } } else if (OVS_LIKELY(nw_proto == IPPROTO_ICMP)) { if (OVS_LIKELY(size >= ICMP_HEADER_LEN)) { const struct icmp_header *icmp = data; miniflow_push_be16(mf, tp_src, htons(icmp->icmp_type)); miniflow_push_be16(mf, tp_dst, htons(icmp->icmp_code)); miniflow_pad_to_64(mf, igmp_group_ip4); } } else if (OVS_LIKELY(nw_proto == IPPROTO_IGMP)) { if (OVS_LIKELY(size >= IGMP_HEADER_LEN)) { const struct igmp_header *igmp = data; miniflow_push_be16(mf, tp_src, htons(igmp->igmp_type)); miniflow_push_be16(mf, tp_dst, htons(igmp->igmp_code)); miniflow_push_be32(mf, igmp_group_ip4, get_16aligned_be32(&igmp->group)); } } else if (OVS_LIKELY(nw_proto == IPPROTO_ICMPV6)) { if (OVS_LIKELY(size >= sizeof(struct icmp6_hdr))) { const struct in6_addr *nd_target = NULL; struct eth_addr arp_buf[2] = { { { { 0 } } } }; const struct icmp6_hdr *icmp = data_pull(&data, &size, sizeof *icmp); parse_icmpv6(&data, &size, icmp, &nd_target, arp_buf); if (nd_target) { miniflow_push_words(mf, nd_target, nd_target, sizeof *nd_target / sizeof(uint64_t)); } miniflow_push_macs(mf, arp_sha, arp_buf); miniflow_pad_to_64(mf, tcp_flags); miniflow_push_be16(mf, tp_src, htons(icmp->icmp6_type)); miniflow_push_be16(mf, tp_dst, htons(icmp->icmp6_code)); miniflow_pad_to_64(mf, igmp_group_ip4); } } } out: dst->map = mf.map; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'flow: Support extra padding length. Although not required, padding can be optionally added until the packet length is MTU bytes. A packet with extra padding currently fails sanity checks. Vulnerability: CVE-2020-35498 Fixes: fa8d9001a624 ("miniflow_extract: Properly handle small IP packets.") Reported-by: Joakim Hindersson <joakim.hindersson@elastx.se> Acked-by: Ilya Maximets <i.maximets@ovn.org> Signed-off-by: Flavio Leitner <fbl@sysclose.org> Signed-off-by: Ilya Maximets <i.maximets@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 uint8_t esp_fifo_pop(ESPState *s) { if (fifo8_is_empty(&s->fifo)) { return 0; } return fifo8_pop(&s->fifo); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'esp: consolidate esp_cmdfifo_pop() into esp_fifo_pop() Each FIFO currently has its own pop functions with the only difference being the capacity check. The original reason for this was that the fifo8 implementation doesn't have a formal API for retrieving the FIFO capacity, however there are multiple examples within QEMU where the capacity field is accessed directly. Change esp_fifo_pop() to access the FIFO capacity directly and then consolidate esp_cmdfifo_pop() into esp_fifo_pop(). Signed-off-by: Mark Cave-Ayland <mark.cave-ayland@ilande.co.uk> Reviewed-by: Philippe Mathieu-Daudé <f4bug@amsat.org> Tested-by: Alexander Bulekov <alxndr@bu.edu> Message-Id: <20210407195801.685-5-mark.cave-ayland@ilande.co.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: static void do_cmd(ESPState *s) { uint8_t busid = fifo8_pop(&s->cmdfifo); s->cmdfifo_cdb_offset--; /* Ignore extended messages for now */ if (s->cmdfifo_cdb_offset) { esp_fifo_pop_buf(&s->cmdfifo, NULL, s->cmdfifo_cdb_offset); s->cmdfifo_cdb_offset = 0; } do_busid_cmd(s, busid); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'esp: don't underflow cmdfifo in do_cmd() If the guest tries to execute a CDB when cmdfifo is not empty before the start of the message out phase then clearing the message out phase data will cause cmdfifo to underflow due to cmdfifo_cdb_offset being larger than the amount of data within. Since this can only occur by issuing deliberately incorrect instruction sequences, ensure that the maximum length of esp_fifo_pop_buf() is limited to the size of the data within cmdfifo. Buglink: https://bugs.launchpad.net/qemu/+bug/1909247 Signed-off-by: Mark Cave-Ayland <mark.cave-ayland@ilande.co.uk> Reviewed-by: Philippe Mathieu-Daudé <f4bug@amsat.org> Tested-by: Alexander Bulekov <alxndr@bu.edu> Message-Id: <20210407195801.685-8-mark.cave-ayland@ilande.co.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: handle_add_command(GraphicsManager *self, const GraphicsCommand *g, const uint8_t *payload, bool *is_dirty, uint32_t iid) { #define ABRT(code, ...) { set_add_response(#code, __VA_ARGS__); self->loading_image = 0; if (img) img->data_loaded = false; return NULL; } #define MAX_DATA_SZ (4u * 100000000u) has_add_respose = false; bool existing, init_img = true; Image *img = NULL; unsigned char tt = g->transmission_type ? g->transmission_type : 'd'; enum FORMATS { RGB=24, RGBA=32, PNG=100 }; uint32_t fmt = g->format ? g->format : RGBA; if (tt == 'd' && self->loading_image) init_img = false; if (init_img) { self->last_init_graphics_command = *g; self->last_init_graphics_command.id = iid; self->loading_image = 0; if (g->data_width > 10000 || g->data_height > 10000) ABRT(EINVAL, "Image too large"); remove_images(self, add_trim_predicate, 0); img = find_or_create_image(self, iid, &existing); if (existing) { free_load_data(&img->load_data); img->data_loaded = false; free_refs_data(img); *is_dirty = true; self->layers_dirty = true; } else { img->internal_id = internal_id_counter++; img->client_id = iid; } img->atime = monotonic(); img->used_storage = 0; img->width = g->data_width; img->height = g->data_height; switch(fmt) { case PNG: if (g->data_sz > MAX_DATA_SZ) ABRT(EINVAL, "PNG data size too large"); img->load_data.is_4byte_aligned = true; img->load_data.is_opaque = false; img->load_data.data_sz = g->data_sz ? g->data_sz : 1024 * 100; break; case RGB: case RGBA: img->load_data.data_sz = (size_t)g->data_width * g->data_height * (fmt / 8); if (!img->load_data.data_sz) ABRT(EINVAL, "Zero width/height not allowed"); img->load_data.is_4byte_aligned = fmt == RGBA || (img->width % 4 == 0); img->load_data.is_opaque = fmt == RGB; break; default: ABRT(EINVAL, "Unknown image format: %u", fmt); } if (tt == 'd') { if (g->more) self->loading_image = img->internal_id; img->load_data.buf_capacity = img->load_data.data_sz + (g->compressed ? 1024 : 10); // compression header img->load_data.buf = malloc(img->load_data.buf_capacity); img->load_data.buf_used = 0; if (img->load_data.buf == NULL) { ABRT(ENOMEM, "Out of memory"); img->load_data.buf_capacity = 0; img->load_data.buf_used = 0; } } } else { self->last_init_graphics_command.more = g->more; self->last_init_graphics_command.payload_sz = g->payload_sz; g = &self->last_init_graphics_command; tt = g->transmission_type ? g->transmission_type : 'd'; fmt = g->format ? g->format : RGBA; img = img_by_internal_id(self, self->loading_image); if (img == NULL) { self->loading_image = 0; ABRT(EILSEQ, "More payload loading refers to non-existent image"); } } int fd; static char fname[2056] = {0}; switch(tt) { case 'd': // direct if (img->load_data.buf_capacity - img->load_data.buf_used < g->payload_sz) { if (img->load_data.buf_used + g->payload_sz > MAX_DATA_SZ || fmt != PNG) ABRT(EFBIG, "Too much data"); img->load_data.buf_capacity = MIN(2 * img->load_data.buf_capacity, MAX_DATA_SZ); img->load_data.buf = realloc(img->load_data.buf, img->load_data.buf_capacity); if (img->load_data.buf == NULL) { ABRT(ENOMEM, "Out of memory"); img->load_data.buf_capacity = 0; img->load_data.buf_used = 0; } } memcpy(img->load_data.buf + img->load_data.buf_used, payload, g->payload_sz); img->load_data.buf_used += g->payload_sz; if (!g->more) { img->data_loaded = true; self->loading_image = 0; } break; case 'f': // file case 't': // temporary file case 's': // POSIX shared memory if (g->payload_sz > 2048) ABRT(EINVAL, "Filename too long"); snprintf(fname, sizeof(fname)/sizeof(fname[0]), "%.*s", (int)g->payload_sz, payload); if (tt == 's') fd = shm_open(fname, O_RDONLY, 0); else fd = open(fname, O_CLOEXEC | O_RDONLY); if (fd == -1) ABRT(EBADF, "Failed to open file %s for graphics transmission with error: [%d] %s", fname, errno, strerror(errno)); img->data_loaded = mmap_img_file(self, img, fd, g->data_sz, g->data_offset); safe_close(fd, __FILE__, __LINE__); if (tt == 't') { if (global_state.boss) { call_boss(safe_delete_temp_file, "s", fname); } else unlink(fname); } else if (tt == 's') shm_unlink(fname); break; default: ABRT(EINVAL, "Unknown transmission type: %c", g->transmission_type); } if (!img->data_loaded) return NULL; self->loading_image = 0; bool needs_processing = g->compressed || fmt == PNG; if (needs_processing) { uint8_t *buf; size_t bufsz; #define IB { if (img->load_data.buf) { buf = img->load_data.buf; bufsz = img->load_data.buf_used; } else { buf = img->load_data.mapped_file; bufsz = img->load_data.mapped_file_sz; } } switch(g->compressed) { case 'z': IB; if (!inflate_zlib(self, img, buf, bufsz)) { img->data_loaded = false; return NULL; } break; case 0: break; default: ABRT(EINVAL, "Unknown image compression: %c", g->compressed); } switch(fmt) { case PNG: IB; if (!inflate_png(self, img, buf, bufsz)) { img->data_loaded = false; return NULL; } break; default: break; } #undef IB img->load_data.data = img->load_data.buf; if (img->load_data.buf_used < img->load_data.data_sz) { ABRT(ENODATA, "Insufficient image data: %zu < %zu", img->load_data.buf_used, img->load_data.data_sz); } if (img->load_data.mapped_file) { munmap(img->load_data.mapped_file, img->load_data.mapped_file_sz); img->load_data.mapped_file = NULL; img->load_data.mapped_file_sz = 0; } } else { if (tt == 'd') { if (img->load_data.buf_used < img->load_data.data_sz) { ABRT(ENODATA, "Insufficient image data: %zu < %zu", img->load_data.buf_used, img->load_data.data_sz); } else img->load_data.data = img->load_data.buf; } else { if (img->load_data.mapped_file_sz < img->load_data.data_sz) { ABRT(ENODATA, "Insufficient image data: %zu < %zu", img->load_data.mapped_file_sz, img->load_data.data_sz); } else img->load_data.data = img->load_data.mapped_file; } } size_t required_sz = (size_t)(img->load_data.is_opaque ? 3 : 4) * img->width * img->height; if (img->load_data.data_sz != required_sz) ABRT(EINVAL, "Image dimensions: %ux%u do not match data size: %zu, expected size: %zu", img->width, img->height, img->load_data.data_sz, required_sz); if (LIKELY(img->data_loaded && send_to_gpu)) { send_image_to_gpu(&img->texture_id, img->load_data.data, img->width, img->height, img->load_data.is_opaque, img->load_data.is_4byte_aligned, false, REPEAT_CLAMP); free_load_data(&img->load_data); self->used_storage += required_sz; img->used_storage = required_sz; } return img; #undef MAX_DATA_SZ #undef ABRT } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Graphics protocol: Dont return filename in the error message when opening file fails, since filenames can contain control characters Fixes #3128'</s>
<s>[INST] Given the following code containing errors, provide 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 VALUE read_memory(VALUE klass, VALUE content) { xmlRelaxNGParserCtxtPtr ctx = xmlRelaxNGNewMemParserCtxt( (const char *)StringValuePtr(content), (int)RSTRING_LEN(content) ); xmlRelaxNGPtr schema; VALUE errors = rb_ary_new(); VALUE rb_schema; xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher); #ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS xmlRelaxNGSetParserStructuredErrors( ctx, Nokogiri_error_array_pusher, (void *)errors ); #endif schema = xmlRelaxNGParse(ctx); xmlSetStructuredErrorFunc(NULL, NULL); xmlRelaxNGFreeParserCtxt(ctx); if(NULL == schema) { xmlErrorPtr error = xmlGetLastError(); if(error) Nokogiri_error_raise(NULL, error); else rb_raise(rb_eRuntimeError, "Could not parse document"); return Qnil; } rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema); rb_iv_set(rb_schema, "@errors", errors); return rb_schema; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-611', 'CWE-703'], 'message': 'feat: XML::Schema and RelaxNG creation accept optional ParseOptions I'm trying out a new pattern, which is that the parsed object carries around the ParseOptions it was created with, which should make some testing a bit easier. I'm also not implementing the "config block" pattern in use for Documents, because I think the UX is weird and I'm hoping to change everything to use kwargs in a 2.0 release, anyway.'</s>
<s>[INST] Given the following code containing errors, provide 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 ReadStrip(TIFF* tiff, UINT32 row, UINT32* buffer) { uint16 photometric = 0; // init to not PHOTOMETRIC_YCBCR TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); // To avoid dealing with YCbCr subsampling, let libtiff handle it if (photometric == PHOTOMETRIC_YCBCR) { TIFFRGBAImage img; char emsg[1024] = ""; UINT32 rows_per_strip, rows_to_read; int ok; TIFFGetFieldDefaulted(tiff, TIFFTAG_ROWSPERSTRIP, &rows_per_strip); if ((row % rows_per_strip) != 0) { TRACE(("Row passed to ReadStrip() must be first in a strip.")); return -1; } if (TIFFRGBAImageOK(tiff, emsg) && TIFFRGBAImageBegin(&img, tiff, 0, emsg)) { TRACE(("Initialized RGBAImage\n")); img.req_orientation = ORIENTATION_TOPLEFT; img.row_offset = row; img.col_offset = 0; rows_to_read = min(rows_per_strip, img.height - row); TRACE(("rows to read: %d\n", rows_to_read)); ok = TIFFRGBAImageGet(&img, buffer, img.width, rows_to_read); TIFFRGBAImageEnd(&img); } else { ok = 0; } if (ok == 0) { TRACE(("Decode Error, row %d; msg: %s\n", row, emsg)); return -1; } return 0; } if (TIFFReadEncodedStrip(tiff, TIFFComputeStrip(tiff, row, 0), (tdata_t)buffer, -1) == -1) { TRACE(("Decode Error, strip %d\n", TIFFComputeStrip(tiff, row, 0))); return -1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix CVE-2020-35654 - OOB Write in TiffDecode.c * In some circumstances with some versions of libtiff (4.1.0+), there could be a 4 byte out of bound write when decoding a YCbCr tiff. * The Pillow code dates to 6.0.0 * Found and reported through Tidelift'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: flatpak_run_apply_env_vars (FlatpakBwrap *bwrap, FlatpakContext *context) { GHashTableIter iter; gpointer key, value; g_hash_table_iter_init (&iter, context->env_vars); while (g_hash_table_iter_next (&iter, &key, &value)) { const char *var = key; const char *val = value; if (val && val[0] != 0) flatpak_bwrap_set_env (bwrap, var, val, TRUE); else flatpak_bwrap_unset_env (bwrap, var); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-74'], 'message': 'run: Allow setting environment variables to empty strings Some consumers of environment variables distinguish between present with an empty value and absent. For example, if an environment variable represents a search path like VK_ICD_FILENAMES, unsetting it often results in use of a default, but setting it to the empty string results in not searching any locations, which is sometimes what is desired. The shell syntax "${BAR-unset}" expands to the value of ${BAR} if it is set to anything (even an empty string), or to "unset" if not. We can use that in the unit test to check that BAR is set to the empty string in this case. This follows up from GHSA-4ppf-fxf6-vxg2 to fix an issue that I noticed while resolving that vulnerability, but is not required for fixing the vulnerability. Signed-off-by: Simon McVittie <smcv@collabora.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: sudoers_policy_main(int argc, char * const argv[], int pwflag, char *env_add[], bool verbose, void *closure) { char *iolog_path = NULL; mode_t cmnd_umask = ACCESSPERMS; struct sudo_nss *nss; int oldlocale, validated, ret = -1; debug_decl(sudoers_policy_main, SUDOERS_DEBUG_PLUGIN); sudo_warn_set_locale_func(sudoers_warn_setlocale); unlimit_nproc(); /* Is root even allowed to run sudo? */ if (user_uid == 0 && !def_root_sudo) { /* Not an audit event (should it be?). */ sudo_warnx("%s", U_("sudoers specifies that root is not allowed to sudo")); goto bad; } if (!set_perms(PERM_INITIAL)) goto bad; /* Environment variables specified on the command line. */ if (env_add != NULL && env_add[0] != NULL) sudo_user.env_vars = env_add; /* * Make a local copy of argc/argv, with special handling * for pseudo-commands and the '-i' option. */ if (argc == 0) { NewArgc = 1; NewArgv = reallocarray(NULL, NewArgc + 1, sizeof(char *)); if (NewArgv == NULL) { sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); goto done; } sudoers_gc_add(GC_VECTOR, NewArgv); NewArgv[0] = user_cmnd; NewArgv[1] = NULL; } else { /* Must leave an extra slot before NewArgv for bash's --login */ NewArgc = argc; NewArgv = reallocarray(NULL, NewArgc + 2, sizeof(char *)); if (NewArgv == NULL) { sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); goto done; } sudoers_gc_add(GC_VECTOR, NewArgv); NewArgv++; /* reserve an extra slot for --login */ memcpy(NewArgv, argv, argc * sizeof(char *)); NewArgv[NewArgc] = NULL; if (ISSET(sudo_mode, MODE_LOGIN_SHELL) && runas_pw != NULL) { NewArgv[0] = strdup(runas_pw->pw_shell); if (NewArgv[0] == NULL) { sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); goto done; } sudoers_gc_add(GC_PTR, NewArgv[0]); } } /* If given the -P option, set the "preserve_groups" flag. */ if (ISSET(sudo_mode, MODE_PRESERVE_GROUPS)) def_preserve_groups = true; /* Find command in path and apply per-command Defaults. */ cmnd_status = set_cmnd(); if (cmnd_status == NOT_FOUND_ERROR) goto done; /* Check for -C overriding def_closefrom. */ if (user_closefrom >= 0 && user_closefrom != def_closefrom) { if (!def_closefrom_override) { log_warningx(SLOG_NO_STDERR|SLOG_AUDIT, N_("user not allowed to override closefrom limit")); sudo_warnx("%s", U_("you are not permitted to use the -C option")); goto bad; } def_closefrom = user_closefrom; } /* * Check sudoers sources, using the locale specified in sudoers. */ sudoers_setlocale(SUDOERS_LOCALE_SUDOERS, &oldlocale); validated = sudoers_lookup(snl, sudo_user.pw, &cmnd_status, pwflag); if (ISSET(validated, VALIDATE_ERROR)) { /* The lookup function should have printed an error. */ goto done; } /* Restore user's locale. */ sudoers_setlocale(oldlocale, NULL); if (safe_cmnd == NULL) { if ((safe_cmnd = strdup(user_cmnd)) == NULL) { sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); goto done; } } /* Defer uid/gid checks until after defaults have been updated. */ if (unknown_runas_uid && !def_runas_allow_unknown_id) { log_warningx(SLOG_AUDIT, N_("unknown user: %s"), runas_pw->pw_name); goto done; } if (runas_gr != NULL) { if (unknown_runas_gid && !def_runas_allow_unknown_id) { log_warningx(SLOG_AUDIT, N_("unknown group: %s"), runas_gr->gr_name); goto done; } } /* * Look up the timestamp dir owner if one is specified. */ if (def_timestampowner) { struct passwd *pw = NULL; if (*def_timestampowner == '#') { const char *errstr; uid_t uid = sudo_strtoid(def_timestampowner + 1, &errstr); if (errstr == NULL) pw = sudo_getpwuid(uid); } if (pw == NULL) pw = sudo_getpwnam(def_timestampowner); if (pw != NULL) { timestamp_uid = pw->pw_uid; timestamp_gid = pw->pw_gid; sudo_pw_delref(pw); } else { /* XXX - audit too? */ log_warningx(SLOG_SEND_MAIL, N_("timestamp owner (%s): No such user"), def_timestampowner); timestamp_uid = ROOT_UID; timestamp_gid = ROOT_GID; } } /* If no command line args and "shell_noargs" is not set, error out. */ if (ISSET(sudo_mode, MODE_IMPLIED_SHELL) && !def_shell_noargs) { /* Not an audit event. */ ret = -2; /* usage error */ goto done; } /* Bail if a tty is required and we don't have one. */ if (def_requiretty && !tty_present()) { log_warningx(SLOG_NO_STDERR|SLOG_AUDIT, N_("no tty")); sudo_warnx("%s", U_("sorry, you must have a tty to run sudo")); goto bad; } /* Check runas user's shell. */ if (!check_user_shell(runas_pw)) { log_warningx(SLOG_RAW_MSG|SLOG_AUDIT, N_("invalid shell for user %s: %s"), runas_pw->pw_name, runas_pw->pw_shell); goto bad; } /* * We don't reset the environment for sudoedit or if the user * specified the -E command line flag and they have setenv privs. */ if (ISSET(sudo_mode, MODE_EDIT) || (ISSET(sudo_mode, MODE_PRESERVE_ENV) && def_setenv)) def_env_reset = false; /* Build a new environment that avoids any nasty bits. */ if (!rebuild_env()) goto bad; /* Require a password if sudoers says so. */ switch (check_user(validated, sudo_mode)) { case true: /* user authenticated successfully. */ break; case false: /* Note: log_denial() calls audit for us. */ if (!ISSET(validated, VALIDATE_SUCCESS)) { /* Only display a denial message if no password was read. */ if (!log_denial(validated, def_passwd_tries <= 0)) goto done; } goto bad; default: /* some other error, ret is -1. */ goto done; } /* Check whether user_runchroot is permitted (if specified). */ switch (check_user_runchroot()) { case true: break; case false: goto bad; default: goto done; } /* Check whether user_runcwd is permitted (if specified). */ switch (check_user_runcwd()) { case true: break; case false: goto bad; default: goto done; } /* If run as root with SUDO_USER set, set sudo_user.pw to that user. */ /* XXX - causes confusion when root is not listed in sudoers */ if (sudo_mode & (MODE_RUN | MODE_EDIT) && prev_user != NULL) { if (user_uid == 0 && strcmp(prev_user, "root") != 0) { struct passwd *pw; if ((pw = sudo_getpwnam(prev_user)) != NULL) { if (sudo_user.pw != NULL) sudo_pw_delref(sudo_user.pw); sudo_user.pw = pw; } } } /* If the user was not allowed to run the command we are done. */ if (!ISSET(validated, VALIDATE_SUCCESS)) { /* Note: log_failure() calls audit for us. */ if (!log_failure(validated, cmnd_status)) goto done; goto bad; } /* Create Ubuntu-style dot file to indicate sudo was successful. */ if (create_admin_success_flag() == -1) goto done; /* Finally tell the user if the command did not exist. */ if (cmnd_status == NOT_FOUND_DOT) { audit_failure(NewArgv, N_("command in current directory")); sudo_warnx(U_("ignoring \"%s\" found in '.'\nUse \"sudo ./%s\" if this is the \"%s\" you wish to run."), user_cmnd, user_cmnd, user_cmnd); goto bad; } else if (cmnd_status == NOT_FOUND) { if (ISSET(sudo_mode, MODE_CHECK)) { audit_failure(NewArgv, N_("%s: command not found"), NewArgv[0]); sudo_warnx(U_("%s: command not found"), NewArgv[0]); } else { audit_failure(NewArgv, N_("%s: command not found"), user_cmnd); sudo_warnx(U_("%s: command not found"), user_cmnd); } goto bad; } /* If user specified a timeout make sure sudoers allows it. */ if (!def_user_command_timeouts && user_timeout > 0) { log_warningx(SLOG_NO_STDERR|SLOG_AUDIT, N_("user not allowed to set a command timeout")); sudo_warnx("%s", U_("sorry, you are not allowed set a command timeout")); goto bad; } /* If user specified env vars make sure sudoers allows it. */ if (ISSET(sudo_mode, MODE_RUN) && !def_setenv) { if (ISSET(sudo_mode, MODE_PRESERVE_ENV)) { log_warningx(SLOG_NO_STDERR|SLOG_AUDIT, N_("user not allowed to preserve the environment")); sudo_warnx("%s", U_("sorry, you are not allowed to preserve the environment")); goto bad; } else { if (!validate_env_vars(sudo_user.env_vars)) goto bad; } } if (ISSET(sudo_mode, (MODE_RUN | MODE_EDIT)) && !remote_iologs) { if ((def_log_input || def_log_output) && def_iolog_file && def_iolog_dir) { if ((iolog_path = format_iolog_path()) == NULL) { if (!def_ignore_iolog_errors) goto done; /* Unable to expand I/O log path, disable I/O logging. */ def_log_input = false; def_log_output = false; } } } switch (sudo_mode & MODE_MASK) { case MODE_CHECK: ret = display_cmnd(snl, list_pw ? list_pw : sudo_user.pw); break; case MODE_LIST: ret = display_privs(snl, list_pw ? list_pw : sudo_user.pw, verbose); break; case MODE_VALIDATE: case MODE_RUN: case MODE_EDIT: /* ret may be overridden by "goto bad" later */ ret = true; break; default: /* Should not happen. */ sudo_warnx("internal error, unexpected sudo mode 0x%x", sudo_mode); goto done; } /* Cleanup sudoers sources */ TAILQ_FOREACH(nss, snl, entries) { nss->close(nss); } if (def_group_plugin) group_plugin_unload(); init_parser(NULL, false, false); if (ISSET(sudo_mode, (MODE_VALIDATE|MODE_CHECK|MODE_LIST))) { /* ret already set appropriately */ goto done; } /* * Set umask based on sudoers. * If user's umask is more restrictive, OR in those bits too * unless umask_override is set. */ if (def_umask != ACCESSPERMS) { cmnd_umask = def_umask; if (!def_umask_override) cmnd_umask |= user_umask; } if (ISSET(sudo_mode, MODE_LOGIN_SHELL)) { char *p; /* Convert /bin/sh -> -sh so shell knows it is a login shell */ if ((p = strrchr(NewArgv[0], '/')) == NULL) p = NewArgv[0]; *p = '-'; NewArgv[0] = p; /* * Newer versions of bash require the --login option to be used * in conjunction with the -c option even if the shell name starts * with a '-'. Unfortunately, bash 1.x uses -login, not --login * so this will cause an error for that. */ if (NewArgc > 1 && strcmp(NewArgv[0], "-bash") == 0 && strcmp(NewArgv[1], "-c") == 0) { /* Use the extra slot before NewArgv so we can store --login. */ NewArgv--; NewArgc++; NewArgv[0] = NewArgv[1]; NewArgv[1] = "--login"; } #if defined(_AIX) || (defined(__linux__) && !defined(HAVE_PAM)) /* Insert system-wide environment variables. */ if (!read_env_file(_PATH_ENVIRONMENT, true, false)) sudo_warn("%s", _PATH_ENVIRONMENT); #endif #ifdef HAVE_LOGIN_CAP_H /* Set environment based on login class. */ if (login_class) { login_cap_t *lc = login_getclass(login_class); if (lc != NULL) { setusercontext(lc, runas_pw, runas_pw->pw_uid, LOGIN_SETPATH|LOGIN_SETENV); login_close(lc); } } #endif /* HAVE_LOGIN_CAP_H */ } /* Insert system-wide environment variables. */ if (def_restricted_env_file) { if (!read_env_file(def_restricted_env_file, false, true)) sudo_warn("%s", def_restricted_env_file); } if (def_env_file) { if (!read_env_file(def_env_file, false, false)) sudo_warn("%s", def_env_file); } /* Insert user-specified environment variables. */ if (!insert_env_vars(sudo_user.env_vars)) goto done; /* Note: must call audit before uid change. */ if (ISSET(sudo_mode, MODE_EDIT)) { char **edit_argv; int edit_argc; const char *env_editor; free(safe_cmnd); safe_cmnd = find_editor(NewArgc - 1, NewArgv + 1, &edit_argc, &edit_argv, NULL, &env_editor, false); if (safe_cmnd == NULL) { if (errno != ENOENT) goto done; audit_failure(NewArgv, N_("%s: command not found"), env_editor ? env_editor : def_editor); sudo_warnx(U_("%s: command not found"), env_editor ? env_editor : def_editor); goto bad; } sudoers_gc_add(GC_VECTOR, edit_argv); NewArgv = edit_argv; NewArgc = edit_argc; /* We want to run the editor with the unmodified environment. */ env_swap_old(); } goto done; bad: ret = false; done: if (ret == -1) { /* Free stashed copy of the environment. */ (void)env_init(NULL); } else { /* Store settings to pass back to front-end. */ if (!sudoers_policy_store_result(ret, NewArgv, env_get(), cmnd_umask, iolog_path, closure)) ret = -1; } if (!rewind_perms()) ret = -1; restore_nproc(); /* Destroy the password and group caches and free the contents. */ sudo_freepwcache(); sudo_freegrcache(); sudo_warn_set_locale_func(NULL); debug_return_int(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-193'], 'message': 'Fix potential buffer overflow when unescaping backslashes in user_args. Also, do not try to unescaping backslashes unless in run mode *and* we are running the command via a shell. Found by Qualys, this fixes CVE-2021-3156.'</s>
<s>[INST] Given the following code containing errors, provide 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 read_multiple_cb(struct bt_att_chan *chan, uint8_t opcode, const void *pdu, uint16_t length, void *user_data) { struct bt_gatt_server *server = user_data; struct gatt_db_attribute *attr; struct read_mult_data *data = NULL; uint8_t ecode; size_t i = 0; uint16_t handle = 0; if (length < 4) { ecode = BT_ATT_ERROR_INVALID_PDU; goto error; } data = read_mult_data_new(server, chan, opcode, length / 2); if (!data) goto error; for (i = 0; i < data->num_handles; i++) data->handles[i] = get_le16(pdu + i * 2); handle = data->handles[0]; util_debug(server->debug_callback, server->debug_data, "%s Req - %zu handles, 1st: 0x%04x", data->opcode == BT_ATT_OP_READ_MULT_REQ ? "Read Multiple" : "Read Multiple Variable Length", data->num_handles, handle); attr = gatt_db_get_attribute(server->db, handle); if (!attr) { ecode = BT_ATT_ERROR_INVALID_HANDLE; goto error; } ecode = check_permissions(data->server, attr, BT_ATT_PERM_READ | BT_ATT_PERM_READ_AUTHEN | BT_ATT_PERM_READ_ENCRYPT); if (ecode) goto error; if (gatt_db_attribute_read(attr, 0, opcode, server->att, read_multiple_complete_cb, data)) return; ecode = BT_ATT_ERROR_UNLIKELY; error: if (data) read_mult_data_free(data); bt_att_chan_send_error_rsp(chan, opcode, handle, ecode); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'shared/gatt-server: Fix not properly checking for secure flags When passing the mask to check_permissions all valid permissions for the operation must be set including BT_ATT_PERM_SECURE flags.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: decompress_gzip(tvbuff_t *tvb, packet_info *pinfo, int offset, guint32 length, tvbuff_t **decompressed_tvb, int *decompressed_offset) { *decompressed_tvb = tvb_child_uncompress(tvb, tvb, offset, length); *decompressed_offset = 0; if (*decompressed_tvb) { return 1; } else { col_append_str(pinfo->cinfo, COL_INFO, " [gzip decompression failed] "); return 0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Kafka: Limit our decompression size. Don't assume that the Internet has our best interests at heart when it gives us the size of our decompression buffer. Assign an arbitrary limit of 50 MB. This fixes #16739 in that it takes care of ** (process:17681): WARNING **: 20:03:07.440: Dissector bug, protocol Kafka, in packet 31: ../epan/proto.c:7043: failed assertion "end >= fi->start" which is different from the original error output. It looks like *that* might have taken care of in one of the other recent Kafka bug fixes. The decompression routines return a success or failure status. Use gbooleans instead of ints for that.'</s>
<s>[INST] Given the following code containing errors, provide 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 hidinput_configure_usage(struct hid_input *hidinput, struct hid_field *field, struct hid_usage *usage) { struct input_dev *input = hidinput->input; struct hid_device *device = input_get_drvdata(input); int max = 0, code; unsigned long *bit = NULL; field->hidinput = hidinput; if (field->flags & HID_MAIN_ITEM_CONSTANT) goto ignore; /* Ignore if report count is out of bounds. */ if (field->report_count < 1) goto ignore; /* only LED usages are supported in output fields */ if (field->report_type == HID_OUTPUT_REPORT && (usage->hid & HID_USAGE_PAGE) != HID_UP_LED) { goto ignore; } if (device->driver->input_mapping) { int ret = device->driver->input_mapping(device, hidinput, field, usage, &bit, &max); if (ret > 0) goto mapped; if (ret < 0) goto ignore; } switch (usage->hid & HID_USAGE_PAGE) { case HID_UP_UNDEFINED: goto ignore; case HID_UP_KEYBOARD: set_bit(EV_REP, input->evbit); if ((usage->hid & HID_USAGE) < 256) { if (!hid_keyboard[usage->hid & HID_USAGE]) goto ignore; map_key_clear(hid_keyboard[usage->hid & HID_USAGE]); } else map_key(KEY_UNKNOWN); break; case HID_UP_BUTTON: code = ((usage->hid - 1) & HID_USAGE); switch (field->application) { case HID_GD_MOUSE: case HID_GD_POINTER: code += BTN_MOUSE; break; case HID_GD_JOYSTICK: if (code <= 0xf) code += BTN_JOYSTICK; else code += BTN_TRIGGER_HAPPY - 0x10; break; case HID_GD_GAMEPAD: if (code <= 0xf) code += BTN_GAMEPAD; else code += BTN_TRIGGER_HAPPY - 0x10; break; default: switch (field->physical) { case HID_GD_MOUSE: case HID_GD_POINTER: code += BTN_MOUSE; break; case HID_GD_JOYSTICK: code += BTN_JOYSTICK; break; case HID_GD_GAMEPAD: code += BTN_GAMEPAD; break; default: code += BTN_MISC; } } map_key(code); break; case HID_UP_SIMULATION: switch (usage->hid & 0xffff) { case 0xba: map_abs(ABS_RUDDER); break; case 0xbb: map_abs(ABS_THROTTLE); break; case 0xc4: map_abs(ABS_GAS); break; case 0xc5: map_abs(ABS_BRAKE); break; case 0xc8: map_abs(ABS_WHEEL); break; default: goto ignore; } break; case HID_UP_GENDESK: if ((usage->hid & 0xf0) == 0x80) { /* SystemControl */ switch (usage->hid & 0xf) { case 0x1: map_key_clear(KEY_POWER); break; case 0x2: map_key_clear(KEY_SLEEP); break; case 0x3: map_key_clear(KEY_WAKEUP); break; case 0x4: map_key_clear(KEY_CONTEXT_MENU); break; case 0x5: map_key_clear(KEY_MENU); break; case 0x6: map_key_clear(KEY_PROG1); break; case 0x7: map_key_clear(KEY_HELP); break; case 0x8: map_key_clear(KEY_EXIT); break; case 0x9: map_key_clear(KEY_SELECT); break; case 0xa: map_key_clear(KEY_RIGHT); break; case 0xb: map_key_clear(KEY_LEFT); break; case 0xc: map_key_clear(KEY_UP); break; case 0xd: map_key_clear(KEY_DOWN); break; case 0xe: map_key_clear(KEY_POWER2); break; case 0xf: map_key_clear(KEY_RESTART); break; default: goto unknown; } break; } if ((usage->hid & 0xf0) == 0xb0) { /* SC - Display */ switch (usage->hid & 0xf) { case 0x05: map_key_clear(KEY_SWITCHVIDEOMODE); break; default: goto ignore; } break; } /* * Some lazy vendors declare 255 usages for System Control, * leading to the creation of ABS_X|Y axis and too many others. * It wouldn't be a problem if joydev doesn't consider the * device as a joystick then. */ if (field->application == HID_GD_SYSTEM_CONTROL) goto ignore; if ((usage->hid & 0xf0) == 0x90) { /* D-pad */ switch (usage->hid) { case HID_GD_UP: usage->hat_dir = 1; break; case HID_GD_DOWN: usage->hat_dir = 5; break; case HID_GD_RIGHT: usage->hat_dir = 3; break; case HID_GD_LEFT: usage->hat_dir = 7; break; default: goto unknown; } if (field->dpad) { map_abs(field->dpad); goto ignore; } map_abs(ABS_HAT0X); break; } switch (usage->hid) { /* These usage IDs map directly to the usage codes. */ case HID_GD_X: case HID_GD_Y: case HID_GD_Z: case HID_GD_RX: case HID_GD_RY: case HID_GD_RZ: if (field->flags & HID_MAIN_ITEM_RELATIVE) map_rel(usage->hid & 0xf); else map_abs_clear(usage->hid & 0xf); break; case HID_GD_WHEEL: if (field->flags & HID_MAIN_ITEM_RELATIVE) { set_bit(REL_WHEEL, input->relbit); map_rel(REL_WHEEL_HI_RES); } else { map_abs(usage->hid & 0xf); } break; case HID_GD_SLIDER: case HID_GD_DIAL: if (field->flags & HID_MAIN_ITEM_RELATIVE) map_rel(usage->hid & 0xf); else map_abs(usage->hid & 0xf); break; case HID_GD_HATSWITCH: usage->hat_min = field->logical_minimum; usage->hat_max = field->logical_maximum; map_abs(ABS_HAT0X); break; case HID_GD_START: map_key_clear(BTN_START); break; case HID_GD_SELECT: map_key_clear(BTN_SELECT); break; case HID_GD_RFKILL_BTN: /* MS wireless radio ctl extension, also check CA */ if (field->application == HID_GD_WIRELESS_RADIO_CTLS) { map_key_clear(KEY_RFKILL); /* We need to simulate the btn release */ field->flags |= HID_MAIN_ITEM_RELATIVE; break; } default: goto unknown; } break; case HID_UP_LED: switch (usage->hid & 0xffff) { /* HID-Value: */ case 0x01: map_led (LED_NUML); break; /* "Num Lock" */ case 0x02: map_led (LED_CAPSL); break; /* "Caps Lock" */ case 0x03: map_led (LED_SCROLLL); break; /* "Scroll Lock" */ case 0x04: map_led (LED_COMPOSE); break; /* "Compose" */ case 0x05: map_led (LED_KANA); break; /* "Kana" */ case 0x27: map_led (LED_SLEEP); break; /* "Stand-By" */ case 0x4c: map_led (LED_SUSPEND); break; /* "System Suspend" */ case 0x09: map_led (LED_MUTE); break; /* "Mute" */ case 0x4b: map_led (LED_MISC); break; /* "Generic Indicator" */ case 0x19: map_led (LED_MAIL); break; /* "Message Waiting" */ case 0x4d: map_led (LED_CHARGING); break; /* "External Power Connected" */ default: goto ignore; } break; case HID_UP_DIGITIZER: if ((field->application & 0xff) == 0x01) /* Digitizer */ __set_bit(INPUT_PROP_POINTER, input->propbit); else if ((field->application & 0xff) == 0x02) /* Pen */ __set_bit(INPUT_PROP_DIRECT, input->propbit); switch (usage->hid & 0xff) { case 0x00: /* Undefined */ goto ignore; case 0x30: /* TipPressure */ if (!test_bit(BTN_TOUCH, input->keybit)) { device->quirks |= HID_QUIRK_NOTOUCH; set_bit(EV_KEY, input->evbit); set_bit(BTN_TOUCH, input->keybit); } map_abs_clear(ABS_PRESSURE); break; case 0x32: /* InRange */ switch (field->physical & 0xff) { case 0x21: map_key(BTN_TOOL_MOUSE); break; case 0x22: map_key(BTN_TOOL_FINGER); break; default: map_key(BTN_TOOL_PEN); break; } break; case 0x3b: /* Battery Strength */ hidinput_setup_battery(device, HID_INPUT_REPORT, field); usage->type = EV_PWR; goto ignore; case 0x3c: /* Invert */ map_key_clear(BTN_TOOL_RUBBER); break; case 0x3d: /* X Tilt */ map_abs_clear(ABS_TILT_X); break; case 0x3e: /* Y Tilt */ map_abs_clear(ABS_TILT_Y); break; case 0x33: /* Touch */ case 0x42: /* TipSwitch */ case 0x43: /* TipSwitch2 */ device->quirks &= ~HID_QUIRK_NOTOUCH; map_key_clear(BTN_TOUCH); break; case 0x44: /* BarrelSwitch */ map_key_clear(BTN_STYLUS); break; case 0x45: /* ERASER */ /* * This event is reported when eraser tip touches the surface. * Actual eraser (BTN_TOOL_RUBBER) is set by Invert usage when * tool gets in proximity. */ map_key_clear(BTN_TOUCH); break; case 0x46: /* TabletPick */ case 0x5a: /* SecondaryBarrelSwitch */ map_key_clear(BTN_STYLUS2); break; case 0x5b: /* TransducerSerialNumber */ usage->type = EV_MSC; usage->code = MSC_SERIAL; bit = input->mscbit; max = MSC_MAX; break; default: goto unknown; } break; case HID_UP_TELEPHONY: switch (usage->hid & HID_USAGE) { case 0x2f: map_key_clear(KEY_MICMUTE); break; case 0xb0: map_key_clear(KEY_NUMERIC_0); break; case 0xb1: map_key_clear(KEY_NUMERIC_1); break; case 0xb2: map_key_clear(KEY_NUMERIC_2); break; case 0xb3: map_key_clear(KEY_NUMERIC_3); break; case 0xb4: map_key_clear(KEY_NUMERIC_4); break; case 0xb5: map_key_clear(KEY_NUMERIC_5); break; case 0xb6: map_key_clear(KEY_NUMERIC_6); break; case 0xb7: map_key_clear(KEY_NUMERIC_7); break; case 0xb8: map_key_clear(KEY_NUMERIC_8); break; case 0xb9: map_key_clear(KEY_NUMERIC_9); break; case 0xba: map_key_clear(KEY_NUMERIC_STAR); break; case 0xbb: map_key_clear(KEY_NUMERIC_POUND); break; case 0xbc: map_key_clear(KEY_NUMERIC_A); break; case 0xbd: map_key_clear(KEY_NUMERIC_B); break; case 0xbe: map_key_clear(KEY_NUMERIC_C); break; case 0xbf: map_key_clear(KEY_NUMERIC_D); break; default: goto ignore; } break; case HID_UP_CONSUMER: /* USB HUT v1.12, pages 75-84 */ switch (usage->hid & HID_USAGE) { case 0x000: goto ignore; case 0x030: map_key_clear(KEY_POWER); break; case 0x031: map_key_clear(KEY_RESTART); break; case 0x032: map_key_clear(KEY_SLEEP); break; case 0x034: map_key_clear(KEY_SLEEP); break; case 0x035: map_key_clear(KEY_KBDILLUMTOGGLE); break; case 0x036: map_key_clear(BTN_MISC); break; case 0x040: map_key_clear(KEY_MENU); break; /* Menu */ case 0x041: map_key_clear(KEY_SELECT); break; /* Menu Pick */ case 0x042: map_key_clear(KEY_UP); break; /* Menu Up */ case 0x043: map_key_clear(KEY_DOWN); break; /* Menu Down */ case 0x044: map_key_clear(KEY_LEFT); break; /* Menu Left */ case 0x045: map_key_clear(KEY_RIGHT); break; /* Menu Right */ case 0x046: map_key_clear(KEY_ESC); break; /* Menu Escape */ case 0x047: map_key_clear(KEY_KPPLUS); break; /* Menu Value Increase */ case 0x048: map_key_clear(KEY_KPMINUS); break; /* Menu Value Decrease */ case 0x060: map_key_clear(KEY_INFO); break; /* Data On Screen */ case 0x061: map_key_clear(KEY_SUBTITLE); break; /* Closed Caption */ case 0x063: map_key_clear(KEY_VCR); break; /* VCR/TV */ case 0x065: map_key_clear(KEY_CAMERA); break; /* Snapshot */ case 0x069: map_key_clear(KEY_RED); break; case 0x06a: map_key_clear(KEY_GREEN); break; case 0x06b: map_key_clear(KEY_BLUE); break; case 0x06c: map_key_clear(KEY_YELLOW); break; case 0x06d: map_key_clear(KEY_ASPECT_RATIO); break; case 0x06f: map_key_clear(KEY_BRIGHTNESSUP); break; case 0x070: map_key_clear(KEY_BRIGHTNESSDOWN); break; case 0x072: map_key_clear(KEY_BRIGHTNESS_TOGGLE); break; case 0x073: map_key_clear(KEY_BRIGHTNESS_MIN); break; case 0x074: map_key_clear(KEY_BRIGHTNESS_MAX); break; case 0x075: map_key_clear(KEY_BRIGHTNESS_AUTO); break; case 0x079: map_key_clear(KEY_KBDILLUMUP); break; case 0x07a: map_key_clear(KEY_KBDILLUMDOWN); break; case 0x07c: map_key_clear(KEY_KBDILLUMTOGGLE); break; case 0x082: map_key_clear(KEY_VIDEO_NEXT); break; case 0x083: map_key_clear(KEY_LAST); break; case 0x084: map_key_clear(KEY_ENTER); break; case 0x088: map_key_clear(KEY_PC); break; case 0x089: map_key_clear(KEY_TV); break; case 0x08a: map_key_clear(KEY_WWW); break; case 0x08b: map_key_clear(KEY_DVD); break; case 0x08c: map_key_clear(KEY_PHONE); break; case 0x08d: map_key_clear(KEY_PROGRAM); break; case 0x08e: map_key_clear(KEY_VIDEOPHONE); break; case 0x08f: map_key_clear(KEY_GAMES); break; case 0x090: map_key_clear(KEY_MEMO); break; case 0x091: map_key_clear(KEY_CD); break; case 0x092: map_key_clear(KEY_VCR); break; case 0x093: map_key_clear(KEY_TUNER); break; case 0x094: map_key_clear(KEY_EXIT); break; case 0x095: map_key_clear(KEY_HELP); break; case 0x096: map_key_clear(KEY_TAPE); break; case 0x097: map_key_clear(KEY_TV2); break; case 0x098: map_key_clear(KEY_SAT); break; case 0x09a: map_key_clear(KEY_PVR); break; case 0x09c: map_key_clear(KEY_CHANNELUP); break; case 0x09d: map_key_clear(KEY_CHANNELDOWN); break; case 0x0a0: map_key_clear(KEY_VCR2); break; case 0x0b0: map_key_clear(KEY_PLAY); break; case 0x0b1: map_key_clear(KEY_PAUSE); break; case 0x0b2: map_key_clear(KEY_RECORD); break; case 0x0b3: map_key_clear(KEY_FASTFORWARD); break; case 0x0b4: map_key_clear(KEY_REWIND); break; case 0x0b5: map_key_clear(KEY_NEXTSONG); break; case 0x0b6: map_key_clear(KEY_PREVIOUSSONG); break; case 0x0b7: map_key_clear(KEY_STOPCD); break; case 0x0b8: map_key_clear(KEY_EJECTCD); break; case 0x0bc: map_key_clear(KEY_MEDIA_REPEAT); break; case 0x0b9: map_key_clear(KEY_SHUFFLE); break; case 0x0bf: map_key_clear(KEY_SLOW); break; case 0x0cd: map_key_clear(KEY_PLAYPAUSE); break; case 0x0cf: map_key_clear(KEY_VOICECOMMAND); break; case 0x0e0: map_abs_clear(ABS_VOLUME); break; case 0x0e2: map_key_clear(KEY_MUTE); break; case 0x0e5: map_key_clear(KEY_BASSBOOST); break; case 0x0e9: map_key_clear(KEY_VOLUMEUP); break; case 0x0ea: map_key_clear(KEY_VOLUMEDOWN); break; case 0x0f5: map_key_clear(KEY_SLOW); break; case 0x181: map_key_clear(KEY_BUTTONCONFIG); break; case 0x182: map_key_clear(KEY_BOOKMARKS); break; case 0x183: map_key_clear(KEY_CONFIG); break; case 0x184: map_key_clear(KEY_WORDPROCESSOR); break; case 0x185: map_key_clear(KEY_EDITOR); break; case 0x186: map_key_clear(KEY_SPREADSHEET); break; case 0x187: map_key_clear(KEY_GRAPHICSEDITOR); break; case 0x188: map_key_clear(KEY_PRESENTATION); break; case 0x189: map_key_clear(KEY_DATABASE); break; case 0x18a: map_key_clear(KEY_MAIL); break; case 0x18b: map_key_clear(KEY_NEWS); break; case 0x18c: map_key_clear(KEY_VOICEMAIL); break; case 0x18d: map_key_clear(KEY_ADDRESSBOOK); break; case 0x18e: map_key_clear(KEY_CALENDAR); break; case 0x18f: map_key_clear(KEY_TASKMANAGER); break; case 0x190: map_key_clear(KEY_JOURNAL); break; case 0x191: map_key_clear(KEY_FINANCE); break; case 0x192: map_key_clear(KEY_CALC); break; case 0x193: map_key_clear(KEY_PLAYER); break; case 0x194: map_key_clear(KEY_FILE); break; case 0x196: map_key_clear(KEY_WWW); break; case 0x199: map_key_clear(KEY_CHAT); break; case 0x19c: map_key_clear(KEY_LOGOFF); break; case 0x19e: map_key_clear(KEY_COFFEE); break; case 0x19f: map_key_clear(KEY_CONTROLPANEL); break; case 0x1a2: map_key_clear(KEY_APPSELECT); break; case 0x1a3: map_key_clear(KEY_NEXT); break; case 0x1a4: map_key_clear(KEY_PREVIOUS); break; case 0x1a6: map_key_clear(KEY_HELP); break; case 0x1a7: map_key_clear(KEY_DOCUMENTS); break; case 0x1ab: map_key_clear(KEY_SPELLCHECK); break; case 0x1ae: map_key_clear(KEY_KEYBOARD); break; case 0x1b1: map_key_clear(KEY_SCREENSAVER); break; case 0x1b4: map_key_clear(KEY_FILE); break; case 0x1b6: map_key_clear(KEY_IMAGES); break; case 0x1b7: map_key_clear(KEY_AUDIO); break; case 0x1b8: map_key_clear(KEY_VIDEO); break; case 0x1bc: map_key_clear(KEY_MESSENGER); break; case 0x1bd: map_key_clear(KEY_INFO); break; case 0x1cb: map_key_clear(KEY_ASSISTANT); break; case 0x201: map_key_clear(KEY_NEW); break; case 0x202: map_key_clear(KEY_OPEN); break; case 0x203: map_key_clear(KEY_CLOSE); break; case 0x204: map_key_clear(KEY_EXIT); break; case 0x207: map_key_clear(KEY_SAVE); break; case 0x208: map_key_clear(KEY_PRINT); break; case 0x209: map_key_clear(KEY_PROPS); break; case 0x21a: map_key_clear(KEY_UNDO); break; case 0x21b: map_key_clear(KEY_COPY); break; case 0x21c: map_key_clear(KEY_CUT); break; case 0x21d: map_key_clear(KEY_PASTE); break; case 0x21f: map_key_clear(KEY_FIND); break; case 0x221: map_key_clear(KEY_SEARCH); break; case 0x222: map_key_clear(KEY_GOTO); break; case 0x223: map_key_clear(KEY_HOMEPAGE); break; case 0x224: map_key_clear(KEY_BACK); break; case 0x225: map_key_clear(KEY_FORWARD); break; case 0x226: map_key_clear(KEY_STOP); break; case 0x227: map_key_clear(KEY_REFRESH); break; case 0x22a: map_key_clear(KEY_BOOKMARKS); break; case 0x22d: map_key_clear(KEY_ZOOMIN); break; case 0x22e: map_key_clear(KEY_ZOOMOUT); break; case 0x22f: map_key_clear(KEY_ZOOMRESET); break; case 0x232: map_key_clear(KEY_FULL_SCREEN); break; case 0x233: map_key_clear(KEY_SCROLLUP); break; case 0x234: map_key_clear(KEY_SCROLLDOWN); break; case 0x238: /* AC Pan */ set_bit(REL_HWHEEL, input->relbit); map_rel(REL_HWHEEL_HI_RES); break; case 0x23d: map_key_clear(KEY_EDIT); break; case 0x25f: map_key_clear(KEY_CANCEL); break; case 0x269: map_key_clear(KEY_INSERT); break; case 0x26a: map_key_clear(KEY_DELETE); break; case 0x279: map_key_clear(KEY_REDO); break; case 0x289: map_key_clear(KEY_REPLY); break; case 0x28b: map_key_clear(KEY_FORWARDMAIL); break; case 0x28c: map_key_clear(KEY_SEND); break; case 0x29d: map_key_clear(KEY_KBD_LAYOUT_NEXT); break; case 0x2c7: map_key_clear(KEY_KBDINPUTASSIST_PREV); break; case 0x2c8: map_key_clear(KEY_KBDINPUTASSIST_NEXT); break; case 0x2c9: map_key_clear(KEY_KBDINPUTASSIST_PREVGROUP); break; case 0x2ca: map_key_clear(KEY_KBDINPUTASSIST_NEXTGROUP); break; case 0x2cb: map_key_clear(KEY_KBDINPUTASSIST_ACCEPT); break; case 0x2cc: map_key_clear(KEY_KBDINPUTASSIST_CANCEL); break; case 0x29f: map_key_clear(KEY_SCALE); break; default: map_key_clear(KEY_UNKNOWN); } break; case HID_UP_GENDEVCTRLS: switch (usage->hid) { case HID_DC_BATTERYSTRENGTH: hidinput_setup_battery(device, HID_INPUT_REPORT, field); usage->type = EV_PWR; goto ignore; } goto unknown; case HID_UP_HPVENDOR: /* Reported on a Dutch layout HP5308 */ set_bit(EV_REP, input->evbit); switch (usage->hid & HID_USAGE) { case 0x021: map_key_clear(KEY_PRINT); break; case 0x070: map_key_clear(KEY_HP); break; case 0x071: map_key_clear(KEY_CAMERA); break; case 0x072: map_key_clear(KEY_SOUND); break; case 0x073: map_key_clear(KEY_QUESTION); break; case 0x080: map_key_clear(KEY_EMAIL); break; case 0x081: map_key_clear(KEY_CHAT); break; case 0x082: map_key_clear(KEY_SEARCH); break; case 0x083: map_key_clear(KEY_CONNECT); break; case 0x084: map_key_clear(KEY_FINANCE); break; case 0x085: map_key_clear(KEY_SPORT); break; case 0x086: map_key_clear(KEY_SHOP); break; default: goto ignore; } break; case HID_UP_HPVENDOR2: set_bit(EV_REP, input->evbit); switch (usage->hid & HID_USAGE) { case 0x001: map_key_clear(KEY_MICMUTE); break; case 0x003: map_key_clear(KEY_BRIGHTNESSDOWN); break; case 0x004: map_key_clear(KEY_BRIGHTNESSUP); break; default: goto ignore; } break; case HID_UP_MSVENDOR: goto ignore; case HID_UP_CUSTOM: /* Reported on Logitech and Apple USB keyboards */ set_bit(EV_REP, input->evbit); goto ignore; case HID_UP_LOGIVENDOR: /* intentional fallback */ case HID_UP_LOGIVENDOR2: /* intentional fallback */ case HID_UP_LOGIVENDOR3: goto ignore; case HID_UP_PID: switch (usage->hid & HID_USAGE) { case 0xa4: map_key_clear(BTN_DEAD); break; default: goto ignore; } break; default: unknown: if (field->report_size == 1) { if (field->report->type == HID_OUTPUT_REPORT) { map_led(LED_MISC); break; } map_key(BTN_MISC); break; } if (field->flags & HID_MAIN_ITEM_RELATIVE) { map_rel(REL_MISC); break; } map_abs(ABS_MISC); break; } mapped: if (device->driver->input_mapped && device->driver->input_mapped(device, hidinput, field, usage, &bit, &max) < 0) { /* * The driver indicated that no further generic handling * of the usage is desired. */ return; } set_bit(usage->type, input->evbit); /* * This part is *really* controversial: * - HID aims at being generic so we should do our best to export * all incoming events * - HID describes what events are, so there is no reason for ABS_X * to be mapped to ABS_Y * - HID is using *_MISC+N as a default value, but nothing prevents * *_MISC+N to overwrite a legitimate even, which confuses userspace * (for instance ABS_MISC + 7 is ABS_MT_SLOT, which has a different * processing) * * If devices still want to use this (at their own risk), they will * have to use the quirk HID_QUIRK_INCREMENT_USAGE_ON_DUPLICATE, but * the default should be a reliable mapping. */ while (usage->code <= max && test_and_set_bit(usage->code, bit)) { if (device->quirks & HID_QUIRK_INCREMENT_USAGE_ON_DUPLICATE) { usage->code = find_next_zero_bit(bit, max + 1, usage->code); } else { device->status |= HID_STAT_DUP_DETECTED; goto ignore; } } if (usage->code > max) goto ignore; if (usage->type == EV_ABS) { int a = field->logical_minimum; int b = field->logical_maximum; if ((device->quirks & HID_QUIRK_BADPAD) && (usage->code == ABS_X || usage->code == ABS_Y)) { a = field->logical_minimum = 0; b = field->logical_maximum = 255; } if (field->application == HID_GD_GAMEPAD || field->application == HID_GD_JOYSTICK) input_set_abs_params(input, usage->code, a, b, (b - a) >> 8, (b - a) >> 4); else input_set_abs_params(input, usage->code, a, b, 0, 0); input_abs_set_res(input, usage->code, hidinput_calc_abs_res(field, usage->code)); /* use a larger default input buffer for MT devices */ if (usage->code == ABS_MT_POSITION_X && input->hint_events_per_packet == 0) input_set_events_per_packet(input, 60); } if (usage->type == EV_ABS && (usage->hat_min < usage->hat_max || usage->hat_dir)) { int i; for (i = usage->code; i < usage->code + 2 && i <= max; i++) { input_set_abs_params(input, i, -1, 1, 0, 0); set_bit(i, input->absbit); } if (usage->hat_dir && !field->dpad) field->dpad = usage->code; } /* for those devices which produce Consumer volume usage as relative, * we emulate pressing volumeup/volumedown appropriate number of times * in hidinput_hid_event() */ if ((usage->type == EV_ABS) && (field->flags & HID_MAIN_ITEM_RELATIVE) && (usage->code == ABS_VOLUME)) { set_bit(KEY_VOLUMEUP, input->keybit); set_bit(KEY_VOLUMEDOWN, input->keybit); } if (usage->type == EV_KEY) { set_bit(EV_MSC, input->evbit); set_bit(MSC_SCAN, input->mscbit); } return; ignore: usage->type = 0; usage->code = 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: core: Sanitize event code and type when mapping input When calling into hid_map_usage(), the passed event code is blindly stored as is, even if it doesn't fit in the associated bitmap. This event code can come from a variety of sources, including devices masquerading as input devices, only a bit more "programmable". Instead of taking the event code at face value, check that it actually fits the corresponding bitmap, and if it doesn't: - spit out a warning so that we know which device is acting up - NULLify the bitmap pointer so that we catch unexpected uses Code paths that can make use of untrusted inputs can now check that the mapping was indeed correct and bail out if not. Cc: stable@vger.kernel.org Signed-off-by: Marc Zyngier <maz@kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@gmail.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: authzPretty( Syntax *syntax, struct berval *val, struct berval *out, void *ctx) { int rc; Debug( LDAP_DEBUG_TRACE, ">>> authzPretty: <%s>\n", val->bv_val, 0, 0 ); rc = authzPrettyNormal( val, out, ctx, 0 ); Debug( LDAP_DEBUG_TRACE, "<<< authzPretty: <%s> (%d)\n", out->bv_val, rc, 0 ); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'ITS#9406 fix debug msg'</s>
<s>[INST] Given the following code containing errors, provide 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 cancel_extop( Operation *op, SlapReply *rs ) { Operation *o; int rc; int opid; BerElementBuffer berbuf; BerElement *ber = (BerElement *)&berbuf; assert( ber_bvcmp( &slap_EXOP_CANCEL, &op->ore_reqoid ) == 0 ); if ( op->ore_reqdata == NULL ) { rs->sr_text = "no message ID supplied"; return LDAP_PROTOCOL_ERROR; } if ( op->ore_reqdata->bv_len == 0 ) { rs->sr_text = "empty request data field"; return LDAP_PROTOCOL_ERROR; } /* ber_init2 uses reqdata directly, doesn't allocate new buffers */ ber_init2( ber, op->ore_reqdata, 0 ); if ( ber_scanf( ber, "{i}", &opid ) == LBER_ERROR ) { rs->sr_text = "message ID parse failed"; return LDAP_PROTOCOL_ERROR; } Statslog( LDAP_DEBUG_STATS, "%s CANCEL msg=%d\n", op->o_log_prefix, opid, 0, 0, 0 ); if ( opid < 0 ) { rs->sr_text = "message ID invalid"; return LDAP_PROTOCOL_ERROR; } ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex ); if ( op->o_abandon ) { /* FIXME: Should instead reject the cancel/abandon of this op, but * it seems unsafe to reset op->o_abandon once it is set. ITS#6138. */ rc = LDAP_OPERATIONS_ERROR; rs->sr_text = "tried to abandon or cancel this operation"; goto out; } LDAP_STAILQ_FOREACH( o, &op->o_conn->c_pending_ops, o_next ) { if ( o->o_msgid == opid ) { /* TODO: We could instead remove the cancelled operation * from c_pending_ops like Abandon does, and send its * response here. Not if it is pending because of a * congested connection though. */ rc = LDAP_CANNOT_CANCEL; rs->sr_text = "too busy for Cancel, try Abandon instead"; goto out; } } LDAP_STAILQ_FOREACH( o, &op->o_conn->c_ops, o_next ) { if ( o->o_msgid == opid ) { break; } } if ( o == NULL ) { rc = LDAP_NO_SUCH_OPERATION; rs->sr_text = "message ID not found"; } else if ( o->o_tag == LDAP_REQ_BIND || o->o_tag == LDAP_REQ_UNBIND || o->o_tag == LDAP_REQ_ABANDON ) { rc = LDAP_CANNOT_CANCEL; } else if ( o->o_cancel != SLAP_CANCEL_NONE ) { rc = LDAP_OPERATIONS_ERROR; rs->sr_text = "message ID already being cancelled"; #if 0 } else if ( o->o_abandon ) { /* TODO: Would this break something when * o_abandon="suppress response"? (ITS#6138) */ rc = LDAP_TOO_LATE; #endif } else { rc = LDAP_SUCCESS; o->o_cancel = SLAP_CANCEL_REQ; o->o_abandon = 1; } out: ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex ); if ( rc == LDAP_SUCCESS ) { LDAP_STAILQ_FOREACH( op->o_bd, &backendDB, be_next ) { if( !op->o_bd->be_cancel ) continue; op->oq_cancel.rs_msgid = opid; if ( op->o_bd->be_cancel( op, rs ) == LDAP_SUCCESS ) { return LDAP_SUCCESS; } } do { /* Fake a cond_wait with thread_yield, then * verify the result properly mutex-protected. */ while ( o->o_cancel == SLAP_CANCEL_REQ ) ldap_pvt_thread_yield(); ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex ); rc = o->o_cancel; ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex ); } while ( rc == SLAP_CANCEL_REQ ); if ( rc == SLAP_CANCEL_ACK ) { rc = LDAP_SUCCESS; } o->o_cancel = SLAP_CANCEL_DONE; } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'ITS#9428 fix cancel exop'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: key_share_send_params(gnutls_session_t session, gnutls_buffer_st * extdata) { unsigned i; int ret; unsigned char *lengthp; unsigned int cur_length; unsigned int generated = 0; const gnutls_group_entry_st *group; const version_entry_st *ver; /* this extension is only being sent on client side */ if (session->security_parameters.entity == GNUTLS_CLIENT) { ver = _gnutls_version_max(session); if (unlikely(ver == NULL || ver->key_shares == 0)) return 0; if (!have_creds_for_tls13(session)) return 0; /* write the total length later */ lengthp = &extdata->data[extdata->length]; ret = _gnutls_buffer_append_prefix(extdata, 16, 0); if (ret < 0) return gnutls_assert_val(ret); cur_length = extdata->length; if (session->internals.hsk_flags & HSK_HRR_RECEIVED) { /* we know the group */ group = get_group(session); if (unlikely(group == NULL)) return gnutls_assert_val(GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER); ret = client_gen_key_share(session, group, extdata); if (ret == GNUTLS_E_INT_RET_0) return gnutls_assert_val(GNUTLS_E_NO_COMMON_KEY_SHARE); if (ret < 0) return gnutls_assert_val(ret); } else { gnutls_pk_algorithm_t selected_groups[3]; unsigned max_groups = 2; /* GNUTLS_KEY_SHARE_TOP2 */ if (session->internals.flags & GNUTLS_KEY_SHARE_TOP) max_groups = 1; else if (session->internals.flags & GNUTLS_KEY_SHARE_TOP3) max_groups = 3; assert(max_groups <= sizeof(selected_groups)/sizeof(selected_groups[0])); /* generate key shares for out top-(max_groups) groups * if they are of different PK type. */ for (i = 0; i < session->internals.priorities->groups.size; i++) { group = session->internals.priorities->groups.entry[i]; if (generated == 1 && group->pk == selected_groups[0]) continue; else if (generated == 2 && (group->pk == selected_groups[1] || group->pk == selected_groups[0])) continue; selected_groups[generated] = group->pk; ret = client_gen_key_share(session, group, extdata); if (ret == GNUTLS_E_INT_RET_0) continue; /* no key share for this algorithm */ if (ret < 0) return gnutls_assert_val(ret); generated++; if (generated >= max_groups) break; } } /* copy actual length */ _gnutls_write_uint16(extdata->length - cur_length, lengthp); } else { /* server */ ver = get_version(session); if (unlikely(ver == NULL || ver->key_shares == 0)) return gnutls_assert_val(0); if (_gnutls_ext_get_msg(session) == GNUTLS_EXT_FLAG_HRR) { group = session->internals.cand_group; if (group == NULL) return gnutls_assert_val(GNUTLS_E_NO_COMMON_KEY_SHARE); _gnutls_session_group_set(session, group); _gnutls_handshake_log("EXT[%p]: requesting retry with group %s\n", session, group->name); ret = _gnutls_buffer_append_prefix(extdata, 16, group->tls_id); if (ret < 0) return gnutls_assert_val(ret); } else { /* if we are negotiating PSK without DH, do not send a key share */ if ((session->internals.hsk_flags & HSK_PSK_SELECTED) && (session->internals.hsk_flags & HSK_PSK_KE_MODE_PSK)) return gnutls_assert_val(0); group = get_group(session); if (unlikely(group == NULL)) return gnutls_assert_val(GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER); ret = server_gen_key_share(session, group, extdata); if (ret < 0) return gnutls_assert_val(ret); } session->internals.hsk_flags |= HSK_KEY_SHARE_SENT; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'key_share: avoid use-after-free around realloc Signed-off-by: Daiki Ueno <ueno@gnu.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 DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g) { if(!p || !g) /* q is optional */ return 0; BN_free(dh->p); BN_free(dh->q); BN_free(dh->g); dh->p = p; dh->q = q; dh->g = g; if(q) dh->length = BN_num_bits(q); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'stunnel-5.57'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: NOEXPORT char *parse_service_option(CMD cmd, SERVICE_OPTIONS **section_ptr, char *opt, char *arg) { SERVICE_OPTIONS *section; int endpoints=0; #ifndef USE_WIN32 struct group *gr; struct passwd *pw; #endif section=section_ptr ? *section_ptr : NULL; if(cmd==CMD_SET_DEFAULTS || cmd==CMD_SET_COPY) { section->ref=1; } else if(cmd==CMD_FREE) { if(section==&service_options || section==&new_service_options) s_log(LOG_DEBUG, "Deallocating section defaults"); else s_log(LOG_DEBUG, "Deallocating section [%s]", section->servname); } else if(cmd==CMD_PRINT_DEFAULTS || cmd==CMD_PRINT_HELP) { s_log(LOG_NOTICE, " "); s_log(LOG_NOTICE, "Service-level options:"); } /* accept */ switch(cmd) { case CMD_SET_DEFAULTS: addrlist_clear(&section->local_addr, 1); section->local_fd=NULL; break; case CMD_SET_COPY: addrlist_clear(&section->local_addr, 1); section->local_fd=NULL; name_list_dup(&section->local_addr.names, new_service_options.local_addr.names); break; case CMD_FREE: name_list_free(section->local_addr.names); str_free(section->local_addr.addr); str_free(section->local_fd); break; case CMD_SET_VALUE: if(strcasecmp(opt, "accept")) break; section->option.accept=1; name_list_append(&section->local_addr.names, arg); return NULL; /* OK */ case CMD_INITIALIZE: if(section->local_addr.names) { unsigned i; if(!addrlist_resolve(&section->local_addr)) return "Cannot resolve accept target"; section->local_fd=str_alloc_detached(section->local_addr.num*sizeof(SOCKET)); for(i=0; i<section->local_addr.num; ++i) section->local_fd[i]=INVALID_SOCKET; ++endpoints; } break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = [host:]port accept connections on specified host:port", "accept"); break; } /* CApath */ switch(cmd) { case CMD_SET_DEFAULTS: #if 0 section->ca_dir=(char *)X509_get_default_cert_dir(); #endif section->ca_dir=NULL; break; case CMD_SET_COPY: section->ca_dir=str_dup_detached(new_service_options.ca_dir); break; case CMD_FREE: str_free(section->ca_dir); break; case CMD_SET_VALUE: if(strcasecmp(opt, "CApath")) break; str_free(section->ca_dir); if(arg[0]) /* not empty */ section->ca_dir=str_dup_detached(arg); else section->ca_dir=NULL; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: #if 0 s_log(LOG_NOTICE, "%-22s = %s", "CApath", section->ca_dir ? section->ca_dir : "(none)"); #endif break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = CA certificate directory for 'verify' option", "CApath"); break; } /* CAfile */ switch(cmd) { case CMD_SET_DEFAULTS: #if 0 section->ca_file=(char *)X509_get_default_certfile(); #endif section->ca_file=NULL; break; case CMD_SET_COPY: section->ca_file=str_dup_detached(new_service_options.ca_file); break; case CMD_FREE: str_free(section->ca_file); break; case CMD_SET_VALUE: if(strcasecmp(opt, "CAfile")) break; str_free(section->ca_file); if(arg[0]) /* not empty */ section->ca_file=str_dup_detached(arg); else section->ca_file=NULL; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: #if 0 s_log(LOG_NOTICE, "%-22s = %s", "CAfile", section->ca_file ? section->ca_file : "(none)"); #endif break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = CA certificate file for 'verify' option", "CAfile"); break; } /* cert */ switch(cmd) { case CMD_SET_DEFAULTS: section->cert=NULL; break; case CMD_SET_COPY: section->cert=str_dup_detached(new_service_options.cert); break; case CMD_FREE: str_free(section->cert); break; case CMD_SET_VALUE: if(strcasecmp(opt, "cert")) break; str_free(section->cert); section->cert=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: #ifndef OPENSSL_NO_PSK if(section->psk_keys) break; #endif /* !defined(OPENSSL_NO_PSK) */ #ifndef OPENSSL_NO_ENGINE if(section->engine) break; #endif /* !defined(OPENSSL_NO_ENGINE) */ if(!section->option.client && !section->cert) return "TLS server needs a certificate"; break; case CMD_PRINT_DEFAULTS: break; /* no default certificate */ case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = certificate chain", "cert"); break; } #if OPENSSL_VERSION_NUMBER>=0x10002000L /* checkEmail */ switch(cmd) { case CMD_SET_DEFAULTS: section->check_email=NULL; break; case CMD_SET_COPY: name_list_dup(&section->check_email, new_service_options.check_email); break; case CMD_FREE: name_list_free(section->check_email); break; case CMD_SET_VALUE: if(strcasecmp(opt, "checkEmail")) break; name_list_append(&section->check_email, arg); return NULL; /* OK */ case CMD_INITIALIZE: if(section->check_email && !section->option.verify_chain && !section->option.verify_peer) return "Either \"verifyChain\" or \"verifyPeer\" has to be enabled"; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = peer certificate email address", "checkEmail"); break; } /* checkHost */ switch(cmd) { case CMD_SET_DEFAULTS: section->check_host=NULL; break; case CMD_SET_COPY: name_list_dup(&section->check_host, new_service_options.check_host); break; case CMD_FREE: name_list_free(section->check_host); break; case CMD_SET_VALUE: if(strcasecmp(opt, "checkHost")) break; name_list_append(&section->check_host, arg); return NULL; /* OK */ case CMD_INITIALIZE: if(section->check_host && !section->option.verify_chain && !section->option.verify_peer) return "Either \"verifyChain\" or \"verifyPeer\" has to be enabled"; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = peer certificate host name pattern", "checkHost"); break; } /* checkIP */ switch(cmd) { case CMD_SET_DEFAULTS: section->check_ip=NULL; break; case CMD_SET_COPY: name_list_dup(&section->check_ip, new_service_options.check_ip); break; case CMD_FREE: name_list_free(section->check_ip); break; case CMD_SET_VALUE: if(strcasecmp(opt, "checkIP")) break; name_list_append(&section->check_ip, arg); return NULL; /* OK */ case CMD_INITIALIZE: if(section->check_ip && !section->option.verify_chain && !section->option.verify_peer) return "Either \"verifyChain\" or \"verifyPeer\" has to be enabled"; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = peer certificate IP address", "checkIP"); break; } #endif /* OPENSSL_VERSION_NUMBER>=0x10002000L */ /* ciphers */ switch(cmd) { case CMD_SET_DEFAULTS: section->cipher_list=NULL; break; case CMD_SET_COPY: section->cipher_list=str_dup_detached(new_service_options.cipher_list); break; case CMD_FREE: str_free(section->cipher_list); break; case CMD_SET_VALUE: if(strcasecmp(opt, "ciphers")) break; str_free(section->cipher_list); section->cipher_list=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: if(!section->cipher_list) { /* this is only executed for global options, because * section->cipher_list is no longer NULL in sections */ #ifdef USE_FIPS if(new_global_options.option.fips) section->cipher_list=str_dup_detached("FIPS"); else #endif /* USE_FIPS */ section->cipher_list=str_dup_detached(stunnel_cipher_list); } break; case CMD_PRINT_DEFAULTS: #ifdef USE_FIPS s_log(LOG_NOTICE, "%-22s = %s %s", "ciphers", "FIPS", "(with \"fips = yes\")"); s_log(LOG_NOTICE, "%-22s = %s %s", "ciphers", stunnel_cipher_list, "(with \"fips = no\")"); #else s_log(LOG_NOTICE, "%-22s = %s", "ciphers", stunnel_cipher_list); #endif /* USE_FIPS */ break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = permitted ciphers for TLS 1.2 or older", "ciphers"); break; } #ifndef OPENSSL_NO_TLS1_3 /* ciphersuites */ switch(cmd) { case CMD_SET_DEFAULTS: section->ciphersuites=NULL; break; case CMD_SET_COPY: section->ciphersuites=str_dup_detached(new_service_options.ciphersuites); break; case CMD_FREE: str_free(section->ciphersuites); break; case CMD_SET_VALUE: if(strcasecmp(opt, "ciphersuites")) break; str_free(section->ciphersuites); section->ciphersuites=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: if(!section->ciphersuites) { /* this is only executed for global options, because * section->ciphersuites is no longer NULL in sections */ section->ciphersuites=str_dup_detached(stunnel_ciphersuites); } break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %s %s", "ciphersuites", stunnel_ciphersuites, "(with TLSv1.3)"); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = permitted ciphersuites for TLS 1.3", "ciphersuites"); break; } #endif /* TLS 1.3 */ /* client */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.client=0; break; case CMD_SET_COPY: section->option.client=new_service_options.option.client; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "client")) break; if(!strcasecmp(arg, "yes")) section->option.client=1; else if(!strcasecmp(arg, "no")) section->option.client=0; else return "The argument needs to be either 'yes' or 'no'"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no client mode (remote service uses TLS)", "client"); break; } #if OPENSSL_VERSION_NUMBER>=0x10002000L /* config */ switch(cmd) { case CMD_SET_DEFAULTS: section->config=NULL; break; case CMD_SET_COPY: name_list_dup(&section->config, new_service_options.config); break; case CMD_FREE: name_list_free(section->config); break; case CMD_SET_VALUE: if(strcasecmp(opt, "config")) break; name_list_append(&section->config, arg); return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = command[:parameter] to execute", "config"); break; } #endif /* OPENSSL_VERSION_NUMBER>=0x10002000L */ /* connect */ switch(cmd) { case CMD_SET_DEFAULTS: addrlist_clear(&section->connect_addr, 0); section->connect_session=NULL; break; case CMD_SET_COPY: addrlist_clear(&section->connect_addr, 0); section->connect_session=NULL; name_list_dup(&section->connect_addr.names, new_service_options.connect_addr.names); break; case CMD_FREE: name_list_free(section->connect_addr.names); str_free(section->connect_addr.addr); str_free(section->connect_session); break; case CMD_SET_VALUE: if(strcasecmp(opt, "connect")) break; name_list_append(&section->connect_addr.names, arg); return NULL; /* OK */ case CMD_INITIALIZE: if(section->connect_addr.names) { if(!section->option.delayed_lookup && !addrlist_resolve(&section->connect_addr)) { s_log(LOG_INFO, "Cannot resolve connect target - delaying DNS lookup"); section->connect_addr.num=0; section->redirect_addr.num=0; section->option.delayed_lookup=1; } if(section->option.client) section->connect_session= str_alloc_detached(section->connect_addr.num*sizeof(SSL_SESSION *)); ++endpoints; } break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = [host:]port to connect", "connect"); break; } /* CRLpath */ switch(cmd) { case CMD_SET_DEFAULTS: section->crl_dir=NULL; break; case CMD_SET_COPY: section->crl_dir=str_dup_detached(new_service_options.crl_dir); break; case CMD_FREE: str_free(section->crl_dir); break; case CMD_SET_VALUE: if(strcasecmp(opt, "CRLpath")) break; str_free(section->crl_dir); if(arg[0]) /* not empty */ section->crl_dir=str_dup_detached(arg); else section->crl_dir=NULL; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = CRL directory", "CRLpath"); break; } /* CRLfile */ switch(cmd) { case CMD_SET_DEFAULTS: section->crl_file=NULL; break; case CMD_SET_COPY: section->crl_file=str_dup_detached(new_service_options.crl_file); break; case CMD_FREE: str_free(section->crl_file); break; case CMD_SET_VALUE: if(strcasecmp(opt, "CRLfile")) break; str_free(section->crl_file); if(arg[0]) /* not empty */ section->crl_file=str_dup_detached(arg); else section->crl_file=NULL; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = CRL file", "CRLfile"); break; } #ifndef OPENSSL_NO_ECDH /* curves */ switch(cmd) { case CMD_SET_DEFAULTS: section->curves=str_dup_detached(DEFAULT_CURVES); break; case CMD_SET_COPY: section->curves=str_dup_detached(new_service_options.curves); break; case CMD_FREE: str_free(section->curves); break; case CMD_SET_VALUE: if(strcasecmp(opt, "curves") && strcasecmp(opt, "curve")) break; str_free(section->curves); section->curves=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %s", "curves", DEFAULT_CURVES); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = ECDH curve names", "curves"); break; } #endif /* !defined(OPENSSL_NO_ECDH) */ /* debug */ switch(cmd) { case CMD_SET_DEFAULTS: section->log_level=LOG_NOTICE; #if !defined (USE_WIN32) && !defined (__vms) new_global_options.log_facility=LOG_DAEMON; #endif break; case CMD_SET_COPY: section->log_level=new_service_options.log_level; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "debug")) break; return parse_debug_level(arg, section); case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: #if !defined (USE_WIN32) && !defined (__vms) s_log(LOG_NOTICE, "%-22s = %s", "debug", "daemon.notice"); #else s_log(LOG_NOTICE, "%-22s = %s", "debug", "notice"); #endif break; case CMD_PRINT_HELP: #if !defined (USE_WIN32) && !defined (__vms) s_log(LOG_NOTICE, "%-22s = [facility].level (e.g. daemon.info)", "debug"); #else s_log(LOG_NOTICE, "%-22s = level (e.g. info)", "debug"); #endif break; } /* delay */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.delayed_lookup=0; break; case CMD_SET_COPY: section->option.delayed_lookup=new_service_options.option.delayed_lookup; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "delay")) break; if(!strcasecmp(arg, "yes")) section->option.delayed_lookup=1; else if(!strcasecmp(arg, "no")) section->option.delayed_lookup=0; else return "The argument needs to be either 'yes' or 'no'"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no delay DNS lookup for 'connect' option", "delay"); break; } #ifndef OPENSSL_NO_ENGINE /* engineId */ switch(cmd) { case CMD_SET_DEFAULTS: break; case CMD_SET_COPY: section->engine=new_service_options.engine; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "engineId")) break; section->engine=engine_get_by_id(arg); if(!section->engine) return "Engine ID not found"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = ID of engine to read the key from", "engineId"); break; } /* engineNum */ switch(cmd) { case CMD_SET_DEFAULTS: break; case CMD_SET_COPY: section->engine=new_service_options.engine; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "engineNum")) break; { char *tmp_str; int tmp_int=(int)strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str) /* not a number */ return "Illegal engine number"; section->engine=engine_get_by_num(tmp_int-1); } if(!section->engine) return "Illegal engine number"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = number of engine to read the key from", "engineNum"); break; } #endif /* !defined(OPENSSL_NO_ENGINE) */ /* exec */ switch(cmd) { case CMD_SET_DEFAULTS: section->exec_name=NULL; break; case CMD_SET_COPY: section->exec_name=str_dup_detached(new_service_options.exec_name); break; case CMD_FREE: str_free(section->exec_name); break; case CMD_SET_VALUE: if(strcasecmp(opt, "exec")) break; str_free(section->exec_name); section->exec_name=str_dup_detached(arg); #ifdef USE_WIN32 section->exec_args=str_dup_detached(arg); #else if(!section->exec_args) { section->exec_args=str_alloc_detached(2*sizeof(char *)); section->exec_args[0]=str_dup_detached(section->exec_name); section->exec_args[1]=NULL; /* null-terminate */ } #endif return NULL; /* OK */ case CMD_INITIALIZE: if(section->exec_name) ++endpoints; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = file execute local inetd-type program", "exec"); break; } /* execArgs */ switch(cmd) { case CMD_SET_DEFAULTS: section->exec_args=NULL; break; case CMD_SET_COPY: #ifdef USE_WIN32 section->exec_args=str_dup_detached(new_service_options.exec_args); #else section->exec_args=arg_dup(new_service_options.exec_args); #endif break; case CMD_FREE: #ifdef USE_WIN32 str_free(section->exec_args); #else arg_free(section->exec_args); #endif break; case CMD_SET_VALUE: if(strcasecmp(opt, "execArgs")) break; #ifdef USE_WIN32 str_free(section->exec_args); section->exec_args=str_dup_detached(arg); #else arg_free(section->exec_args); section->exec_args=arg_alloc(arg); #endif return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = arguments for 'exec' (including $0)", "execArgs"); break; } /* failover */ switch(cmd) { case CMD_SET_DEFAULTS: section->failover=FAILOVER_PRIO; section->rr=0; break; case CMD_SET_COPY: section->failover=new_service_options.failover; section->rr=new_service_options.rr; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "failover")) break; if(!strcasecmp(arg, "rr")) section->failover=FAILOVER_RR; else if(!strcasecmp(arg, "prio")) section->failover=FAILOVER_PRIO; else return "The argument needs to be either 'rr' or 'prio'"; return NULL; /* OK */ case CMD_INITIALIZE: if(section->option.delayed_lookup) section->failover=FAILOVER_PRIO; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = rr|prio failover strategy", "failover"); break; } /* ident */ switch(cmd) { case CMD_SET_DEFAULTS: section->username=NULL; break; case CMD_SET_COPY: section->username=str_dup_detached(new_service_options.username); break; case CMD_FREE: str_free(section->username); break; case CMD_SET_VALUE: if(strcasecmp(opt, "ident")) break; str_free(section->username); section->username=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = username for IDENT (RFC 1413) checking", "ident"); break; } /* include */ switch(cmd) { case CMD_SET_DEFAULTS: break; case CMD_SET_COPY: break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "include")) break; return include_config(arg, section_ptr); case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = directory with configuration file snippets", "include"); break; } /* key */ switch(cmd) { case CMD_SET_DEFAULTS: section->key=NULL; break; case CMD_SET_COPY: section->key=str_dup_detached(new_service_options.key); break; case CMD_FREE: str_free(section->key); break; case CMD_SET_VALUE: if(strcasecmp(opt, "key")) break; str_free(section->key); section->key=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: if(section->cert && !section->key) section->key=str_dup_detached(section->cert); break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = certificate private key", "key"); break; } /* libwrap */ #ifdef USE_LIBWRAP switch(cmd) { case CMD_SET_DEFAULTS: section->option.libwrap=0; /* disable libwrap by default */ break; case CMD_SET_COPY: section->option.libwrap=new_service_options.option.libwrap; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "libwrap")) break; if(!strcasecmp(arg, "yes")) section->option.libwrap=1; else if(!strcasecmp(arg, "no")) section->option.libwrap=0; else return "The argument needs to be either 'yes' or 'no'"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no use /etc/hosts.allow and /etc/hosts.deny", "libwrap"); break; } #endif /* USE_LIBWRAP */ /* local */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.local=0; break; case CMD_SET_COPY: section->option.local=new_service_options.option.local; memcpy(&section->source_addr, &new_service_options.source_addr, sizeof(SOCKADDR_UNION)); break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "local")) break; if(!hostport2addr(&section->source_addr, arg, "0", 1)) return "Failed to resolve local address"; section->option.local=1; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = IP address to be used as source for remote" " connections", "local"); break; } /* logId */ switch(cmd) { case CMD_SET_DEFAULTS: section->log_id=LOG_ID_SEQUENTIAL; break; case CMD_SET_COPY: section->log_id=new_service_options.log_id; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "logId")) break; if(!strcasecmp(arg, "sequential")) section->log_id=LOG_ID_SEQUENTIAL; else if(!strcasecmp(arg, "unique")) section->log_id=LOG_ID_UNIQUE; else if(!strcasecmp(arg, "thread")) section->log_id=LOG_ID_THREAD; else if(!strcasecmp(arg, "process")) section->log_id=LOG_ID_PROCESS; else return "Invalid connection identifier type"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %s", "logId", "sequential"); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = connection identifier type", "logId"); break; } #ifndef OPENSSL_NO_OCSP /* OCSP */ switch(cmd) { case CMD_SET_DEFAULTS: section->ocsp_url=NULL; break; case CMD_SET_COPY: section->ocsp_url=str_dup_detached(new_service_options.ocsp_url); break; case CMD_FREE: str_free(section->ocsp_url); break; case CMD_SET_VALUE: if(strcasecmp(opt, "ocsp")) break; str_free(section->ocsp_url); section->ocsp_url=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = OCSP responder URL", "OCSP"); break; } /* OCSPaia */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.aia=0; /* disable AIA by default */ break; case CMD_SET_COPY: section->option.aia=new_service_options.option.aia; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "OCSPaia")) break; if(!strcasecmp(arg, "yes")) section->option.aia=1; else if(!strcasecmp(arg, "no")) section->option.aia=0; else return "The argument needs to be either 'yes' or 'no'"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no check the AIA responders from certificates", "OCSPaia"); break; } /* OCSPflag */ switch(cmd) { case CMD_SET_DEFAULTS: section->ocsp_flags=0; break; case CMD_SET_COPY: section->ocsp_flags=new_service_options.ocsp_flags; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "OCSPflag")) break; { unsigned long tmp_ulong=parse_ocsp_flag(arg); if(!tmp_ulong) return "Illegal OCSP flag"; section->ocsp_flags|=tmp_ulong; } return NULL; case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = OCSP responder flags", "OCSPflag"); break; } /* OCSPnonce */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.nonce=0; /* disable OCSP nonce by default */ break; case CMD_SET_COPY: section->option.nonce=new_service_options.option.nonce; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "OCSPnonce")) break; if(!strcasecmp(arg, "yes")) section->option.nonce=1; else if(!strcasecmp(arg, "no")) section->option.nonce=0; else return "The argument needs to be either 'yes' or 'no'"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no send and verify the OCSP nonce extension", "OCSPnonce"); break; } #endif /* !defined(OPENSSL_NO_OCSP) */ /* options */ switch(cmd) { case CMD_SET_DEFAULTS: section->ssl_options_set=0; #if OPENSSL_VERSION_NUMBER>=0x009080dfL section->ssl_options_clear=0; #endif /* OpenSSL 0.9.8m or later */ break; case CMD_SET_COPY: section->ssl_options_set=new_service_options.ssl_options_set; #if OPENSSL_VERSION_NUMBER>=0x009080dfL section->ssl_options_clear=new_service_options.ssl_options_clear; #endif /* OpenSSL 0.9.8m or later */ break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "options")) break; #if OPENSSL_VERSION_NUMBER>=0x009080dfL if(*arg=='-') { long unsigned tmp=parse_ssl_option(arg+1); if(tmp==INVALID_SSL_OPTION) return "Illegal TLS option"; section->ssl_options_clear|=tmp; return NULL; /* OK */ } #endif /* OpenSSL 0.9.8m or later */ { long unsigned tmp=parse_ssl_option(arg); if(tmp==INVALID_SSL_OPTION) return "Illegal TLS option"; section->ssl_options_set|=tmp; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %s", "options", "NO_SSLv2"); s_log(LOG_NOTICE, "%-22s = %s", "options", "NO_SSLv3"); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = TLS option to set/reset", "options"); break; } /* protocol */ switch(cmd) { case CMD_SET_DEFAULTS: section->protocol=NULL; break; case CMD_SET_COPY: section->protocol=str_dup_detached(new_service_options.protocol); break; case CMD_FREE: str_free(section->protocol); break; case CMD_SET_VALUE: if(strcasecmp(opt, "protocol")) break; str_free(section->protocol); section->protocol=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: /* PROTOCOL_CHECK also initializes: section->option.connect_before_ssl section->option.protocol_endpoint */ { char *tmp_str=protocol(NULL, section, PROTOCOL_CHECK); if(tmp_str) return tmp_str; } endpoints+=section->option.protocol_endpoint; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = protocol to negotiate before TLS initialization", "protocol"); s_log(LOG_NOTICE, "%25scurrently supported: cifs, connect, imap,", ""); s_log(LOG_NOTICE, "%25s nntp, pgsql, pop3, proxy, smtp, socks", ""); break; } /* protocolAuthentication */ switch(cmd) { case CMD_SET_DEFAULTS: section->protocol_authentication=str_dup_detached("basic"); break; case CMD_SET_COPY: section->protocol_authentication= str_dup_detached(new_service_options.protocol_authentication); break; case CMD_FREE: str_free(section->protocol_authentication); break; case CMD_SET_VALUE: if(strcasecmp(opt, "protocolAuthentication")) break; str_free(section->protocol_authentication); section->protocol_authentication=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = authentication type for protocol negotiations", "protocolAuthentication"); break; } /* protocolDomain */ switch(cmd) { case CMD_SET_DEFAULTS: section->protocol_domain=NULL; break; case CMD_SET_COPY: section->protocol_domain= str_dup_detached(new_service_options.protocol_domain); break; case CMD_FREE: str_free(section->protocol_domain); break; case CMD_SET_VALUE: if(strcasecmp(opt, "protocolDomain")) break; str_free(section->protocol_domain); section->protocol_domain=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = domain for protocol negotiations", "protocolDomain"); break; } /* protocolHost */ switch(cmd) { case CMD_SET_DEFAULTS: section->protocol_host=NULL; break; case CMD_SET_COPY: section->protocol_host= str_dup_detached(new_service_options.protocol_host); break; case CMD_FREE: str_free(section->protocol_host); break; case CMD_SET_VALUE: if(strcasecmp(opt, "protocolHost")) break; str_free(section->protocol_host); section->protocol_host=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = host:port for protocol negotiations", "protocolHost"); break; } /* protocolPassword */ switch(cmd) { case CMD_SET_DEFAULTS: section->protocol_password=NULL; break; case CMD_SET_COPY: section->protocol_password= str_dup_detached(new_service_options.protocol_password); break; case CMD_FREE: str_free(section->protocol_password); break; case CMD_SET_VALUE: if(strcasecmp(opt, "protocolPassword")) break; str_free(section->protocol_password); section->protocol_password=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = password for protocol negotiations", "protocolPassword"); break; } /* protocolUsername */ switch(cmd) { case CMD_SET_DEFAULTS: section->protocol_username=NULL; break; case CMD_SET_COPY: section->protocol_username= str_dup_detached(new_service_options.protocol_username); break; case CMD_FREE: str_free(section->protocol_username); break; case CMD_SET_VALUE: if(strcasecmp(opt, "protocolUsername")) break; str_free(section->protocol_username); section->protocol_username=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = username for protocol negotiations", "protocolUsername"); break; } #ifndef OPENSSL_NO_PSK /* PSKidentity */ switch(cmd) { case CMD_SET_DEFAULTS: section->psk_identity=NULL; section->psk_selected=NULL; section->psk_sorted.val=NULL; section->psk_sorted.num=0; break; case CMD_SET_COPY: section->psk_identity= str_dup_detached(new_service_options.psk_identity); break; case CMD_FREE: str_free(section->psk_identity); str_free(section->psk_sorted.val); break; case CMD_SET_VALUE: if(strcasecmp(opt, "PSKidentity")) break; str_free(section->psk_identity); section->psk_identity=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: if(!section->psk_keys) /* PSK not configured */ break; psk_sort(&section->psk_sorted, section->psk_keys); if(section->option.client) { if(section->psk_identity) { section->psk_selected= psk_find(&section->psk_sorted, section->psk_identity); if(!section->psk_selected) return "No key found for the specified PSK identity"; } else { /* take the first specified identity as default */ section->psk_selected=section->psk_keys; } } else { if(section->psk_identity) s_log(LOG_NOTICE, "PSK identity is ignored in the server mode"); } break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = identity for PSK authentication", "PSKidentity"); break; } /* PSKsecrets */ switch(cmd) { case CMD_SET_DEFAULTS: section->psk_keys=NULL; break; case CMD_SET_COPY: section->psk_keys=psk_dup(new_service_options.psk_keys); break; case CMD_FREE: psk_free(section->psk_keys); break; case CMD_SET_VALUE: if(strcasecmp(opt, "PSKsecrets")) break; section->psk_keys=psk_read(arg); if(!section->psk_keys) return "Failed to read PSK secrets"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = secrets for PSK authentication", "PSKsecrets"); break; } #endif /* !defined(OPENSSL_NO_PSK) */ /* pty */ #ifndef USE_WIN32 switch(cmd) { case CMD_SET_DEFAULTS: section->option.pty=0; break; case CMD_SET_COPY: section->option.pty=new_service_options.option.pty; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "pty")) break; if(!strcasecmp(arg, "yes")) section->option.pty=1; else if(!strcasecmp(arg, "no")) section->option.pty=0; else return "The argument needs to be either 'yes' or 'no'"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no allocate pseudo terminal for 'exec' option", "pty"); break; } #endif /* redirect */ switch(cmd) { case CMD_SET_DEFAULTS: addrlist_clear(&section->redirect_addr, 0); break; case CMD_SET_COPY: addrlist_clear(&section->redirect_addr, 0); name_list_dup(&section->redirect_addr.names, new_service_options.redirect_addr.names); break; case CMD_FREE: name_list_free(section->redirect_addr.names); str_free(section->redirect_addr.addr); break; case CMD_SET_VALUE: if(strcasecmp(opt, "redirect")) break; name_list_append(&section->redirect_addr.names, arg); return NULL; /* OK */ case CMD_INITIALIZE: if(section->redirect_addr.names) { if(section->option.client) return "\"redirect\" is unsupported in client sections"; if(section->option.connect_before_ssl) return "\"redirect\" is incompatible with the specified protocol negotiation"; if(!section->option.delayed_lookup && !addrlist_resolve(&section->redirect_addr)) { s_log(LOG_INFO, "Cannot resolve redirect target - delaying DNS lookup"); section->connect_addr.num=0; section->redirect_addr.num=0; section->option.delayed_lookup=1; } if(!section->option.verify_chain && !section->option.verify_peer) return "Either \"verifyChain\" or \"verifyPeer\" has to be enabled for \"redirect\" to work"; } break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = [host:]port to redirect on authentication failures", "redirect"); break; } /* renegotiation */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.renegotiation=1; break; case CMD_SET_COPY: section->option.renegotiation=new_service_options.option.renegotiation; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "renegotiation")) break; if(!strcasecmp(arg, "yes")) section->option.renegotiation=1; else if(!strcasecmp(arg, "no")) section->option.renegotiation=0; else return "The argument needs to be either 'yes' or 'no'"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no support renegotiation", "renegotiation"); break; } /* requireCert */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.require_cert=0; break; case CMD_SET_COPY: section->option.require_cert=new_service_options.option.require_cert; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "requireCert")) break; if(!strcasecmp(arg, "yes")) { section->option.request_cert=1; section->option.require_cert=1; } else if(!strcasecmp(arg, "no")) { section->option.require_cert=0; } else { return "The argument needs to be either 'yes' or 'no'"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no require client certificate", "requireCert"); break; } /* reset */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.reset=1; /* enabled by default */ break; case CMD_SET_COPY: section->option.reset=new_service_options.option.reset; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "reset")) break; if(!strcasecmp(arg, "yes")) section->option.reset=1; else if(!strcasecmp(arg, "no")) section->option.reset=0; else return "The argument needs to be either 'yes' or 'no'"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no send TCP RST on error", "reset"); break; } /* retry */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.retry=0; break; case CMD_SET_COPY: section->option.retry=new_service_options.option.retry; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "retry")) break; if(!strcasecmp(arg, "yes")) section->option.retry=1; else if(!strcasecmp(arg, "no")) section->option.retry=0; else return "The argument needs to be either 'yes' or 'no'"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no retry connect+exec section", "retry"); break; } #ifndef USE_WIN32 /* service */ switch(cmd) { case CMD_SET_DEFAULTS: section->servname=str_dup_detached("stunnel"); break; case CMD_SET_COPY: /* servname is *not* copied from the global section */ break; case CMD_FREE: /* deallocation is performed at the end CMD_FREE */ break; case CMD_SET_VALUE: if(strcasecmp(opt, "service")) break; str_free(section->servname); section->servname=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = service name", "service"); break; } #endif #ifndef USE_WIN32 /* setgid */ switch(cmd) { case CMD_SET_DEFAULTS: section->gid=0; break; case CMD_SET_COPY: section->gid=new_service_options.gid; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "setgid")) break; gr=getgrnam(arg); if(gr) { section->gid=gr->gr_gid; return NULL; /* OK */ } { char *tmp_str; section->gid=(gid_t)strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str) /* not a number */ return "Illegal GID"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = groupname for setgid()", "setgid"); break; } #endif #ifndef USE_WIN32 /* setuid */ switch(cmd) { case CMD_SET_DEFAULTS: section->uid=0; break; case CMD_SET_COPY: section->uid=new_service_options.uid; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "setuid")) break; pw=getpwnam(arg); if(pw) { section->uid=pw->pw_uid; return NULL; /* OK */ } { char *tmp_str; section->uid=(uid_t)strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str) /* not a number */ return "Illegal UID"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = username for setuid()", "setuid"); break; } #endif /* sessionCacheSize */ switch(cmd) { case CMD_SET_DEFAULTS: section->session_size=1000L; break; case CMD_SET_COPY: section->session_size=new_service_options.session_size; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "sessionCacheSize")) break; { char *tmp_str; section->session_size=strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str) /* not a number */ return "Illegal session cache size"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %ld", "sessionCacheSize", 1000L); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = session cache size", "sessionCacheSize"); break; } /* sessionCacheTimeout */ switch(cmd) { case CMD_SET_DEFAULTS: section->session_timeout=300L; break; case CMD_SET_COPY: section->session_timeout=new_service_options.session_timeout; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "sessionCacheTimeout") && strcasecmp(opt, "session")) break; { char *tmp_str; section->session_timeout=strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str) /* not a number */ return "Illegal session cache timeout"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %ld seconds", "sessionCacheTimeout", 300L); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = session cache timeout (in seconds)", "sessionCacheTimeout"); break; } /* sessiond */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.sessiond=0; memset(&section->sessiond_addr, 0, sizeof(SOCKADDR_UNION)); section->sessiond_addr.in.sin_family=AF_INET; break; case CMD_SET_COPY: section->option.sessiond=new_service_options.option.sessiond; memcpy(&section->sessiond_addr, &new_service_options.sessiond_addr, sizeof(SOCKADDR_UNION)); break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "sessiond")) break; section->option.sessiond=1; #ifdef SSL_OP_NO_TICKET /* disable RFC4507 support introduced in OpenSSL 0.9.8f */ /* this prevents session callbacks from being executed */ section->ssl_options_set|=SSL_OP_NO_TICKET; #endif if(!name2addr(&section->sessiond_addr, arg, 0)) return "Failed to resolve sessiond server address"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = [host:]port use sessiond at host:port", "sessiond"); break; } #ifndef OPENSSL_NO_TLSEXT /* sni */ switch(cmd) { case CMD_SET_DEFAULTS: section->servername_list_head=NULL; section->servername_list_tail=NULL; break; case CMD_SET_COPY: section->sni= str_dup_detached(new_service_options.sni); break; case CMD_FREE: str_free(section->sni); sni_free(section); break; case CMD_SET_VALUE: if(strcasecmp(opt, "sni")) break; str_free(section->sni); section->sni=str_dup_detached(arg); return NULL; /* OK */ case CMD_INITIALIZE: { char *tmp_str=sni_init(section); if(tmp_str) return tmp_str; } if(!section->option.client && section->sni) ++endpoints; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = master_service:host_name for an SNI virtual service", "sni"); break; } #endif /* !defined(OPENSSL_NO_TLSEXT) */ /* socket */ switch(cmd) { case CMD_SET_DEFAULTS: section->sock_opts=socket_options_init(); break; case CMD_SET_COPY: section->sock_opts=socket_options_dup(new_service_options.sock_opts); break; case CMD_FREE: socket_options_free(section->sock_opts); break; case CMD_SET_VALUE: if(strcasecmp(opt, "socket")) break; if(socket_option_parse(section->sock_opts, arg)) return "Illegal socket option"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = a|l|r:option=value[:value]", "socket"); s_log(LOG_NOTICE, "%25sset an option on accept/local/remote socket", ""); break; } #if OPENSSL_VERSION_NUMBER>=0x10100000L /* sslVersion */ switch(cmd) { case CMD_SET_DEFAULTS: /* handled in sslVersionMax and sslVersionMin */ break; case CMD_SET_COPY: /* handled in sslVersionMax and sslVersionMin */ break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "sslVersion")) break; section->max_proto_version= section->min_proto_version=str_to_proto_version(arg); if(section->max_proto_version==-1) return "Invalid protocol version"; return NULL; /* OK */ case CMD_INITIALIZE: if(section->max_proto_version && section->min_proto_version && section->max_proto_version<section->min_proto_version) return "Invalid protocol version range"; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = all" "|SSLv3|TLSv1|TLSv1.1|TLSv1.2" #ifdef TLS1_3_VERSION "|TLSv1.3" #endif " TLS version", "sslVersion"); break; } /* sslVersionMax */ switch(cmd) { case CMD_SET_DEFAULTS: section->max_proto_version=0; /* highest supported */ break; case CMD_SET_COPY: section->max_proto_version=new_service_options.max_proto_version; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "sslVersionMax")) break; section->max_proto_version=str_to_proto_version(arg); if(section->max_proto_version==-1) return "Invalid protocol version"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = all" "|SSLv3|TLSv1|TLSv1.1|TLSv1.2" #ifdef TLS1_3_VERSION "|TLSv1.3" #endif " TLS version", "sslVersionMax"); break; } /* sslVersionMin */ switch(cmd) { case CMD_SET_DEFAULTS: section->min_proto_version=TLS1_VERSION; break; case CMD_SET_COPY: section->min_proto_version=new_service_options.min_proto_version; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "sslVersionMin")) break; section->min_proto_version=str_to_proto_version(arg); if(section->min_proto_version==-1) return "Invalid protocol version"; return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = all" "|SSLv3|TLSv1|TLSv1.1|TLSv1.2" #ifdef TLS1_3_VERSION "|TLSv1.3" #endif " TLS version", "sslVersionMin"); break; } #else /* OPENSSL_VERSION_NUMBER<0x10100000L */ /* sslVersion */ switch(cmd) { case CMD_SET_DEFAULTS: tls_methods_set(section, NULL); break; case CMD_SET_COPY: section->client_method=new_service_options.client_method; section->server_method=new_service_options.server_method; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "sslVersion")) break; return tls_methods_set(section, arg); case CMD_INITIALIZE: { char *tmp_str=tls_methods_check(section); if(tmp_str) return tmp_str; } break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = all" "|SSLv2|SSLv3|TLSv1" #if OPENSSL_VERSION_NUMBER>=0x10001000L "|TLSv1.1|TLSv1.2" #endif /* OPENSSL_VERSION_NUMBER>=0x10001000L */ " TLS method", "sslVersion"); break; } #endif /* OPENSSL_VERSION_NUMBER<0x10100000L */ #ifndef USE_FORK /* stack */ switch(cmd) { case CMD_SET_DEFAULTS: section->stack_size=DEFAULT_STACK_SIZE; break; case CMD_SET_COPY: section->stack_size=new_service_options.stack_size; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "stack")) break; { char *tmp_str; section->stack_size=(size_t)strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str) /* not a number */ return "Illegal thread stack size"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %d bytes", "stack", DEFAULT_STACK_SIZE); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = thread stack size (in bytes)", "stack"); break; } #endif #if OPENSSL_VERSION_NUMBER>=0x10000000L /* ticketKeySecret */ switch(cmd) { case CMD_SET_DEFAULTS: section->ticket_key=NULL; break; case CMD_SET_COPY: section->ticket_key=key_dup(new_service_options.ticket_key); break; case CMD_FREE: key_free(section->ticket_key); break; case CMD_SET_VALUE: if(strcasecmp(opt, "ticketKeySecret")) break; section->ticket_key=key_read(arg, "ticketKeySecret"); if(!section->ticket_key) return "Failed to read ticketKeySecret"; return NULL; /* OK */ case CMD_INITIALIZE: if(!section->ticket_key) /* ticketKeySecret not configured */ break; if(section->option.client){ s_log(LOG_NOTICE, "ticketKeySecret is ignored in the client mode"); break; } if(section->ticket_key && !section->ticket_mac) return "\"ticketKeySecret\" and \"ticketMacSecret\" must be set together"; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = secret key for encryption/decryption TLSv1.3 tickets", "ticketKeySecret"); break; } /* ticketMacSecret */ switch(cmd) { case CMD_SET_DEFAULTS: section->ticket_mac=NULL; break; case CMD_SET_COPY: section->ticket_mac=key_dup(new_service_options.ticket_mac); break; case CMD_FREE: key_free(section->ticket_mac); break; case CMD_SET_VALUE: if(strcasecmp(opt, "ticketMacSecret")) break; section->ticket_mac=key_read(arg, "ticketMacSecret"); if(!section->ticket_mac) return "Failed to read ticketMacSecret"; return NULL; /* OK */ case CMD_INITIALIZE: if(!section->ticket_mac) /* ticketMacSecret not configured */ break; if(section->option.client){ s_log(LOG_NOTICE, "ticketMacSecret is ignored in the client mode"); break; } if(section->ticket_mac && !section->ticket_key) return "\"ticketKeySecret\" and \"ticketMacSecret\" must be set together"; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = key for HMAC operations on TLSv1.3 tickets", "ticketMacSecret"); break; } #endif /* OpenSSL 1.0.0 or later */ /* TIMEOUTbusy */ switch(cmd) { case CMD_SET_DEFAULTS: section->timeout_busy=300; /* 5 minutes */ break; case CMD_SET_COPY: section->timeout_busy=new_service_options.timeout_busy; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "TIMEOUTbusy")) break; { char *tmp_str; section->timeout_busy=(int)strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str) /* not a number */ return "Illegal busy timeout"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %d seconds", "TIMEOUTbusy", 300); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = seconds to wait for expected data", "TIMEOUTbusy"); break; } /* TIMEOUTclose */ switch(cmd) { case CMD_SET_DEFAULTS: section->timeout_close=60; /* 1 minute */ break; case CMD_SET_COPY: section->timeout_close=new_service_options.timeout_close; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "TIMEOUTclose")) break; { char *tmp_str; section->timeout_close=(int)strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str) /* not a number */ return "Illegal close timeout"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %d seconds", "TIMEOUTclose", 60); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = seconds to wait for close_notify", "TIMEOUTclose"); break; } /* TIMEOUTconnect */ switch(cmd) { case CMD_SET_DEFAULTS: section->timeout_connect=10; /* 10 seconds */ break; case CMD_SET_COPY: section->timeout_connect=new_service_options.timeout_connect; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "TIMEOUTconnect")) break; { char *tmp_str; section->timeout_connect=(int)strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str) /* not a number */ return "Illegal connect timeout"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %d seconds", "TIMEOUTconnect", 10); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = seconds to connect remote host", "TIMEOUTconnect"); break; } /* TIMEOUTidle */ switch(cmd) { case CMD_SET_DEFAULTS: section->timeout_idle=43200; /* 12 hours */ break; case CMD_SET_COPY: section->timeout_idle=new_service_options.timeout_idle; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "TIMEOUTidle")) break; { char *tmp_str; section->timeout_idle=(int)strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str) /* not a number */ return "Illegal idle timeout"; return NULL; /* OK */ } case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = %d seconds", "TIMEOUTidle", 43200); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = seconds to keep an idle connection", "TIMEOUTidle"); break; } /* transparent */ #ifndef USE_WIN32 switch(cmd) { case CMD_SET_DEFAULTS: section->option.transparent_src=0; section->option.transparent_dst=0; break; case CMD_SET_COPY: section->option.transparent_src=new_service_options.option.transparent_src; section->option.transparent_dst=new_service_options.option.transparent_dst; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "transparent")) break; if(!strcasecmp(arg, "none") || !strcasecmp(arg, "no")) { section->option.transparent_src=0; section->option.transparent_dst=0; } else if(!strcasecmp(arg, "source") || !strcasecmp(arg, "yes")) { section->option.transparent_src=1; section->option.transparent_dst=0; } else if(!strcasecmp(arg, "destination")) { section->option.transparent_src=0; section->option.transparent_dst=1; } else if(!strcasecmp(arg, "both")) { section->option.transparent_src=1; section->option.transparent_dst=1; } else return "Selected transparent proxy mode is not available"; return NULL; /* OK */ case CMD_INITIALIZE: if(section->option.transparent_dst) ++endpoints; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = none|source|destination|both transparent proxy mode", "transparent"); break; } #endif /* verify */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.request_cert=0; break; case CMD_SET_COPY: section->option.request_cert=new_service_options.option.request_cert; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "verify")) break; { char *tmp_str; int tmp_int=(int)strtol(arg, &tmp_str, 10); if(tmp_str==arg || *tmp_str || tmp_int<0 || tmp_int>4) return "Bad verify level"; section->option.request_cert=1; section->option.require_cert=(tmp_int>=2); section->option.verify_chain=(tmp_int>=1 && tmp_int<=3); section->option.verify_peer=(tmp_int>=3); } return NULL; /* OK */ case CMD_INITIALIZE: if((section->option.verify_chain || section->option.verify_peer) && !section->ca_file && !section->ca_dir) return "Either \"CAfile\" or \"CApath\" has to be configured"; break; case CMD_PRINT_DEFAULTS: s_log(LOG_NOTICE, "%-22s = none", "verify"); break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = level of peer certificate verification", "verify"); s_log(LOG_NOTICE, "%25slevel 0 - request and ignore peer cert", ""); s_log(LOG_NOTICE, "%25slevel 1 - only validate peer cert if present", ""); s_log(LOG_NOTICE, "%25slevel 2 - always require a valid peer cert", ""); s_log(LOG_NOTICE, "%25slevel 3 - verify peer with locally installed cert", ""); s_log(LOG_NOTICE, "%25slevel 4 - ignore CA chain and only verify peer cert", ""); break; } /* verifyChain */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.verify_chain=0; break; case CMD_SET_COPY: section->option.verify_chain=new_service_options.option.verify_chain; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "verifyChain")) break; if(!strcasecmp(arg, "yes")) { section->option.request_cert=1; section->option.require_cert=1; section->option.verify_chain=1; } else if(!strcasecmp(arg, "no")) { section->option.verify_chain=0; } else { return "The argument needs to be either 'yes' or 'no'"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no verify certificate chain", "verifyChain"); break; } /* verifyPeer */ switch(cmd) { case CMD_SET_DEFAULTS: section->option.verify_peer=0; break; case CMD_SET_COPY: section->option.verify_peer=new_service_options.option.verify_peer; break; case CMD_FREE: break; case CMD_SET_VALUE: if(strcasecmp(opt, "verifyPeer")) break; if(!strcasecmp(arg, "yes")) { section->option.request_cert=1; section->option.require_cert=1; section->option.verify_peer=1; } else if(!strcasecmp(arg, "no")) { section->option.verify_peer=0; } else { return "The argument needs to be either 'yes' or 'no'"; } return NULL; /* OK */ case CMD_INITIALIZE: break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: s_log(LOG_NOTICE, "%-22s = yes|no verify peer certificate", "verifyPeer"); break; } /* final checks */ switch(cmd) { case CMD_SET_DEFAULTS: break; case CMD_SET_COPY: break; case CMD_FREE: str_free(section->chain); if(section->session) SSL_SESSION_free(section->session); if(section->ctx) SSL_CTX_free(section->ctx); str_free(section->servname); if(section==&service_options) memset(section, 0, sizeof(SERVICE_OPTIONS)); else str_free(section); break; case CMD_SET_VALUE: return option_not_found; case CMD_INITIALIZE: if(section!=&new_service_options) { /* daemon mode checks */ if(endpoints!=2) return "Each service must define two endpoints"; } else { /* inetd mode checks */ if(section->option.accept) return "'accept' option is only allowed in a [section]"; /* no need to check for section->sni in inetd mode, as it requires valid sections to be set */ if(endpoints!=1) return "Inetd mode must define one endpoint"; } #ifdef SSL_OP_NO_TICKET /* disable RFC4507 support introduced in OpenSSL 0.9.8f */ /* OpenSSL 1.1.1 is required to serialize application data * into session tickets */ /* server mode sections need it for the "redirect" option * and connect address session persistence */ if(OpenSSL_version_num()<0x10101000L && !section->option.client && !section->option.connect_before_ssl) section->ssl_options_set|=SSL_OP_NO_TICKET; #endif /* SSL_OP_NO_TICKET */ if(context_init(section)) /* initialize TLS context */ return "Failed to initialize TLS context"; break; case CMD_PRINT_DEFAULTS: break; case CMD_PRINT_HELP: break; } return NULL; /* OK */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'stunnel-5.57'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: NOEXPORT unsigned __stdcall daemon_thread(void *arg) { (void)arg; /* squash the unused parameter warning */ tls_alloc(NULL, NULL, "main"); /* new thread-local storage */ main_init(); SetEvent(main_initialized); /* unlock the GUI thread */ /* get a valid configuration */ while(main_configure(cmdline.config_file, NULL)) { if(cmdline.config_file && *cmdline.config_file=='-') cmdline.config_file=NULL; /* don't retry commandline switches */ unbind_ports(); /* in case initialization failed after bind_ports() */ log_flush(LOG_MODE_ERROR); /* otherwise logs are buffered */ PostMessage(hwnd, WM_INVALID_CONFIG, 0, 0); /* display error */ WaitForSingleObject(config_ready, INFINITE); } PostMessage(hwnd, WM_VALID_CONFIG, 0, 0); /* start the main loop */ daemon_loop(); main_cleanup(); _endthreadex(0); /* SIGNAL_TERMINATE received */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'stunnel-5.57'</s>
<s>[INST] Given the following code containing errors, provide 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 attr_is_equal_ex(xmlAttrPtr node, char *name, char *ns) { if (name == NULL || strcmp((char*)node->name, name) == 0) { if (ns) { xmlNsPtr nsPtr = attr_find_ns(node); if (nsPtr) { return (strcmp((char*)nsPtr->href, ns) == 0); } else { return FALSE; } } return TRUE; } return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix bug #80672 - Null Dereference in SoapClient'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: autoar_extractor_step_extract (AutoarExtractor *self) { /* Step 3: Extract files * We have to re-open the archive to extract files */ struct archive *a; struct archive_entry *entry; int r; g_debug ("autoar_extractor_step_extract: called"); r = libarchive_create_read_object (self->use_raw_format, self, &a); if (r != ARCHIVE_OK) { if (self->error == NULL) { self->error = autoar_common_g_error_new_a (a, self->source_basename); } archive_read_free (a); return; } while ((r = archive_read_next_header (a, &entry)) == ARCHIVE_OK) { const char *pathname; const char *hardlink; g_autoptr (GFile) extracted_filename = NULL; g_autoptr (GFile) hardlink_filename = NULL; AutoarConflictAction action; gboolean file_conflict; if (g_cancellable_is_cancelled (self->cancellable)) { archive_read_free (a); return; } pathname = archive_entry_pathname (entry); hardlink = archive_entry_hardlink (entry); extracted_filename = autoar_extractor_do_sanitize_pathname (self, pathname); if (hardlink != NULL) { hardlink_filename = autoar_extractor_do_sanitize_pathname (self, hardlink); } /* Attempt to solve any name conflict before doing any operations */ file_conflict = autoar_extractor_check_file_conflict (extracted_filename, archive_entry_filetype (entry)); while (file_conflict) { GFile *new_extracted_filename = NULL; action = autoar_extractor_signal_conflict (self, extracted_filename, &new_extracted_filename); switch (action) { case AUTOAR_CONFLICT_OVERWRITE: break; case AUTOAR_CONFLICT_CHANGE_DESTINATION: g_assert_nonnull (new_extracted_filename); g_clear_object (&extracted_filename); extracted_filename = new_extracted_filename; break; case AUTOAR_CONFLICT_SKIP: archive_read_data_skip (a); break; default: g_assert_not_reached (); break; } if (action != AUTOAR_CONFLICT_CHANGE_DESTINATION) { break; } file_conflict = autoar_extractor_check_file_conflict (extracted_filename, archive_entry_filetype (entry)); } if (file_conflict && action == AUTOAR_CONFLICT_SKIP) { continue; } autoar_extractor_do_write_entry (self, a, entry, extracted_filename, hardlink_filename); if (self->error != NULL) { archive_read_free (a); return; } self->completed_files++; autoar_extractor_signal_progress (self); } if (r != ARCHIVE_EOF) { if (self->error == NULL) { self->error = autoar_common_g_error_new_a (a, self->source_basename); } archive_read_free (a); return; } archive_read_free (a); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'AutoarExtractor: Do not extract files outside the destination dir Currently, a malicious archive can cause that the files are extracted outside of the destination dir. This can happen if the archive contains a file whose parent is a symbolic link, which points outside of the destination dir. This is potentially a security threat similar to CVE-2020-11736. Let's skip such problematic files when extracting. Fixes: https://gitlab.gnome.org/GNOME/gnome-autoar/-/issues/7'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lzw_decoder_feed (LZWDecoder *self, guint8 *input, gsize input_length, guint8 *output, gsize output_length) { gsize i, n_written = 0; g_return_val_if_fail (LZW_IS_DECODER (self), 0); /* Ignore data after "end of information" codeword */ if (self->last_code == self->eoi_code) return 0; /* Processes each octet of input */ for (i = 0; i < input_length; i++) { guint8 d = input[i]; int n_available; /* Process the bits of the octet into codewords */ for (n_available = 8; n_available > 0; ) { int n_bits, new_bits; /* Extract up the the required number of bits from the octet */ n_bits = MIN (self->code_size - self->code_bits, n_available); new_bits = d & ((1 << n_bits) - 1); d = d >> n_bits; n_available -= n_bits; /* Add the new bits to the code until we have a full codeword */ self->code = new_bits << self->code_bits | self->code; self->code_bits += n_bits; if (self->code_bits < self->code_size) continue; /* Stop on "end of information" codeword */ if (self->code == self->eoi_code) { self->last_code = self->code; return n_written; } /* Reset the code table on "clear" */ if (self->code == self->clear_code) { self->code_table_size = self->eoi_code + 1; self->code_size = self->min_code_size; } else { /* Add a new code word if space. * The first code after a clear is skipped */ if (self->last_code != self->clear_code && self->code_table_size < MAX_CODES) { if (self->code < self->code_table_size) add_code (self, self->code); else if (self->code == self->code_table_size) add_code (self, self->last_code); else { /* Invalid code received - just stop here */ self->last_code = self->eoi_code; return output_length; } /* When table is full increase code size */ if (self->code_table_size == (1 << self->code_size) && self->code_size < LZW_CODE_MAX) self->code_size++; } /* Convert codeword into indexes */ n_written += write_indexes (self, output + n_written, output_length - n_written); } self->last_code = self->code; self->code = 0; self->code_bits = 0; /* Out of space */ if (n_written >= output_length) return output_length; } } return n_written; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'gif: Fix LZW decoder accepting invalid LZW code. The code value after a reset wasn't being validated, which means we would accept invalid codes. This could cause an infinite loop in the decoder. Fixes CVE-2020-29385 Fixes https://gitlab.gnome.org/GNOME/gdk-pixbuf/-/issues/164'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sdhci_write(void *opaque, hwaddr offset, uint64_t val, unsigned size) { SDHCIState *s = (SDHCIState *)opaque; unsigned shift = 8 * (offset & 0x3); uint32_t mask = ~(((1ULL << (size * 8)) - 1) << shift); uint32_t value = val; value <<= shift; if (timer_pending(s->transfer_timer)) { sdhci_resume_pending_transfer(s); } switch (offset & ~0x3) { case SDHC_SYSAD: if (!TRANSFERRING_DATA(s->prnsts)) { s->sdmasysad = (s->sdmasysad & mask) | value; MASKED_WRITE(s->sdmasysad, mask, value); /* Writing to last byte of sdmasysad might trigger transfer */ if (!(mask & 0xFF000000) && s->blkcnt && s->blksize && SDHC_DMA_TYPE(s->hostctl1) == SDHC_CTRL_SDMA) { if (s->trnmod & SDHC_TRNS_MULTI) { sdhci_sdma_transfer_multi_blocks(s); } else { sdhci_sdma_transfer_single_block(s); } } } break; case SDHC_BLKSIZE: if (!TRANSFERRING_DATA(s->prnsts)) { MASKED_WRITE(s->blksize, mask, extract32(value, 0, 12)); MASKED_WRITE(s->blkcnt, mask >> 16, value >> 16); /* Limit block size to the maximum buffer size */ if (extract32(s->blksize, 0, 12) > s->buf_maxsz) { qemu_log_mask(LOG_GUEST_ERROR, "%s: Size 0x%x is larger than " "the maximum buffer 0x%x\n", __func__, s->blksize, s->buf_maxsz); s->blksize = deposit32(s->blksize, 0, 12, s->buf_maxsz); } } break; case SDHC_ARGUMENT: MASKED_WRITE(s->argument, mask, value); break; case SDHC_TRNMOD: /* DMA can be enabled only if it is supported as indicated by * capabilities register */ if (!(s->capareg & R_SDHC_CAPAB_SDMA_MASK)) { value &= ~SDHC_TRNS_DMA; } MASKED_WRITE(s->trnmod, mask, value & SDHC_TRNMOD_MASK); MASKED_WRITE(s->cmdreg, mask >> 16, value >> 16); /* Writing to the upper byte of CMDREG triggers SD command generation */ if ((mask & 0xFF000000) || !sdhci_can_issue_command(s)) { break; } sdhci_send_command(s); break; case SDHC_BDATA: if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) { sdhci_write_dataport(s, value >> shift, size); } break; case SDHC_HOSTCTL: if (!(mask & 0xFF0000)) { sdhci_blkgap_write(s, value >> 16); } MASKED_WRITE(s->hostctl1, mask, value); MASKED_WRITE(s->pwrcon, mask >> 8, value >> 8); MASKED_WRITE(s->wakcon, mask >> 24, value >> 24); if (!(s->prnsts & SDHC_CARD_PRESENT) || ((s->pwrcon >> 1) & 0x7) < 5 || !(s->capareg & (1 << (31 - ((s->pwrcon >> 1) & 0x7))))) { s->pwrcon &= ~SDHC_POWER_ON; } break; case SDHC_CLKCON: if (!(mask & 0xFF000000)) { sdhci_reset_write(s, value >> 24); } MASKED_WRITE(s->clkcon, mask, value); MASKED_WRITE(s->timeoutcon, mask >> 16, value >> 16); if (s->clkcon & SDHC_CLOCK_INT_EN) { s->clkcon |= SDHC_CLOCK_INT_STABLE; } else { s->clkcon &= ~SDHC_CLOCK_INT_STABLE; } break; case SDHC_NORINTSTS: if (s->norintstsen & SDHC_NISEN_CARDINT) { value &= ~SDHC_NIS_CARDINT; } s->norintsts &= mask | ~value; s->errintsts &= (mask >> 16) | ~(value >> 16); if (s->errintsts) { s->norintsts |= SDHC_NIS_ERR; } else { s->norintsts &= ~SDHC_NIS_ERR; } sdhci_update_irq(s); break; case SDHC_NORINTSTSEN: MASKED_WRITE(s->norintstsen, mask, value); MASKED_WRITE(s->errintstsen, mask >> 16, value >> 16); s->norintsts &= s->norintstsen; s->errintsts &= s->errintstsen; if (s->errintsts) { s->norintsts |= SDHC_NIS_ERR; } else { s->norintsts &= ~SDHC_NIS_ERR; } /* Quirk for Raspberry Pi: pending card insert interrupt * appears when first enabled after power on */ if ((s->norintstsen & SDHC_NISEN_INSERT) && s->pending_insert_state) { assert(s->pending_insert_quirk); s->norintsts |= SDHC_NIS_INSERT; s->pending_insert_state = false; } sdhci_update_irq(s); break; case SDHC_NORINTSIGEN: MASKED_WRITE(s->norintsigen, mask, value); MASKED_WRITE(s->errintsigen, mask >> 16, value >> 16); sdhci_update_irq(s); break; case SDHC_ADMAERR: MASKED_WRITE(s->admaerr, mask, value); break; case SDHC_ADMASYSADDR: s->admasysaddr = (s->admasysaddr & (0xFFFFFFFF00000000ULL | (uint64_t)mask)) | (uint64_t)value; break; case SDHC_ADMASYSADDR + 4: s->admasysaddr = (s->admasysaddr & (0x00000000FFFFFFFFULL | ((uint64_t)mask << 32))) | ((uint64_t)value << 32); break; case SDHC_FEAER: s->acmd12errsts |= value; s->errintsts |= (value >> 16) & s->errintstsen; if (s->acmd12errsts) { s->errintsts |= SDHC_EIS_CMD12ERR; } if (s->errintsts) { s->norintsts |= SDHC_NIS_ERR; } sdhci_update_irq(s); break; case SDHC_ACMD12ERRSTS: MASKED_WRITE(s->acmd12errsts, mask, value & UINT16_MAX); if (s->uhs_mode >= UHS_I) { MASKED_WRITE(s->hostctl2, mask >> 16, value >> 16); if (FIELD_EX32(s->hostctl2, SDHC_HOSTCTL2, V18_ENA)) { sdbus_set_voltage(&s->sdbus, SD_VOLTAGE_1_8V); } else { sdbus_set_voltage(&s->sdbus, SD_VOLTAGE_3_3V); } } break; case SDHC_CAPAB: case SDHC_CAPAB + 4: case SDHC_MAXCURR: case SDHC_MAXCURR + 4: qemu_log_mask(LOG_GUEST_ERROR, "SDHC wr_%ub @0x%02" HWADDR_PRIx " <- 0x%08x read-only\n", size, offset, value >> shift); break; default: qemu_log_mask(LOG_UNIMP, "SDHC wr_%ub @0x%02" HWADDR_PRIx " <- 0x%08x " "not implemented\n", size, offset, value >> shift); break; } trace_sdhci_access("wr", size << 3, offset, "<-", value >> shift, value >> shift); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'hw/sd: sdhci: Reset the data pointer of s->fifo_buffer[] when a different block size is programmed If the block size is programmed to a different value from the previous one, reset the data pointer of s->fifo_buffer[] so that s->fifo_buffer[] can be filled in using the new block size in the next transfer. With this fix, the following reproducer: outl 0xcf8 0x80001010 outl 0xcfc 0xe0000000 outl 0xcf8 0x80001001 outl 0xcfc 0x06000000 write 0xe000002c 0x1 0x05 write 0xe0000005 0x1 0x02 write 0xe0000007 0x1 0x01 write 0xe0000028 0x1 0x10 write 0x0 0x1 0x23 write 0x2 0x1 0x08 write 0xe000000c 0x1 0x01 write 0xe000000e 0x1 0x20 write 0xe000000f 0x1 0x00 write 0xe000000c 0x1 0x32 write 0xe0000004 0x2 0x0200 write 0xe0000028 0x1 0x00 write 0xe0000003 0x1 0x40 cannot be reproduced with the following QEMU command line: $ qemu-system-x86_64 -nographic -machine accel=qtest -m 512M \ -nodefaults -device sdhci-pci,sd-spec-version=3 \ -drive if=sd,index=0,file=null-co://,format=raw,id=mydrive \ -device sd-card,drive=mydrive -qtest stdio Cc: qemu-stable@nongnu.org Fixes: CVE-2020-17380 Fixes: CVE-2020-25085 Fixes: CVE-2021-3409 Fixes: d7dfca0807a0 ("hw/sdhci: introduce standard SD host controller") Reported-by: Alexander Bulekov <alxndr@bu.edu> Reported-by: Cornelius Aschermann (Ruhr-Universität Bochum) Reported-by: Sergej Schumilo (Ruhr-Universität Bochum) Reported-by: Simon Wörner (Ruhr-Universität Bochum) Buglink: https://bugs.launchpad.net/qemu/+bug/1892960 Buglink: https://bugs.launchpad.net/qemu/+bug/1909418 Buglink: https://bugzilla.redhat.com/show_bug.cgi?id=1928146 Tested-by: Alexander Bulekov <alxndr@bu.edu> Signed-off-by: Bin Meng <bmeng.cn@gmail.com> Message-Id: <20210303122639.20004-6-bmeng.cn@gmail.com> Signed-off-by: Philippe Mathieu-Daudé <f4bug@amsat.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: show_ep_handle(struct device *dev, struct device_attribute *attr, char *buf) { struct iscsi_endpoint *ep = iscsi_dev_to_endpoint(dev); return sprintf(buf, "%llu\n", (unsigned long long) ep->id); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'scsi: iscsi: Ensure sysfs attributes are limited to PAGE_SIZE As the iSCSI parameters are exported back through sysfs, it should be enforcing that they never are more than PAGE_SIZE (which should be more than enough) before accepting updates through netlink. Change all iSCSI sysfs attributes to use sysfs_emit(). Cc: stable@vger.kernel.org Reported-by: Adam Nichols <adam@grimm-co.com> Reviewed-by: Lee Duncan <lduncan@suse.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Reviewed-by: Mike Christie <michael.christie@oracle.com> Signed-off-by: Chris Leech <cleech@redhat.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int iscsi_if_recv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, uint32_t *group) { int err = 0; u32 portid; struct iscsi_uevent *ev = nlmsg_data(nlh); struct iscsi_transport *transport = NULL; struct iscsi_internal *priv; struct iscsi_cls_session *session; struct iscsi_cls_conn *conn; struct iscsi_endpoint *ep = NULL; if (!netlink_capable(skb, CAP_SYS_ADMIN)) return -EPERM; if (nlh->nlmsg_type == ISCSI_UEVENT_PATH_UPDATE) *group = ISCSI_NL_GRP_UIP; else *group = ISCSI_NL_GRP_ISCSID; priv = iscsi_if_transport_lookup(iscsi_ptr(ev->transport_handle)); if (!priv) return -EINVAL; transport = priv->iscsi_transport; if (!try_module_get(transport->owner)) return -EINVAL; portid = NETLINK_CB(skb).portid; switch (nlh->nlmsg_type) { case ISCSI_UEVENT_CREATE_SESSION: err = iscsi_if_create_session(priv, ep, ev, portid, ev->u.c_session.initial_cmdsn, ev->u.c_session.cmds_max, ev->u.c_session.queue_depth); break; case ISCSI_UEVENT_CREATE_BOUND_SESSION: ep = iscsi_lookup_endpoint(ev->u.c_bound_session.ep_handle); if (!ep) { err = -EINVAL; break; } err = iscsi_if_create_session(priv, ep, ev, portid, ev->u.c_bound_session.initial_cmdsn, ev->u.c_bound_session.cmds_max, ev->u.c_bound_session.queue_depth); break; case ISCSI_UEVENT_DESTROY_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (!session) err = -EINVAL; else if (iscsi_session_has_conns(ev->u.d_session.sid)) err = -EBUSY; else transport->destroy_session(session); break; case ISCSI_UEVENT_DESTROY_SESSION_ASYNC: session = iscsi_session_lookup(ev->u.d_session.sid); if (!session) err = -EINVAL; else if (iscsi_session_has_conns(ev->u.d_session.sid)) err = -EBUSY; else { unsigned long flags; /* Prevent this session from being found again */ spin_lock_irqsave(&sesslock, flags); list_del_init(&session->sess_list); spin_unlock_irqrestore(&sesslock, flags); queue_work(iscsi_destroy_workq, &session->destroy_work); } break; case ISCSI_UEVENT_UNBIND_SESSION: session = iscsi_session_lookup(ev->u.d_session.sid); if (session) scsi_queue_work(iscsi_session_to_shost(session), &session->unbind_work); else err = -EINVAL; break; case ISCSI_UEVENT_CREATE_CONN: err = iscsi_if_create_conn(transport, ev); break; case ISCSI_UEVENT_DESTROY_CONN: err = iscsi_if_destroy_conn(transport, ev); break; case ISCSI_UEVENT_BIND_CONN: session = iscsi_session_lookup(ev->u.b_conn.sid); conn = iscsi_conn_lookup(ev->u.b_conn.sid, ev->u.b_conn.cid); if (conn && conn->ep) iscsi_if_ep_disconnect(transport, conn->ep->id); if (!session || !conn) { err = -EINVAL; break; } mutex_lock(&conn_mutex); ev->r.retcode = transport->bind_conn(session, conn, ev->u.b_conn.transport_eph, ev->u.b_conn.is_leading); mutex_unlock(&conn_mutex); if (ev->r.retcode || !transport->ep_connect) break; ep = iscsi_lookup_endpoint(ev->u.b_conn.transport_eph); if (ep) { ep->conn = conn; mutex_lock(&conn->ep_mutex); conn->ep = ep; mutex_unlock(&conn->ep_mutex); } else iscsi_cls_conn_printk(KERN_ERR, conn, "Could not set ep conn " "binding\n"); break; case ISCSI_UEVENT_SET_PARAM: err = iscsi_set_param(transport, ev); break; case ISCSI_UEVENT_START_CONN: conn = iscsi_conn_lookup(ev->u.start_conn.sid, ev->u.start_conn.cid); if (conn) { mutex_lock(&conn_mutex); ev->r.retcode = transport->start_conn(conn); if (!ev->r.retcode) conn->state = ISCSI_CONN_UP; mutex_unlock(&conn_mutex); } else err = -EINVAL; break; case ISCSI_UEVENT_STOP_CONN: conn = iscsi_conn_lookup(ev->u.stop_conn.sid, ev->u.stop_conn.cid); if (conn) iscsi_if_stop_conn(conn, ev->u.stop_conn.flag); else err = -EINVAL; break; case ISCSI_UEVENT_SEND_PDU: conn = iscsi_conn_lookup(ev->u.send_pdu.sid, ev->u.send_pdu.cid); if (conn) { mutex_lock(&conn_mutex); ev->r.retcode = transport->send_pdu(conn, (struct iscsi_hdr*)((char*)ev + sizeof(*ev)), (char*)ev + sizeof(*ev) + ev->u.send_pdu.hdr_size, ev->u.send_pdu.data_size); mutex_unlock(&conn_mutex); } else err = -EINVAL; break; case ISCSI_UEVENT_GET_STATS: err = iscsi_if_get_stats(transport, nlh); break; case ISCSI_UEVENT_TRANSPORT_EP_CONNECT: case ISCSI_UEVENT_TRANSPORT_EP_POLL: case ISCSI_UEVENT_TRANSPORT_EP_DISCONNECT: case ISCSI_UEVENT_TRANSPORT_EP_CONNECT_THROUGH_HOST: err = iscsi_if_transport_ep(transport, ev, nlh->nlmsg_type); break; case ISCSI_UEVENT_TGT_DSCVR: err = iscsi_tgt_dscvr(transport, ev); break; case ISCSI_UEVENT_SET_HOST_PARAM: err = iscsi_set_host_param(transport, ev); break; case ISCSI_UEVENT_PATH_UPDATE: err = iscsi_set_path(transport, ev); break; case ISCSI_UEVENT_SET_IFACE_PARAMS: err = iscsi_set_iface_params(transport, ev, nlmsg_attrlen(nlh, sizeof(*ev))); break; case ISCSI_UEVENT_PING: err = iscsi_send_ping(transport, ev); break; case ISCSI_UEVENT_GET_CHAP: err = iscsi_get_chap(transport, nlh); break; case ISCSI_UEVENT_DELETE_CHAP: err = iscsi_delete_chap(transport, ev); break; case ISCSI_UEVENT_SET_FLASHNODE_PARAMS: err = iscsi_set_flashnode_param(transport, ev, nlmsg_attrlen(nlh, sizeof(*ev))); break; case ISCSI_UEVENT_NEW_FLASHNODE: err = iscsi_new_flashnode(transport, ev, nlmsg_attrlen(nlh, sizeof(*ev))); break; case ISCSI_UEVENT_DEL_FLASHNODE: err = iscsi_del_flashnode(transport, ev); break; case ISCSI_UEVENT_LOGIN_FLASHNODE: err = iscsi_login_flashnode(transport, ev); break; case ISCSI_UEVENT_LOGOUT_FLASHNODE: err = iscsi_logout_flashnode(transport, ev); break; case ISCSI_UEVENT_LOGOUT_FLASHNODE_SID: err = iscsi_logout_flashnode_sid(transport, ev); break; case ISCSI_UEVENT_SET_CHAP: err = iscsi_set_chap(transport, ev, nlmsg_attrlen(nlh, sizeof(*ev))); break; case ISCSI_UEVENT_GET_HOST_STATS: err = iscsi_get_host_stats(transport, nlh); break; default: err = -ENOSYS; break; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'scsi: iscsi: Verify lengths on passthrough PDUs Open-iSCSI sends passthrough PDUs over netlink, but the kernel should be verifying that the provided PDU header and data lengths fall within the netlink message to prevent accessing beyond that in memory. Cc: stable@vger.kernel.org Reported-by: Adam Nichols <adam@grimm-co.com> Reviewed-by: Lee Duncan <lduncan@suse.com> Reviewed-by: Mike Christie <michael.christie@oracle.com> Signed-off-by: Chris Leech <cleech@redhat.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cvt_whole_image( TIFF *in, TIFF *out ) { uint32* raster; /* retrieve RGBA image */ uint32 width, height; /* image width & height */ uint32 row; size_t pixel_count; TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &height); pixel_count = width * height; /* XXX: Check the integer overflow. */ if (!width || !height || pixel_count / width != height) { TIFFError(TIFFFileName(in), "Malformed input file; can't allocate buffer for raster of %lux%lu size", (unsigned long)width, (unsigned long)height); return 0; } rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); raster = (uint32*)_TIFFCheckMalloc(in, pixel_count, sizeof(uint32), "raster buffer"); if (raster == 0) { TIFFError(TIFFFileName(in), "Failed to allocate buffer (%lu elements of %lu each)", (unsigned long)pixel_count, (unsigned long)sizeof(uint32)); return (0); } /* Read the image in one chunk into an RGBA array */ if (!TIFFReadRGBAImageOriented(in, width, height, raster, ORIENTATION_TOPLEFT, 0)) { _TIFFfree(raster); return (0); } /* * XXX: raster array has 4-byte unsigned integer type, that is why * we should rearrange it here. */ #if HOST_BIGENDIAN TIFFSwabArrayOfLong(raster, width * height); #endif /* * Do we want to strip away alpha components? */ if (no_alpha) { size_t count = pixel_count; unsigned char *src, *dst; src = dst = (unsigned char *) raster; while (count > 0) { *(dst++) = *(src++); *(dst++) = *(src++); *(dst++) = *(src++); src++; count--; } } /* * Write out the result in strips */ for (row = 0; row < height; row += rowsperstrip) { unsigned char * raster_strip; int rows_to_write; int bytes_per_pixel; if (no_alpha) { raster_strip = ((unsigned char *) raster) + 3 * row * width; bytes_per_pixel = 3; } else { raster_strip = (unsigned char *) (raster + row * width); bytes_per_pixel = 4; } if( row + rowsperstrip > height ) rows_to_write = height - row; else rows_to_write = rowsperstrip; if( TIFFWriteEncodedStrip( out, row / rowsperstrip, raster_strip, bytes_per_pixel * rows_to_write * width ) == -1 ) { _TIFFfree( raster ); return 0; } } _TIFFfree( raster ); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'enforce (configurable) memory limit in tiff2rgba fixes #207 fixes #209'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int do_format(int drive, struct format_descr *tmp_format_req) { int ret; if (lock_fdc(drive, true)) return -EINTR; set_floppy(drive); if (!_floppy || _floppy->track > DP->tracks || tmp_format_req->track >= _floppy->track || tmp_format_req->head >= _floppy->head || (_floppy->sect << 2) % (1 << FD_SIZECODE(_floppy)) || !_floppy->fmt_gap) { process_fd_request(); return -EINVAL; } format_req = *tmp_format_req; format_errors = 0; cont = &format_cont; errors = &format_errors; ret = wait_til_done(redo_format, true); if (ret == -EINTR) return -EINTR; process_fd_request(); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'floppy: fix lock_fdc() signal handling floppy_revalidate() doesn't perform any error handling on lock_fdc() result. lock_fdc() might actually be interrupted by a signal (it waits for fdc becoming non-busy interruptibly). In such case, floppy_revalidate() proceeds as if it had claimed the lock, but it fact it doesn't. In case of multiple threads trying to open("/dev/fdX"), this leads to serious corruptions all over the place, because all of a sudden there is no critical section protection (that'd otherwise be guaranteed by locked fd) whatsoever. While at this, fix the fact that the 'interruptible' parameter to lock_fdc() doesn't make any sense whatsoever, because we always wait interruptibly anyway. Most of the lock_fdc() callsites do properly handle error (and propagate EINTR), but floppy_revalidate() and floppy_check_events() don't. Fix this. Spotted by 'syzkaller' tool. Reported-by: Dmitry Vyukov <dvyukov@google.com> Tested-by: Dmitry Vyukov <dvyukov@google.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: static void msf2_dma_tx(MSF2EmacState *s) { NetClientState *nc = qemu_get_queue(s->nic); hwaddr desc = s->regs[R_DMA_TX_DESC]; uint8_t buf[MAX_PKT_SIZE]; EmacDesc d; int size; uint8_t pktcnt; uint32_t status; if (!(s->regs[R_CFG1] & R_CFG1_TX_EN_MASK)) { return; } while (1) { emac_load_desc(s, &d, desc); if (d.pktsize & EMPTY_MASK) { break; } size = d.pktsize & PKT_SIZE; address_space_read(&s->dma_as, d.pktaddr, MEMTXATTRS_UNSPECIFIED, buf, size); /* * This is very basic way to send packets. Ideally there should be * a FIFO and packets should be sent out from FIFO only when * R_CFG1 bit 0 is set. */ if (s->regs[R_CFG1] & R_CFG1_LB_EN_MASK) { nc->info->receive(nc, buf, size); } else { qemu_send_packet(nc, buf, size); } d.pktsize |= EMPTY_MASK; emac_store_desc(s, &d, desc); /* update sent packets count */ status = s->regs[R_DMA_TX_STATUS]; pktcnt = FIELD_EX32(status, DMA_TX_STATUS, PKTCNT); pktcnt++; s->regs[R_DMA_TX_STATUS] = FIELD_DP32(status, DMA_TX_STATUS, PKTCNT, pktcnt); s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_PKT_SENT_MASK; desc = d.next; } s->regs[R_DMA_TX_STATUS] |= R_DMA_TX_STATUS_UNDERRUN_MASK; s->regs[R_DMA_TX_CTL] &= ~R_DMA_TX_CTL_EN_MASK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'msf2-mac: switch to use qemu_receive_packet() for loopback This patch switches to use qemu_receive_packet() which can detect reentrancy and return early. This is intended to address CVE-2021-3416. Cc: Prasad J Pandit <ppandit@redhat.com> Cc: qemu-stable@nongnu.org Reviewed-by: Philippe Mathieu-Daudé <philmd@redhat.com> Signed-off-by: Jason Wang <jasowang@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: Status explain(OperationContext* opCtx, const OpMsgRequest& request, ExplainOptions::Verbosity verbosity, BSONObjBuilder* out) const override { std::string dbname = request.getDatabase().toString(); const BSONObj& cmdObj = request.body; // Acquire locks and resolve possible UUID. The RAII object is optional, because in the case // of a view, the locks need to be released. boost::optional<AutoGetCollectionForReadCommand> ctx; ctx.emplace(opCtx, CommandHelpers::parseNsOrUUID(dbname, cmdObj), AutoGetCollection::ViewMode::kViewsPermitted); const auto nss = ctx->getNss(); const ExtensionsCallbackReal extensionsCallback(opCtx, &nss); auto parsedDistinct = uassertStatusOK(ParsedDistinct::parse(opCtx, nss, cmdObj, extensionsCallback, true)); if (ctx->getView()) { // Relinquish locks. The aggregation command will re-acquire them. ctx.reset(); auto viewAggregation = parsedDistinct.asAggregationCommand(); if (!viewAggregation.isOK()) { return viewAggregation.getStatus(); } auto viewAggRequest = AggregationRequest::parseFromBSON(nss, viewAggregation.getValue(), verbosity); if (!viewAggRequest.isOK()) { return viewAggRequest.getStatus(); } return runAggregate( opCtx, nss, viewAggRequest.getValue(), viewAggregation.getValue(), *out); } Collection* const collection = ctx->getCollection(); auto executor = uassertStatusOK(getExecutorDistinct(opCtx, collection, nss.ns(), &parsedDistinct)); Explain::explainStages(executor.get(), collection, verbosity, out); return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-38275 ban explain with UUID'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PJ_DEF(pj_status_t) pjsip_tpmgr_acquire_transport2(pjsip_tpmgr *mgr, pjsip_transport_type_e type, const pj_sockaddr_t *remote, int addr_len, const pjsip_tpselector *sel, pjsip_tx_data *tdata, pjsip_transport **tp) { pjsip_tpfactory *factory; pj_status_t status; TRACE_((THIS_FILE,"Acquiring transport type=%s, sel=%s remote=%s:%d", pjsip_transport_get_type_name(type), print_tpsel_info(sel), addr_string(remote), pj_sockaddr_get_port(remote))); pj_lock_acquire(mgr->lock); /* If transport is specified, then just use it if it is suitable * for the destination. */ if (sel && sel->type == PJSIP_TPSELECTOR_TRANSPORT && sel->u.transport) { pjsip_transport *seltp = sel->u.transport; /* See if the transport is (not) suitable */ if (seltp->key.type != type) { pj_lock_release(mgr->lock); TRACE_((THIS_FILE, "Transport type in tpsel not matched")); return PJSIP_ETPNOTSUITABLE; } /* Make sure the transport is not being destroyed */ if (seltp->is_destroying) { pj_lock_release(mgr->lock); TRACE_((THIS_FILE,"Transport to be acquired is being destroyed")); return PJ_ENOTFOUND; } /* We could also verify that the destination address is reachable * from this transport (i.e. both are equal), but if application * has requested a specific transport to be used, assume that * it knows what to do. * * In other words, I don't think destination verification is a good * idea for now. */ /* Transport looks to be suitable to use, so just use it. */ pjsip_transport_add_ref(seltp); pj_lock_release(mgr->lock); *tp = seltp; TRACE_((THIS_FILE, "Transport %s acquired", seltp->obj_name)); return PJ_SUCCESS; } else { /* * This is the "normal" flow, where application doesn't specify * specific transport to be used to send message to. * In this case, lookup the transport from the hash table. */ pjsip_transport_key key; int key_len; pjsip_transport *tp_ref = NULL; transport *tp_entry = NULL; /* If listener is specified, verify that the listener type matches * the destination type. */ if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener) { if (sel->u.listener->type != type) { pj_lock_release(mgr->lock); TRACE_((THIS_FILE, "Listener type in tpsel not matched")); return PJSIP_ETPNOTSUITABLE; } } if (!sel || sel->disable_connection_reuse == PJ_FALSE) { pj_bzero(&key, sizeof(key)); key_len = sizeof(key.type) + addr_len; /* First try to get exact destination. */ key.type = type; pj_memcpy(&key.rem_addr, remote, addr_len); tp_entry = (transport *)pj_hash_get(mgr->table, &key, key_len, NULL); if (tp_entry) { transport *tp_iter = tp_entry; do { /* Don't use transport being shutdown/destroyed */ if (!tp_iter->tp->is_shutdown && !tp_iter->tp->is_destroying) { if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener) { /* Match listener if selector is set */ if (tp_iter->tp->factory == sel->u.listener) { tp_ref = tp_iter->tp; break; } } else { tp_ref = tp_iter->tp; break; } } tp_iter = tp_iter->next; } while (tp_iter != tp_entry); } } if (tp_ref == NULL && (!sel || sel->disable_connection_reuse == PJ_FALSE)) { unsigned flag = pjsip_transport_get_flag_from_type(type); const pj_sockaddr *remote_addr = (const pj_sockaddr*)remote; /* Ignore address for loop transports. */ if (type == PJSIP_TRANSPORT_LOOP || type == PJSIP_TRANSPORT_LOOP_DGRAM) { pj_sockaddr *addr = &key.rem_addr; pj_bzero(addr, addr_len); key_len = sizeof(key.type) + addr_len; tp_entry = (transport *) pj_hash_get(mgr->table, &key, key_len, NULL); if (tp_entry) { tp_ref = tp_entry->tp; } } /* For datagram transports, try lookup with zero address. */ else if (flag & PJSIP_TRANSPORT_DATAGRAM) { pj_sockaddr *addr = &key.rem_addr; pj_bzero(addr, addr_len); addr->addr.sa_family = remote_addr->addr.sa_family; key_len = sizeof(key.type) + addr_len; tp_entry = (transport *) pj_hash_get(mgr->table, &key, key_len, NULL); if (tp_entry) { tp_ref = tp_entry->tp; } } } /* If transport is found and listener is specified, verify listener */ else if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener && tp_ref->factory != sel->u.listener) { tp_ref = NULL; /* This will cause a new transport to be created which will be a * 'duplicate' of the existing transport (same type & remote addr, * but different factory). */ TRACE_((THIS_FILE, "Transport found but from different listener")); } if (tp_ref!=NULL && !tp_ref->is_shutdown && !tp_ref->is_destroying) { /* * Transport found! */ pjsip_transport_add_ref(tp_ref); pj_lock_release(mgr->lock); *tp = tp_ref; TRACE_((THIS_FILE, "Transport %s acquired", tp_ref->obj_name)); return PJ_SUCCESS; } /* * Either transport not found, or we don't want to use the existing * transport (such as in the case of different factory or * if connection reuse is disabled). So we need to create one, * find factory that can create such transport. * * If there's an existing transport, its place in the hash table * will be replaced by this new one. And eventually the existing * transport will still be freed (by application or #1774). */ if (sel && sel->type == PJSIP_TPSELECTOR_LISTENER && sel->u.listener) { /* Application has requested that a specific listener is to * be used. */ /* Verify that the listener type matches the destination type */ /* Already checked above. */ /* if (sel->u.listener->type != type) { pj_lock_release(mgr->lock); return PJSIP_ETPNOTSUITABLE; } */ /* We'll use this listener to create transport */ factory = sel->u.listener; /* Verify if listener is still valid */ if (!pjsip_tpmgr_is_tpfactory_valid(mgr, factory)) { pj_lock_release(mgr->lock); PJ_LOG(3,(THIS_FILE, "Specified factory for creating " "transport is not found")); return PJ_ENOTFOUND; } } else { /* Find factory with type matches the destination type */ factory = mgr->factory_list.next; while (factory != &mgr->factory_list) { if (factory->type == type) break; factory = factory->next; } if (factory == &mgr->factory_list) { /* No factory can create the transport! */ pj_lock_release(mgr->lock); TRACE_((THIS_FILE, "No suitable factory was found either")); return PJSIP_EUNSUPTRANSPORT; } } } TRACE_((THIS_FILE, "Creating new transport from factory")); /* Request factory to create transport. */ if (factory->create_transport2) { status = factory->create_transport2(factory, mgr, mgr->endpt, (const pj_sockaddr*) remote, addr_len, tdata, tp); } else { status = factory->create_transport(factory, mgr, mgr->endpt, (const pj_sockaddr*) remote, addr_len, tp); } if (status == PJ_SUCCESS) { PJ_ASSERT_ON_FAIL(tp!=NULL, {pj_lock_release(mgr->lock); return PJ_EBUG;}); pjsip_transport_add_ref(*tp); (*tp)->factory = factory; } pj_lock_release(mgr->lock); return status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-297', 'CWE-295'], 'message': 'Merge pull request from GHSA-8hcp-hm38-mfph * Check hostname during TLS transport selection * revision based on feedback * remove the code in create_request that has been moved'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DwaCompressor::uncompress (const char *inPtr, int inSize, IMATH_NAMESPACE::Box2i range, const char *&outPtr) { int minX = range.min.x; int maxX = std::min (range.max.x, _max[0]); int minY = range.min.y; int maxY = std::min (range.max.y, _max[1]); Int64 iSize = static_cast<Int64>( inSize ); Int64 headerSize = NUM_SIZES_SINGLE*sizeof(Int64); if (iSize < headerSize) { throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" "(truncated header)."); } // // Flip the counters from XDR to NATIVE // for (int i = 0; i < NUM_SIZES_SINGLE; ++i) { Int64 *dst = (((Int64 *)inPtr) + i); const char *src = (char *)(((Int64 *)inPtr) + i); Xdr::read<CharPtrIO> (src, *dst); } // // Unwind all the counter info // const Int64 *inPtr64 = (const Int64*) inPtr; Int64 version = *(inPtr64 + VERSION); Int64 unknownUncompressedSize = *(inPtr64 + UNKNOWN_UNCOMPRESSED_SIZE); Int64 unknownCompressedSize = *(inPtr64 + UNKNOWN_COMPRESSED_SIZE); Int64 acCompressedSize = *(inPtr64 + AC_COMPRESSED_SIZE); Int64 dcCompressedSize = *(inPtr64 + DC_COMPRESSED_SIZE); Int64 rleCompressedSize = *(inPtr64 + RLE_COMPRESSED_SIZE); Int64 rleUncompressedSize = *(inPtr64 + RLE_UNCOMPRESSED_SIZE); Int64 rleRawSize = *(inPtr64 + RLE_RAW_SIZE); Int64 totalAcUncompressedCount = *(inPtr64 + AC_UNCOMPRESSED_COUNT); Int64 totalDcUncompressedCount = *(inPtr64 + DC_UNCOMPRESSED_COUNT); Int64 acCompression = *(inPtr64 + AC_COMPRESSION); Int64 compressedSize = unknownCompressedSize + acCompressedSize + dcCompressedSize + rleCompressedSize; const char *dataPtr = inPtr + NUM_SIZES_SINGLE * sizeof(Int64); /* Both the sum and individual sizes are checked in case of overflow. */ if (iSize < (headerSize + compressedSize) || iSize < unknownCompressedSize || iSize < acCompressedSize || iSize < dcCompressedSize || iSize < rleCompressedSize) { throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" "(truncated file)."); } if ((SInt64)unknownUncompressedSize < 0 || (SInt64)unknownCompressedSize < 0 || (SInt64)acCompressedSize < 0 || (SInt64)dcCompressedSize < 0 || (SInt64)rleCompressedSize < 0 || (SInt64)rleUncompressedSize < 0 || (SInt64)rleRawSize < 0 || (SInt64)totalAcUncompressedCount < 0 || (SInt64)totalDcUncompressedCount < 0) { throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" " (corrupt header)."); } if (version < 2) initializeLegacyChannelRules(); else { unsigned short ruleSize = 0; Xdr::read<CharPtrIO>(dataPtr, ruleSize); if (ruleSize < Xdr::size<unsigned short>() ) throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" " (corrupt header file)."); headerSize += ruleSize; if (iSize < headerSize + compressedSize) throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" " (truncated file)."); _channelRules.clear(); ruleSize -= Xdr::size<unsigned short> (); while (ruleSize > 0) { Classifier rule(dataPtr, ruleSize); _channelRules.push_back(rule); ruleSize -= rule.size(); } } size_t outBufferSize = 0; initializeBuffers(outBufferSize); // // Allocate _outBuffer, if we haven't done so already // if (static_cast<size_t>(_maxScanLineSize * numScanLines()) > _outBufferSize) { _outBufferSize = static_cast<size_t>(_maxScanLineSize * numScanLines()); if (_outBuffer != 0) delete[] _outBuffer; _outBuffer = new char[_maxScanLineSize * numScanLines()]; } char *outBufferEnd = _outBuffer; // // Find the start of the RLE packed AC components and // the DC components for each channel. This will be handy // if you want to decode the channels in parallel later on. // char *packedAcBufferEnd = 0; if (_packedAcBuffer) packedAcBufferEnd = _packedAcBuffer; char *packedDcBufferEnd = 0; if (_packedDcBuffer) packedDcBufferEnd = _packedDcBuffer; // // UNKNOWN data is packed first, followed by the // Huffman-compressed AC, then the DC values, // and then the zlib compressed RLE data. // const char *compressedUnknownBuf = dataPtr; const char *compressedAcBuf = compressedUnknownBuf + static_cast<ptrdiff_t>(unknownCompressedSize); const char *compressedDcBuf = compressedAcBuf + static_cast<ptrdiff_t>(acCompressedSize); const char *compressedRleBuf = compressedDcBuf + static_cast<ptrdiff_t>(dcCompressedSize); // // Sanity check that the version is something we expect. Right now, // we can decode version 0, 1, and 2. v1 adds 'end of block' symbols // to the AC RLE. v2 adds channel classification rules at the // start of the data block. // if (version > 2) throw IEX_NAMESPACE::InputExc ("Invalid version of compressed data block"); setupChannelData(minX, minY, maxX, maxY); // // Uncompress the UNKNOWN data into _planarUncBuffer[UNKNOWN] // if (unknownCompressedSize > 0) { if (unknownUncompressedSize > _planarUncBufferSize[UNKNOWN]) { throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" "(corrupt header)."); } uLongf outSize = (uLongf)unknownUncompressedSize; if (Z_OK != ::uncompress ((Bytef *)_planarUncBuffer[UNKNOWN], &outSize, (Bytef *)compressedUnknownBuf, (uLong)unknownCompressedSize)) { throw IEX_NAMESPACE::BaseExc("Error uncompressing UNKNOWN data."); } } // // Uncompress the AC data into _packedAcBuffer // if (acCompressedSize > 0) { if (totalAcUncompressedCount*sizeof(unsigned short) > _packedAcBufferSize) { throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" "(corrupt header)."); } // // Don't trust the user to get it right, look in the file. // switch (acCompression) { case STATIC_HUFFMAN: hufUncompress (compressedAcBuf, (int)acCompressedSize, (unsigned short *)_packedAcBuffer, (int)totalAcUncompressedCount); break; case DEFLATE: { uLongf destLen = (int)(totalAcUncompressedCount) * sizeof (unsigned short); if (Z_OK != ::uncompress ((Bytef *)_packedAcBuffer, &destLen, (Bytef *)compressedAcBuf, (uLong)acCompressedSize)) { throw IEX_NAMESPACE::InputExc ("Data decompression (zlib) failed."); } if (totalAcUncompressedCount * sizeof (unsigned short) != destLen) { throw IEX_NAMESPACE::InputExc ("AC data corrupt."); } } break; default: throw IEX_NAMESPACE::NoImplExc ("Unknown AC Compression"); break; } } // // Uncompress the DC data into _packedDcBuffer // if (dcCompressedSize > 0) { if (totalDcUncompressedCount*sizeof(unsigned short) > _packedDcBufferSize) { throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" "(corrupt header)."); } if (static_cast<Int64>(_zip->uncompress (compressedDcBuf, (int)dcCompressedSize, _packedDcBuffer)) != totalDcUncompressedCount * sizeof (unsigned short)) { throw IEX_NAMESPACE::BaseExc("DC data corrupt."); } } // // Uncompress the RLE data into _rleBuffer, then unRLE the results // into _planarUncBuffer[RLE] // if (rleRawSize > 0) { if (rleUncompressedSize > _rleBufferSize || rleRawSize > _planarUncBufferSize[RLE]) { throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" "(corrupt header)."); } uLongf dstLen = (uLongf)rleUncompressedSize; if (Z_OK != ::uncompress ((Bytef *)_rleBuffer, &dstLen, (Bytef *)compressedRleBuf, (uLong)rleCompressedSize)) { throw IEX_NAMESPACE::BaseExc("Error uncompressing RLE data."); } if (dstLen != rleUncompressedSize) throw IEX_NAMESPACE::BaseExc("RLE data corrupted"); if (static_cast<Int64>(rleUncompress ((int)rleUncompressedSize, (int)rleRawSize, (signed char *)_rleBuffer, _planarUncBuffer[RLE])) != rleRawSize) { throw IEX_NAMESPACE::BaseExc("RLE data corrupted"); } } // // Determine the start of each row in the output buffer // std::vector<bool> decodedChannels (_channelData.size()); std::vector< std::vector<char *> > rowPtrs (_channelData.size()); for (unsigned int chan = 0; chan < _channelData.size(); ++chan) decodedChannels[chan] = false; outBufferEnd = _outBuffer; for (int y = minY; y <= maxY; ++y) { for (unsigned int chan = 0; chan < _channelData.size(); ++chan) { ChannelData *cd = &_channelData[chan]; if (IMATH_NAMESPACE::modp (y, cd->ySampling) != 0) continue; rowPtrs[chan].push_back (outBufferEnd); outBufferEnd += cd->width * OPENEXR_IMF_NAMESPACE::pixelTypeSize (cd->type); } } // // Setup to decode each block of 3 channels that need to // be handled together // for (unsigned int csc = 0; csc < _cscSets.size(); ++csc) { int rChan = _cscSets[csc].idx[0]; int gChan = _cscSets[csc].idx[1]; int bChan = _cscSets[csc].idx[2]; LossyDctDecoderCsc decoder (rowPtrs[rChan], rowPtrs[gChan], rowPtrs[bChan], packedAcBufferEnd, packedDcBufferEnd, dwaCompressorToLinear, _channelData[rChan].width, _channelData[rChan].height, _channelData[rChan].type, _channelData[gChan].type, _channelData[bChan].type); decoder.execute(); packedAcBufferEnd += decoder.numAcValuesEncoded() * sizeof (unsigned short); packedDcBufferEnd += decoder.numDcValuesEncoded() * sizeof (unsigned short); decodedChannels[rChan] = true; decodedChannels[gChan] = true; decodedChannels[bChan] = true; } // // Setup to handle the remaining channels by themselves // for (unsigned int chan = 0; chan < _channelData.size(); ++chan) { if (decodedChannels[chan]) continue; ChannelData *cd = &_channelData[chan]; int pixelSize = OPENEXR_IMF_NAMESPACE::pixelTypeSize (cd->type); switch (cd->compression) { case LOSSY_DCT: // // Setup a single-channel lossy DCT decoder pointing // at the output buffer // { const unsigned short *linearLut = 0; if (!cd->pLinear) linearLut = dwaCompressorToLinear; LossyDctDecoder decoder (rowPtrs[chan], packedAcBufferEnd, packedDcBufferEnd, linearLut, cd->width, cd->height, cd->type); decoder.execute(); packedAcBufferEnd += decoder.numAcValuesEncoded() * sizeof (unsigned short); packedDcBufferEnd += decoder.numDcValuesEncoded() * sizeof (unsigned short); } break; case RLE: // // For the RLE case, the data has been un-RLE'd into // planarUncRleEnd[], but is still split out by bytes. // We need to rearrange the bytes back into the correct // order in the output buffer; // { int row = 0; for (int y = minY; y <= maxY; ++y) { if (IMATH_NAMESPACE::modp (y, cd->ySampling) != 0) continue; char *dst = rowPtrs[chan][row]; if (pixelSize == 2) { interleaveByte2 (dst, cd->planarUncRleEnd[0], cd->planarUncRleEnd[1], cd->width); cd->planarUncRleEnd[0] += cd->width; cd->planarUncRleEnd[1] += cd->width; } else { for (int x = 0; x < cd->width; ++x) { for (int byte = 0; byte < pixelSize; ++byte) { *dst++ = *cd->planarUncRleEnd[byte]++; } } } row++; } } break; case UNKNOWN: // // In the UNKNOWN case, data is already in planarUncBufferEnd // and just needs to copied over to the output buffer // { int row = 0; int dstScanlineSize = cd->width * OPENEXR_IMF_NAMESPACE::pixelTypeSize (cd->type); for (int y = minY; y <= maxY; ++y) { if (IMATH_NAMESPACE::modp (y, cd->ySampling) != 0) continue; // // sanity check for buffer data lying within range // if ((cd->planarUncBufferEnd + static_cast<size_t>(dstScanlineSize)) > (_planarUncBuffer[UNKNOWN] + _planarUncBufferSize[UNKNOWN]) ) { throw Iex::InputExc("DWA data corrupt"); } memcpy (rowPtrs[chan][row], cd->planarUncBufferEnd, dstScanlineSize); cd->planarUncBufferEnd += dstScanlineSize; row++; } } break; default: throw IEX_NAMESPACE::NoImplExc ("Unhandled compression scheme case"); break; } decodedChannels[chan] = true; } // // Return a ptr to _outBuffer // outPtr = _outBuffer; return (int)(outBufferEnd - _outBuffer); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'double-check unpackedBuffer created in DWA uncompress Signed-off-by: Peter Hillman <peterh@wetafx.co.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: writeRead (const Array2D<unsigned int> &pi1, const Array2D<half> &ph1, const Array2D<float> &pf1, const char fileName[], LineOrder lorder, int width, int height, int xSize, int ySize, int xOffset, int yOffset, Compression comp, LevelMode mode, LevelRoundingMode rmode) { // // Write the pixel data in pi1, ph1 and ph2 to a tiled // image file using the specified parameters. // Read the pixel data back from the file using the scanline // interface one scanline at a time, and verify that the data did // not change. // For MIPMAP and RIPMAP_LEVELS, the lower levels of the images // are filled in cropped versions of the level(0,0) image, // i.e. no filtering is done. // cout << "levelMode " << mode << ", roundingMode " << rmode << ", line order " << lorder << ",\ntileSize " << xSize << "x" << ySize << ", xOffset " << xOffset << ", yOffset "<< yOffset << endl; Header hdr ((Box2i (V2i (0, 0), // display window V2i (width - 1, height -1))), (Box2i (V2i (xOffset, yOffset), // data window V2i (xOffset + width - 1, yOffset + height - 1)))); hdr.lineOrder() = lorder; hdr.compression() = comp; hdr.channels().insert ("I", Channel (IMF::UINT)); hdr.channels().insert ("H", Channel (IMF::HALF)); hdr.channels().insert ("F", Channel (IMF::FLOAT)); hdr.setTileDescription(TileDescription(xSize, ySize, mode, rmode)); { FrameBuffer fb; fb.insert ("I", // name Slice (IMF::UINT, // type (char *) &pi1[-yOffset][-xOffset], // base sizeof (pi1[0][0]), // xStride sizeof (pi1[0][0]) * width) // yStride ); fb.insert ("H", // name Slice (IMF::HALF, // type (char *) &ph1[-yOffset][-xOffset], // base sizeof (ph1[0][0]), // xStride sizeof (ph1[0][0]) * width) // yStride ); fb.insert ("F", // name Slice (IMF::FLOAT, // type (char *) &pf1[-yOffset][-xOffset], // base sizeof (pf1[0][0]), // xStride sizeof (pf1[0][0]) * width) // yStride ); cout << " writing" << flush; remove (fileName); TiledOutputFile out (fileName, hdr); out.setFrameBuffer (fb); int startTileY = -1; int endTileY = -1; int dy; switch (mode) { case ONE_LEVEL: { if (lorder == DECREASING_Y) { startTileY = out.numYTiles() - 1; endTileY = -1; dy = -1; } else { startTileY = 0; endTileY = out.numYTiles(); dy = 1; } for (int tileY = startTileY; tileY != endTileY; tileY += dy) for (int tileX = 0; tileX < out.numXTiles(); ++tileX) out.writeTile (tileX, tileY); } break; case MIPMAP_LEVELS: { if (lorder == DECREASING_Y) { endTileY = -1; dy = -1; } else { startTileY = 0; dy = 1; } for (int level = 0; level < out.numLevels(); ++level) { if (lorder == DECREASING_Y) startTileY = out.numYTiles(level) - 1; else endTileY = out.numYTiles(level); for (int tileY = startTileY; tileY != endTileY; tileY += dy) for (int tileX = 0; tileX < out.numXTiles(level); ++tileX) out.writeTile (tileX, tileY, level); } } break; case RIPMAP_LEVELS: { for (int ylevel = 0; ylevel < out.numYLevels(); ++ylevel) { if (lorder == DECREASING_Y) { startTileY = out.numYTiles(ylevel) - 1; endTileY = -1; dy = -1; } else { startTileY = 0; endTileY = out.numYTiles(ylevel); dy = 1; } for (int xlevel = 0; xlevel < out.numXLevels(); ++xlevel) { for (int tileY = startTileY; tileY != endTileY; tileY += dy) for (int tileX = 0; tileX < out.numXTiles (xlevel); ++tileX) out.writeTile (tileX, tileY, xlevel, ylevel); } } } break; case NUM_LEVELMODES: default: std::cerr << "Invalid tile mode " << int(mode) << std::endl; break; } } { cout << " reading INCREASING_Y" << flush; InputFile in (fileName); const Box2i &dw = in.header().dataWindow(); int w = dw.max.x - dw.min.x + 1; int h = dw.max.y - dw.min.y + 1; int dwx = dw.min.x; int dwy = dw.min.y; Array2D<unsigned int> pi2 (h, w); Array2D<half> ph2 (h, w); Array2D<float> pf2 (h, w); FrameBuffer fb; fb.insert ("I", // name Slice (IMF::UINT, // type (char *) &pi2[-dwy][-dwx],// base sizeof (pi2[0][0]), // xStride sizeof (pi2[0][0]) * w) // yStride ); fb.insert ("H", // name Slice (IMF::HALF, // type (char *) &ph2[-dwy][-dwx],// base sizeof (ph2[0][0]), // xStride sizeof (ph2[0][0]) * w) // yStride ); fb.insert ("F", // name Slice (IMF::FLOAT, // type (char *) &pf2[-dwy][-dwx],// base sizeof (pf2[0][0]), // xStride sizeof (pf2[0][0]) * w) // yStride ); in.setFrameBuffer (fb); for (int y = dw.min.y; y <= dw.max.y; ++y) in.readPixels (y); cout << " comparing" << flush; assert (in.header().displayWindow() == hdr.displayWindow()); assert (in.header().dataWindow() == hdr.dataWindow()); assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio()); assert (in.header().screenWindowCenter() == hdr.screenWindowCenter()); assert (in.header().screenWindowWidth() == hdr.screenWindowWidth()); assert (in.header().lineOrder() == hdr.lineOrder()); assert (in.header().compression() == hdr.compression()); ChannelList::ConstIterator hi = hdr.channels().begin(); ChannelList::ConstIterator ii = in.header().channels().begin(); while (hi != hdr.channels().end()) { assert (!strcmp (hi.name(), ii.name())); assert (hi.channel().type == ii.channel().type); assert (hi.channel().xSampling == ii.channel().xSampling); assert (hi.channel().ySampling == ii.channel().ySampling); ++hi; ++ii; } assert (ii == in.header().channels().end()); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { assert (pi1[y][x] == pi2[y][x]); assert (ph1[y][x] == ph2[y][x]); assert (pf1[y][x] == pf2[y][x]); } } } { cout << endl << " reading DECREASING_Y" << flush; InputFile in (fileName); const Box2i &dw = in.header().dataWindow(); int w = dw.max.x - dw.min.x + 1; int h = dw.max.y - dw.min.y + 1; int dwx = dw.min.x; int dwy = dw.min.y; Array2D<unsigned int> pi2 (h, w); Array2D<half> ph2 (h, w); Array2D<float> pf2 (h, w); FrameBuffer fb; fb.insert ("I", // name Slice (IMF::UINT, // type (char *) &pi2[-dwy][-dwx],// base sizeof (pi2[0][0]), // xStride sizeof (pi2[0][0]) * w) // yStride ); fb.insert ("H", // name Slice (IMF::HALF, // type (char *) &ph2[-dwy][-dwx],// base sizeof (ph2[0][0]), // xStride sizeof (ph2[0][0]) * w) // yStride ); fb.insert ("F", // name Slice (IMF::FLOAT, // type (char *) &pf2[-dwy][-dwx],// base sizeof (pf2[0][0]), // xStride sizeof (pf2[0][0]) * w) // yStride ); in.setFrameBuffer (fb); for (int y = dw.max.y; y >= dw.min.y; --y) in.readPixels (y); cout << " comparing" << flush; assert (in.header().displayWindow() == hdr.displayWindow()); assert (in.header().dataWindow() == hdr.dataWindow()); assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio()); assert (in.header().screenWindowCenter() == hdr.screenWindowCenter()); assert (in.header().screenWindowWidth() == hdr.screenWindowWidth()); assert (in.header().lineOrder() == hdr.lineOrder()); assert (in.header().compression() == hdr.compression()); ChannelList::ConstIterator hi = hdr.channels().begin(); ChannelList::ConstIterator ii = in.header().channels().begin(); while (hi != hdr.channels().end()) { assert (!strcmp (hi.name(), ii.name())); assert (hi.channel().type == ii.channel().type); assert (hi.channel().xSampling == ii.channel().xSampling); assert (hi.channel().ySampling == ii.channel().ySampling); ++hi; ++ii; } assert (ii == in.header().channels().end()); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { assert (pi1[y][x] == pi2[y][x]); assert (ph1[y][x] == ph2[y][x]); assert (pf1[y][x] == pf2[y][x]); } } } { cout << endl << " reading INCREASING_Y " "(new frame buffer on every line)" << flush; InputFile in (fileName); const Box2i &dw = in.header().dataWindow(); int w = dw.max.x - dw.min.x + 1; int h = dw.max.y - dw.min.y + 1; int dwx = dw.min.x; int dwy = dw.min.y; Array2D<unsigned int> pi2 (h, w); Array2D<half> ph2 (h, w); Array2D<float> pf2 (h, w); for (int y = dw.min.y; y <= dw.max.y; ++y) { FrameBuffer fb; fb.insert ("I", // name Slice (IMF::UINT, // type (char *) &pi2[y - dwy][-dwx], // base sizeof (pi2[0][0]), // xStride 0) // yStride ); fb.insert ("H", // name Slice (IMF::HALF, // type (char *) &ph2[y - dwy][-dwx], // base sizeof (ph2[0][0]), // xStride 0) // yStride ); fb.insert ("F", // name Slice (IMF::FLOAT, // type (char *) &pf2[y - dwy][-dwx], // base sizeof (pf2[0][0]), // xStride 0) // yStride ); in.setFrameBuffer (fb); in.readPixels (y); } cout << " comparing" << flush; assert (in.header().displayWindow() == hdr.displayWindow()); assert (in.header().dataWindow() == hdr.dataWindow()); assert (in.header().pixelAspectRatio() == hdr.pixelAspectRatio()); assert (in.header().screenWindowCenter() == hdr.screenWindowCenter()); assert (in.header().screenWindowWidth() == hdr.screenWindowWidth()); assert (in.header().lineOrder() == hdr.lineOrder()); assert (in.header().compression() == hdr.compression()); ChannelList::ConstIterator hi = hdr.channels().begin(); ChannelList::ConstIterator ii = in.header().channels().begin(); while (hi != hdr.channels().end()) { assert (!strcmp (hi.name(), ii.name())); assert (hi.channel().type == ii.channel().type); assert (hi.channel().xSampling == ii.channel().xSampling); assert (hi.channel().ySampling == ii.channel().ySampling); ++hi; ++ii; } assert (ii == in.header().channels().end()); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { assert (pi1[y][x] == pi2[y][x]); assert (ph1[y][x] == ph2[y][x]); assert (pf1[y][x] == pf2[y][x]); } } } remove (fileName); cout << endl; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'More efficient handling of filled channels reading tiles with scanline API (#830) * refactor channel filling in InputFile API with tiled source Signed-off-by: Peter Hillman <peterh@wetafx.co.nz> * handle edge-case of empty framebuffer Signed-off-by: Peter Hillman <peterh@wetafx.co.nz>'</s>
<s>[INST] Given the following code containing errors, provide 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) { l_int32 w, h; PIX *pixs, *pixg, *pixim, *pixgm, *pixmi, *pix1, *pix2; PIX *pixmr, *pixmg, *pixmb, *pixmri, *pixmgi, *pixmbi; PIXA *pixa; L_REGPARAMS *rp; if (regTestSetup(argc, argv, &rp)) return 1; lept_mkdir("lept/adapt"); // REMOVE? pixs = pixRead("wet-day.jpg"); pixa = pixaCreate(0); pixg = pixConvertRGBToGray(pixs, 0.33, 0.34, 0.33); pixaAddPix(pixa, pixs, L_INSERT); pixaAddPix(pixa, pixg, L_INSERT); pixGetDimensions(pixs, &w, &h, NULL); /* Process in grayscale */ startTimer(); pixim = pixCreate(w, h, 1); pixRasterop(pixim, XS, YS, WS, HS, PIX_SET, NULL, 0, 0); pixGetBackgroundGrayMap(pixg, pixim, SIZE_X, SIZE_Y, BINTHRESH, MINCOUNT, &pixgm); fprintf(stderr, "Time for gray adaptmap gen: %7.3f\n", stopTimer()); regTestWritePixAndCheck(rp, pixgm, IFF_PNG); /* 0 */ pixaAddPix(pixa, pixgm, L_INSERT); startTimer(); pixmi = pixGetInvBackgroundMap(pixgm, BGVAL, SMOOTH_X, SMOOTH_Y); fprintf(stderr, "Time for gray inv map generation: %7.3f\n", stopTimer()); regTestWritePixAndCheck(rp, pixmi, IFF_PNG); /* 1 */ pixaAddPix(pixa, pixmi, L_INSERT); startTimer(); pix1 = pixApplyInvBackgroundGrayMap(pixg, pixmi, SIZE_X, SIZE_Y); fprintf(stderr, "Time to apply gray inv map: %7.3f\n", stopTimer()); regTestWritePixAndCheck(rp, pix1, IFF_JFIF_JPEG); /* 2 */ pixaAddPix(pixa, pix1, L_INSERT); pix2 = pixGammaTRCMasked(NULL, pix1, pixim, 1.0, 0, 190); pixInvert(pixim, pixim); pixGammaTRCMasked(pix2, pix2, pixim, 1.0, 60, 190); regTestWritePixAndCheck(rp, pix2, IFF_JFIF_JPEG); /* 3 */ pixaAddPix(pixa, pix2, L_INSERT); pixDestroy(&pixim); /* Process in color */ startTimer(); pixim = pixCreate(w, h, 1); pixRasterop(pixim, XS, YS, WS, HS, PIX_SET, NULL, 0, 0); pixGetBackgroundRGBMap(pixs, pixim, NULL, SIZE_X, SIZE_Y, BINTHRESH, MINCOUNT, &pixmr, &pixmg, &pixmb); fprintf(stderr, "Time for color adaptmap gen: %7.3f\n", stopTimer()); regTestWritePixAndCheck(rp, pixmr, IFF_PNG); /* 4 */ regTestWritePixAndCheck(rp, pixmg, IFF_PNG); /* 5 */ regTestWritePixAndCheck(rp, pixmb, IFF_PNG); /* 6 */ pixaAddPix(pixa, pixmr, L_INSERT); pixaAddPix(pixa, pixmg, L_INSERT); pixaAddPix(pixa, pixmb, L_INSERT); startTimer(); pixmri = pixGetInvBackgroundMap(pixmr, BGVAL, SMOOTH_X, SMOOTH_Y); pixmgi = pixGetInvBackgroundMap(pixmg, BGVAL, SMOOTH_X, SMOOTH_Y); pixmbi = pixGetInvBackgroundMap(pixmb, BGVAL, SMOOTH_X, SMOOTH_Y); fprintf(stderr, "Time for color inv map generation: %7.3f\n", stopTimer()); regTestWritePixAndCheck(rp, pixmri, IFF_PNG); /* 7 */ regTestWritePixAndCheck(rp, pixmgi, IFF_PNG); /* 8 */ regTestWritePixAndCheck(rp, pixmbi, IFF_PNG); /* 9 */ pixaAddPix(pixa, pixmri, L_INSERT); pixaAddPix(pixa, pixmgi, L_INSERT); pixaAddPix(pixa, pixmbi, L_INSERT); startTimer(); pix1 = pixApplyInvBackgroundRGBMap(pixs, pixmri, pixmgi, pixmbi, SIZE_X, SIZE_Y); fprintf(stderr, "Time to apply color inv maps: %7.3f\n", stopTimer()); regTestWritePixAndCheck(rp, pix1, IFF_JFIF_JPEG); /* 10 */ pixaAddPix(pixa, pix1, L_INSERT); pix2 = pixGammaTRCMasked(NULL, pix1, pixim, 1.0, 0, 190); pixInvert(pixim, pixim); pixGammaTRCMasked(pix2, pix2, pixim, 1.0, 60, 190); regTestWritePixAndCheck(rp, pix2, IFF_JFIF_JPEG); /* 11 */ pixaAddPix(pixa, pix2, L_INSERT); pixDestroy(&pixim); /* Process at higher level in color */ startTimer(); pixim = pixCreate(w, h, 1); pixRasterop(pixim, XS, YS, WS, HS, PIX_SET, NULL, 0, 0); pix1 = pixBackgroundNorm(pixs, pixim, NULL, 5, 10, BINTHRESH, 20, BGVAL, SMOOTH_X, SMOOTH_Y); fprintf(stderr, "Time for bg normalization: %7.3f\n", stopTimer()); regTestWritePixAndCheck(rp, pix1, IFF_JFIF_JPEG); /* 12 */ pixaAddPix(pixa, pix1, L_INSERT); pix2 = pixGammaTRCMasked(NULL, pix1, pixim, 1.0, 0, 190); pixInvert(pixim, pixim); pixGammaTRCMasked(pix2, pix2, pixim, 1.0, 60, 190); regTestWritePixAndCheck(rp, pix2, IFF_JFIF_JPEG); /* 13 */ pixaAddPix(pixa, pix2, L_INSERT); pixDestroy(&pixim); /* Display results */ pix1 = pixaDisplayTiledAndScaled(pixa, 32, 400, 4, 0, 20, 2); pixWrite("/tmp/lept/adapt/results.jpg", pix1, IFF_JFIF_JPEG); pixDisplayWithTitle(pix1, 100, 0, NULL, rp->display); pixDestroy(&pix1); pixaDestroy(&pixa); return regTestCleanup(rp); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixing oss-fuzz issue 22512: Heap-buffer-overflow in rasteropGeneralLow() * Simplified the hole-filling function `'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: autoar_extractor_check_file_conflict (GFile *file, mode_t extracted_filetype) { GFileType file_type; file_type = g_file_query_file_type (file, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL); /* If there is no file with the given name, there will be no conflict */ if (file_type == G_FILE_TYPE_UNKNOWN) { return FALSE; } /* It is not problem if the directory already exists */ if (file_type == G_FILE_TYPE_DIRECTORY && extracted_filetype == AE_IFDIR) { return FALSE; } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'extractor: Do not allow symlink in parents Currently, it is still possible that some files are extracted outside of the destination dir in case of malicious archives. The checks from commit adb067e6 can be still bypassed in certain cases. See GNOME/file-roller#108 for more details. After some investigation, I am convinced that it would be best to simply disallow symlinks in parents. For example, `tar` fails to extract such files with the `ENOTDIR` error. Let's do the same here. Fixes: https://gitlab.gnome.org/GNOME/gnome-autoar/-/issues/12'</s>
<s>[INST] Given the following code containing errors, provide 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 io_disable_sqo_submit(struct io_ring_ctx *ctx) { mutex_lock(&ctx->uring_lock); ctx->sqo_dead = 1; mutex_unlock(&ctx->uring_lock); /* make sure callers enter the ring to get error */ if (ctx->rings) io_ring_set_wakeup_flag(ctx); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-667'], 'message': 'io_uring: ensure that SQPOLL thread is started for exit If we create it in a disabled state because IORING_SETUP_R_DISABLED is set on ring creation, we need to ensure that we've kicked the thread if we're exiting before it's been explicitly disabled. Otherwise we can run into a deadlock where exit is waiting go park the SQPOLL thread, but the SQPOLL thread itself is waiting to get a signal to start. That results in the below trace of both tasks hung, waiting on each other: INFO: task syz-executor458:8401 blocked for more than 143 seconds. Not tainted 5.11.0-next-20210226-syzkaller #0 "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message. task:syz-executor458 state:D stack:27536 pid: 8401 ppid: 8400 flags:0x00004004 Call Trace: context_switch kernel/sched/core.c:4324 [inline] __schedule+0x90c/0x21a0 kernel/sched/core.c:5075 schedule+0xcf/0x270 kernel/sched/core.c:5154 schedule_timeout+0x1db/0x250 kernel/time/timer.c:1868 do_wait_for_common kernel/sched/completion.c:85 [inline] __wait_for_common kernel/sched/completion.c:106 [inline] wait_for_common kernel/sched/completion.c:117 [inline] wait_for_completion+0x168/0x270 kernel/sched/completion.c:138 io_sq_thread_park fs/io_uring.c:7115 [inline] io_sq_thread_park+0xd5/0x130 fs/io_uring.c:7103 io_uring_cancel_task_requests+0x24c/0xd90 fs/io_uring.c:8745 __io_uring_files_cancel+0x110/0x230 fs/io_uring.c:8840 io_uring_files_cancel include/linux/io_uring.h:47 [inline] do_exit+0x299/0x2a60 kernel/exit.c:780 do_group_exit+0x125/0x310 kernel/exit.c:922 __do_sys_exit_group kernel/exit.c:933 [inline] __se_sys_exit_group kernel/exit.c:931 [inline] __x64_sys_exit_group+0x3a/0x50 kernel/exit.c:931 do_syscall_64+0x2d/0x70 arch/x86/entry/common.c:46 entry_SYSCALL_64_after_hwframe+0x44/0xae RIP: 0033:0x43e899 RSP: 002b:00007ffe89376d48 EFLAGS: 00000246 ORIG_RAX: 00000000000000e7 RAX: ffffffffffffffda RBX: 00000000004af2f0 RCX: 000000000043e899 RDX: 000000000000003c RSI: 00000000000000e7 RDI: 0000000000000000 RBP: 0000000000000000 R08: ffffffffffffffc0 R09: 0000000010000000 R10: 0000000000008011 R11: 0000000000000246 R12: 00000000004af2f0 R13: 0000000000000001 R14: 0000000000000000 R15: 0000000000000001 INFO: task iou-sqp-8401:8402 can't die for more than 143 seconds. task:iou-sqp-8401 state:D stack:30272 pid: 8402 ppid: 8400 flags:0x00004004 Call Trace: context_switch kernel/sched/core.c:4324 [inline] __schedule+0x90c/0x21a0 kernel/sched/core.c:5075 schedule+0xcf/0x270 kernel/sched/core.c:5154 schedule_timeout+0x1db/0x250 kernel/time/timer.c:1868 do_wait_for_common kernel/sched/completion.c:85 [inline] __wait_for_common kernel/sched/completion.c:106 [inline] wait_for_common kernel/sched/completion.c:117 [inline] wait_for_completion+0x168/0x270 kernel/sched/completion.c:138 io_sq_thread+0x27d/0x1ae0 fs/io_uring.c:6717 ret_from_fork+0x1f/0x30 arch/x86/entry/entry_64.S:294 INFO: task iou-sqp-8401:8402 blocked for more than 143 seconds. Reported-by: syzbot+fb5458330b4442f2090d@syzkaller.appspotmail.com Signed-off-by: Jens Axboe <axboe@kernel.dk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: wolfssl_connect_step1(struct Curl_easy *data, struct connectdata *conn, int sockindex) { char *ciphers; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct ssl_backend_data *backend = connssl->backend; SSL_METHOD* req_method = NULL; curl_socket_t sockfd = conn->sock[sockindex]; #ifdef HAVE_SNI bool sni = FALSE; #define use_sni(x) sni = (x) #else #define use_sni(x) Curl_nop_stmt #endif if(connssl->state == ssl_connection_complete) return CURLE_OK; if(SSL_CONN_CONFIG(version_max) != CURL_SSLVERSION_MAX_NONE) { failf(data, "wolfSSL does not support to set maximum SSL/TLS version"); return CURLE_SSL_CONNECT_ERROR; } /* check to see if we've been told to use an explicit SSL/TLS version */ switch(SSL_CONN_CONFIG(version)) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: #if LIBWOLFSSL_VERSION_HEX >= 0x03003000 /* >= 3.3.0 */ /* minimum protocol version is set later after the CTX object is created */ req_method = SSLv23_client_method(); #else infof(data, "wolfSSL <3.3.0 cannot be configured to use TLS 1.0-1.2, " "TLS 1.0 is used exclusively\n"); req_method = TLSv1_client_method(); #endif use_sni(TRUE); break; case CURL_SSLVERSION_TLSv1_0: #if defined(WOLFSSL_ALLOW_TLSV10) && !defined(NO_OLD_TLS) req_method = TLSv1_client_method(); use_sni(TRUE); #else failf(data, "wolfSSL does not support TLS 1.0"); return CURLE_NOT_BUILT_IN; #endif break; case CURL_SSLVERSION_TLSv1_1: #ifndef NO_OLD_TLS req_method = TLSv1_1_client_method(); use_sni(TRUE); #else failf(data, "wolfSSL does not support TLS 1.1"); return CURLE_NOT_BUILT_IN; #endif break; case CURL_SSLVERSION_TLSv1_2: req_method = TLSv1_2_client_method(); use_sni(TRUE); break; case CURL_SSLVERSION_TLSv1_3: #ifdef WOLFSSL_TLS13 req_method = wolfTLSv1_3_client_method(); use_sni(TRUE); break; #else failf(data, "wolfSSL: TLS 1.3 is not yet supported"); return CURLE_SSL_CONNECT_ERROR; #endif case CURL_SSLVERSION_SSLv3: #ifdef WOLFSSL_ALLOW_SSLV3 req_method = SSLv3_client_method(); use_sni(FALSE); #else failf(data, "wolfSSL does not support SSLv3"); return CURLE_NOT_BUILT_IN; #endif break; case CURL_SSLVERSION_SSLv2: failf(data, "wolfSSL does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } if(!req_method) { failf(data, "SSL: couldn't create a method!"); return CURLE_OUT_OF_MEMORY; } if(backend->ctx) SSL_CTX_free(backend->ctx); backend->ctx = SSL_CTX_new(req_method); if(!backend->ctx) { failf(data, "SSL: couldn't create a context!"); return CURLE_OUT_OF_MEMORY; } switch(SSL_CONN_CONFIG(version)) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: #if LIBWOLFSSL_VERSION_HEX > 0x03004006 /* > 3.4.6 */ /* Versions 3.3.0 to 3.4.6 we know the minimum protocol version is * whatever minimum version of TLS was built in and at least TLS 1.0. For * later library versions that could change (eg TLS 1.0 built in but * defaults to TLS 1.1) so we have this short circuit evaluation to find * the minimum supported TLS version. */ if((wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1) != 1) && (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_1) != 1) && (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_2) != 1) #ifdef WOLFSSL_TLS13 && (wolfSSL_CTX_SetMinVersion(backend->ctx, WOLFSSL_TLSV1_3) != 1) #endif ) { failf(data, "SSL: couldn't set the minimum protocol version"); return CURLE_SSL_CONNECT_ERROR; } #endif break; } ciphers = SSL_CONN_CONFIG(cipher_list); if(ciphers) { if(!SSL_CTX_set_cipher_list(backend->ctx, ciphers)) { failf(data, "failed setting cipher list: %s", ciphers); return CURLE_SSL_CIPHER; } infof(data, "Cipher selection: %s\n", ciphers); } #ifndef NO_FILESYSTEM /* load trusted cacert */ if(SSL_CONN_CONFIG(CAfile)) { if(1 != SSL_CTX_load_verify_locations(backend->ctx, SSL_CONN_CONFIG(CAfile), SSL_CONN_CONFIG(CApath))) { if(SSL_CONN_CONFIG(verifypeer)) { /* Fail if we insist on successfully verifying the server. */ failf(data, "error setting certificate verify locations:" " CAfile: %s CApath: %s", SSL_CONN_CONFIG(CAfile)? SSL_CONN_CONFIG(CAfile): "none", SSL_CONN_CONFIG(CApath)? SSL_CONN_CONFIG(CApath) : "none"); return CURLE_SSL_CACERT_BADFILE; } else { /* Just continue with a warning if no strict certificate verification is required. */ infof(data, "error setting certificate verify locations," " continuing anyway:\n"); } } else { /* Everything is fine. */ infof(data, "successfully set certificate verify locations:\n"); } infof(data, " CAfile: %s\n", SSL_CONN_CONFIG(CAfile) ? SSL_CONN_CONFIG(CAfile) : "none"); infof(data, " CApath: %s\n", SSL_CONN_CONFIG(CApath) ? SSL_CONN_CONFIG(CApath) : "none"); } /* Load the client certificate, and private key */ if(SSL_SET_OPTION(primary.clientcert) && SSL_SET_OPTION(key)) { int file_type = do_file_type(SSL_SET_OPTION(cert_type)); if(SSL_CTX_use_certificate_file(backend->ctx, SSL_SET_OPTION(primary.clientcert), file_type) != 1) { failf(data, "unable to use client certificate (no key or wrong pass" " phrase?)"); return CURLE_SSL_CONNECT_ERROR; } file_type = do_file_type(SSL_SET_OPTION(key_type)); if(SSL_CTX_use_PrivateKey_file(backend->ctx, SSL_SET_OPTION(key), file_type) != 1) { failf(data, "unable to set private key"); return CURLE_SSL_CONNECT_ERROR; } } #endif /* !NO_FILESYSTEM */ /* SSL always tries to verify the peer, this only says whether it should * fail to connect if the verification fails, or if it should continue * anyway. In the latter case the result of the verification is checked with * SSL_get_verify_result() below. */ SSL_CTX_set_verify(backend->ctx, SSL_CONN_CONFIG(verifypeer)?SSL_VERIFY_PEER: SSL_VERIFY_NONE, NULL); #ifdef HAVE_SNI if(sni) { struct in_addr addr4; #ifdef ENABLE_IPV6 struct in6_addr addr6; #endif #ifndef CURL_DISABLE_PROXY const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; #else const char * const hostname = conn->host.name; #endif size_t hostname_len = strlen(hostname); if((hostname_len < USHRT_MAX) && (0 == Curl_inet_pton(AF_INET, hostname, &addr4)) && #ifdef ENABLE_IPV6 (0 == Curl_inet_pton(AF_INET6, hostname, &addr6)) && #endif (wolfSSL_CTX_UseSNI(backend->ctx, WOLFSSL_SNI_HOST_NAME, hostname, (unsigned short)hostname_len) != 1)) { infof(data, "WARNING: failed to configure server name indication (SNI) " "TLS extension\n"); } } #endif /* give application a chance to interfere with SSL set up. */ if(data->set.ssl.fsslctx) { CURLcode result = (*data->set.ssl.fsslctx)(data, backend->ctx, data->set.ssl.fsslctxp); if(result) { failf(data, "error signaled by ssl ctx callback"); return result; } } #ifdef NO_FILESYSTEM else if(SSL_CONN_CONFIG(verifypeer)) { failf(data, "SSL: Certificates can't be loaded because wolfSSL was built" " with \"no filesystem\". Either disable peer verification" " (insecure) or if you are building an application with libcurl you" " can load certificates via CURLOPT_SSL_CTX_FUNCTION."); return CURLE_SSL_CONNECT_ERROR; } #endif /* Let's make an SSL structure */ if(backend->handle) SSL_free(backend->handle); backend->handle = SSL_new(backend->ctx); if(!backend->handle) { failf(data, "SSL: couldn't create a context (handle)!"); return CURLE_OUT_OF_MEMORY; } #ifdef HAVE_ALPN if(conn->bits.tls_enable_alpn) { char protocols[128]; *protocols = '\0'; /* wolfSSL's ALPN protocol name list format is a comma separated string of protocols in descending order of preference, eg: "h2,http/1.1" */ #ifdef USE_NGHTTP2 if(data->state.httpversion >= CURL_HTTP_VERSION_2) { strcpy(protocols + strlen(protocols), NGHTTP2_PROTO_VERSION_ID ","); infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID); } #endif strcpy(protocols + strlen(protocols), ALPN_HTTP_1_1); infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1); if(wolfSSL_UseALPN(backend->handle, protocols, (unsigned)strlen(protocols), WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != SSL_SUCCESS) { failf(data, "SSL: failed setting ALPN protocols"); return CURLE_SSL_CONNECT_ERROR; } } #endif /* HAVE_ALPN */ #ifdef OPENSSL_EXTRA if(Curl_tls_keylog_enabled()) { /* Ensure the Client Random is preserved. */ wolfSSL_KeepArrays(backend->handle); #if defined(HAVE_SECRET_CALLBACK) && defined(WOLFSSL_TLS13) wolfSSL_set_tls13_secret_cb(backend->handle, wolfssl_tls13_secret_callback, NULL); #endif } #endif /* OPENSSL_EXTRA */ #ifdef HAVE_SECURE_RENEGOTIATION if(wolfSSL_UseSecureRenegotiation(backend->handle) != SSL_SUCCESS) { failf(data, "SSL: failed setting secure renegotiation"); return CURLE_SSL_CONNECT_ERROR; } #endif /* HAVE_SECURE_RENEGOTIATION */ /* Check if there's a cached ID we can/should use here! */ if(SSL_SET_OPTION(primary.sessionid)) { void *ssl_sessionid = NULL; Curl_ssl_sessionid_lock(data); if(!Curl_ssl_getsessionid(data, conn, &ssl_sessionid, NULL, sockindex)) { /* we got a session id, use it! */ if(!SSL_set_session(backend->handle, ssl_sessionid)) { char error_buffer[WOLFSSL_MAX_ERROR_SZ]; Curl_ssl_sessionid_unlock(data); failf(data, "SSL: SSL_set_session failed: %s", ERR_error_string(SSL_get_error(backend->handle, 0), error_buffer)); return CURLE_SSL_CONNECT_ERROR; } /* Informational message */ infof(data, "SSL re-using session ID\n"); } Curl_ssl_sessionid_unlock(data); } /* pass the raw socket into the SSL layer */ if(!SSL_set_fd(backend->handle, (int)sockfd)) { failf(data, "SSL: SSL_set_fd failed"); return CURLE_SSL_CONNECT_ERROR; } connssl->connecting_state = ssl_connect_2; return CURLE_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-290'], 'message': 'vtls: add 'isproxy' argument to Curl_ssl_get/addsessionid() To make sure we set and extract the correct session. Reported-by: Mingtao Yang Bug: https://curl.se/docs/CVE-2021-22890.html CVE-2021-22890'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mbed_connect_step1(struct Curl_easy *data, struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct ssl_backend_data *backend = connssl->backend; const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile); const bool verifypeer = SSL_CONN_CONFIG(verifypeer); const char * const ssl_capath = SSL_CONN_CONFIG(CApath); char * const ssl_cert = SSL_SET_OPTION(primary.clientcert); const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile); #ifndef CURL_DISABLE_PROXY const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port; #else const char * const hostname = conn->host.name; const long int port = conn->remote_port; #endif int ret = -1; char errorbuf[128]; errorbuf[0] = 0; /* mbedTLS only supports SSLv3 and TLSv1 */ if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) { failf(data, "mbedTLS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } #ifdef THREADING_SUPPORT entropy_init_mutex(&ts_entropy); mbedtls_ctr_drbg_init(&backend->ctr_drbg); ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, entropy_func_mutex, &ts_entropy, NULL, 0); if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s", -ret, errorbuf); } #else mbedtls_entropy_init(&backend->entropy); mbedtls_ctr_drbg_init(&backend->ctr_drbg); ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, mbedtls_entropy_func, &backend->entropy, NULL, 0); if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s", -ret, errorbuf); } #endif /* THREADING_SUPPORT */ /* Load the trusted CA */ mbedtls_x509_crt_init(&backend->cacert); if(ssl_cafile) { ret = mbedtls_x509_crt_parse_file(&backend->cacert, ssl_cafile); if(ret<0) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Error reading ca cert file %s - mbedTLS: (-0x%04X) %s", ssl_cafile, -ret, errorbuf); if(verifypeer) return CURLE_SSL_CACERT_BADFILE; } } if(ssl_capath) { ret = mbedtls_x509_crt_parse_path(&backend->cacert, ssl_capath); if(ret<0) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Error reading ca cert path %s - mbedTLS: (-0x%04X) %s", ssl_capath, -ret, errorbuf); if(verifypeer) return CURLE_SSL_CACERT_BADFILE; } } /* Load the client certificate */ mbedtls_x509_crt_init(&backend->clicert); if(ssl_cert) { ret = mbedtls_x509_crt_parse_file(&backend->clicert, ssl_cert); if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Error reading client cert file %s - mbedTLS: (-0x%04X) %s", ssl_cert, -ret, errorbuf); return CURLE_SSL_CERTPROBLEM; } } /* Load the client private key */ mbedtls_pk_init(&backend->pk); if(SSL_SET_OPTION(key)) { ret = mbedtls_pk_parse_keyfile(&backend->pk, SSL_SET_OPTION(key), SSL_SET_OPTION(key_passwd)); if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) || mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY))) ret = MBEDTLS_ERR_PK_TYPE_MISMATCH; if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s", SSL_SET_OPTION(key), -ret, errorbuf); return CURLE_SSL_CERTPROBLEM; } } /* Load the CRL */ mbedtls_x509_crl_init(&backend->crl); if(ssl_crlfile) { ret = mbedtls_x509_crl_parse_file(&backend->crl, ssl_crlfile); if(ret) { #ifdef MBEDTLS_ERROR_C mbedtls_strerror(ret, errorbuf, sizeof(errorbuf)); #endif /* MBEDTLS_ERROR_C */ failf(data, "Error reading CRL file %s - mbedTLS: (-0x%04X) %s", ssl_crlfile, -ret, errorbuf); return CURLE_SSL_CRL_BADFILE; } } infof(data, "mbedTLS: Connecting to %s:%ld\n", hostname, port); mbedtls_ssl_config_init(&backend->config); mbedtls_ssl_init(&backend->ssl); if(mbedtls_ssl_setup(&backend->ssl, &backend->config)) { failf(data, "mbedTLS: ssl_init failed"); return CURLE_SSL_CONNECT_ERROR; } ret = mbedtls_ssl_config_defaults(&backend->config, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT); if(ret) { failf(data, "mbedTLS: ssl_config failed"); return CURLE_SSL_CONNECT_ERROR; } /* new profile with RSA min key len = 1024 ... */ mbedtls_ssl_conf_cert_profile(&backend->config, &mbedtls_x509_crt_profile_fr); switch(SSL_CONN_CONFIG(version)) { case CURL_SSLVERSION_DEFAULT: case CURL_SSLVERSION_TLSv1: mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1); infof(data, "mbedTLS: Set min SSL version to TLS 1.0\n"); break; case CURL_SSLVERSION_SSLv3: mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0); mbedtls_ssl_conf_max_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_0); infof(data, "mbedTLS: Set SSL version to SSLv3\n"); break; case CURL_SSLVERSION_TLSv1_0: case CURL_SSLVERSION_TLSv1_1: case CURL_SSLVERSION_TLSv1_2: case CURL_SSLVERSION_TLSv1_3: { CURLcode result = set_ssl_version_min_max(data, conn, sockindex); if(result != CURLE_OK) return result; break; } default: failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION"); return CURLE_SSL_CONNECT_ERROR; } mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_OPTIONAL); mbedtls_ssl_conf_rng(&backend->config, mbedtls_ctr_drbg_random, &backend->ctr_drbg); mbedtls_ssl_set_bio(&backend->ssl, &conn->sock[sockindex], mbedtls_net_send, mbedtls_net_recv, NULL /* rev_timeout() */); mbedtls_ssl_conf_ciphersuites(&backend->config, mbedtls_ssl_list_ciphersuites()); #if defined(MBEDTLS_SSL_RENEGOTIATION) mbedtls_ssl_conf_renegotiation(&backend->config, MBEDTLS_SSL_RENEGOTIATION_ENABLED); #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) mbedtls_ssl_conf_session_tickets(&backend->config, MBEDTLS_SSL_SESSION_TICKETS_DISABLED); #endif /* Check if there's a cached ID we can/should use here! */ if(SSL_SET_OPTION(primary.sessionid)) { void *old_session = NULL; Curl_ssl_sessionid_lock(data); if(!Curl_ssl_getsessionid(data, conn, &old_session, NULL, sockindex)) { ret = mbedtls_ssl_set_session(&backend->ssl, old_session); if(ret) { Curl_ssl_sessionid_unlock(data); failf(data, "mbedtls_ssl_set_session returned -0x%x", -ret); return CURLE_SSL_CONNECT_ERROR; } infof(data, "mbedTLS re-using session\n"); } Curl_ssl_sessionid_unlock(data); } mbedtls_ssl_conf_ca_chain(&backend->config, &backend->cacert, &backend->crl); if(SSL_SET_OPTION(key)) { mbedtls_ssl_conf_own_cert(&backend->config, &backend->clicert, &backend->pk); } if(mbedtls_ssl_set_hostname(&backend->ssl, hostname)) { /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks *and* the name to set in the SNI extension. So even if curl connects to a host specified as an IP address, this function must be used. */ failf(data, "couldn't set hostname in mbedTLS"); return CURLE_SSL_CONNECT_ERROR; } #ifdef HAS_ALPN if(conn->bits.tls_enable_alpn) { const char **p = &backend->protocols[0]; #ifdef USE_NGHTTP2 if(data->state.httpversion >= CURL_HTTP_VERSION_2) *p++ = NGHTTP2_PROTO_VERSION_ID; #endif *p++ = ALPN_HTTP_1_1; *p = NULL; /* this function doesn't clone the protocols array, which is why we need to keep it around */ if(mbedtls_ssl_conf_alpn_protocols(&backend->config, &backend->protocols[0])) { failf(data, "Failed setting ALPN protocols"); return CURLE_SSL_CONNECT_ERROR; } for(p = &backend->protocols[0]; *p; ++p) infof(data, "ALPN, offering %s\n", *p); } #endif #ifdef MBEDTLS_DEBUG /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */ mbedtls_ssl_conf_dbg(&backend->config, mbed_debug, data); /* - 0 No debug * - 1 Error * - 2 State change * - 3 Informational * - 4 Verbose */ mbedtls_debug_set_threshold(4); #endif /* give application a chance to interfere with mbedTLS set up. */ if(data->set.ssl.fsslctx) { ret = (*data->set.ssl.fsslctx)(data, &backend->config, data->set.ssl.fsslctxp); if(ret) { failf(data, "error signaled by ssl ctx callback"); return ret; } } connssl->connecting_state = ssl_connect_2; return CURLE_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-290'], 'message': 'vtls: add 'isproxy' argument to Curl_ssl_get/addsessionid() To make sure we set and extract the correct session. Reported-by: Mingtao Yang Bug: https://curl.se/docs/CVE-2021-22890.html CVE-2021-22890'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ecc_eh_to_a (const struct ecc_curve *ecc, int op, mp_limb_t *r, const mp_limb_t *p, mp_limb_t *scratch) { #define izp scratch #define tp (scratch + ecc->p.size) #define xp p #define yp (p + ecc->p.size) #define zp (p + 2*ecc->p.size) mp_limb_t cy; assert(op == 0); /* Needs size + scratch for the invert call. */ ecc->p.invert (&ecc->p, izp, zp, tp); ecc_mod_mul (&ecc->p, tp, xp, izp, tp); cy = mpn_sub_n (r, tp, ecc->p.m, ecc->p.size); cnd_copy (cy, r, tp, ecc->p.size); ecc_mod_mul (&ecc->p, tp, yp, izp, tp); cy = mpn_sub_n (r + ecc->p.size, tp, ecc->p.m, ecc->p.size); cnd_copy (cy, r + ecc->p.size, tp, ecc->p.size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'New functions ecc_mod_mul_canonical and ecc_mod_sqr_canonical. * ecc-mod-arith.c (ecc_mod_mul_canonical, ecc_mod_sqr_canonical): New functions. * ecc-internal.h: Declare and document new functions. * curve448-eh-to-x.c (curve448_eh_to_x): Use ecc_mod_sqr_canonical. * curve25519-eh-to-x.c (curve25519_eh_to_x): Use ecc_mod_mul_canonical. * ecc-eh-to-a.c (ecc_eh_to_a): Likewise. * ecc-j-to-a.c (ecc_j_to_a): Likewise. * ecc-mul-m.c (ecc_mul_m): Likewise. (cherry picked from commit 2bf497ba4d6acc6f352bca015837fad33008565c)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: HRESULT Http::HrReadHeaders() { HRESULT hr; std::string strBuffer; ULONG n = 0; std::map<std::string, std::string>::iterator iHeader = mapHeaders.end(); ec_log_debug("Receiving headers:"); do { hr = m_lpChannel->HrReadLine(strBuffer); if (hr != hrSuccess) return hr; if (strBuffer.empty()) break; if (n == 0) { m_strAction = strBuffer; } else { auto pos = strBuffer.find(':'); size_t start = 0; if (strBuffer[0] == ' ' || strBuffer[0] == '\t') { if (iHeader == mapHeaders.end()) continue; // continue header while (strBuffer[start] == ' ' || strBuffer[start] == '\t') ++start; iHeader->second += strBuffer.substr(start); } else { // new header auto r = mapHeaders.emplace(strBuffer.substr(0, pos), strBuffer.substr(pos + 2)); iHeader = r.first; } } if (strBuffer.find("Authorization") != std::string::npos) ec_log_debug("< Authorization: <value hidden>"); else ec_log_debug("< "+strBuffer); ++n; } while(hr == hrSuccess); hr = HrParseHeaders(); if (hr != hrSuccess) hr_ldebug(hr, "parsing headers failed"); return hr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'Set limit on header size to prevent bad alloc This sets a hard limit of 64 KiB to the header to prevent a memory allocation exception from being thrown during the parsing of the request headers.'</s>
<s>[INST] Given the following code containing errors, provide 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 qrtr_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, int flags) { DECLARE_SOCKADDR(struct sockaddr_qrtr *, addr, msg->msg_name); struct sock *sk = sock->sk; struct sk_buff *skb; struct qrtr_cb *cb; int copied, rc; lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) { release_sock(sk); return -EADDRNOTAVAIL; } skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &rc); if (!skb) { release_sock(sk); return rc; } cb = (struct qrtr_cb *)skb->cb; copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } rc = skb_copy_datagram_msg(skb, 0, msg, copied); if (rc < 0) goto out; rc = copied; if (addr) { addr->sq_family = AF_QIPCRTR; addr->sq_node = cb->src_node; addr->sq_port = cb->src_port; msg->msg_namelen = sizeof(*addr); } out: if (cb->confirm_rx) qrtr_send_resume_tx(cb); skb_free_datagram(sk, skb); release_sock(sk); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-909'], 'message': 'net: qrtr: fix a kernel-infoleak in qrtr_recvmsg() struct sockaddr_qrtr has a 2-byte hole, and qrtr_recvmsg() currently does not clear it before copying kernel data to user space. It might be too late to name the hole since sockaddr_qrtr structure is uapi. BUG: KMSAN: kernel-infoleak in kmsan_copy_to_user+0x9c/0xb0 mm/kmsan/kmsan_hooks.c:249 CPU: 0 PID: 29705 Comm: syz-executor.3 Not tainted 5.11.0-rc7-syzkaller #0 Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011 Call Trace: __dump_stack lib/dump_stack.c:79 [inline] dump_stack+0x21c/0x280 lib/dump_stack.c:120 kmsan_report+0xfb/0x1e0 mm/kmsan/kmsan_report.c:118 kmsan_internal_check_memory+0x202/0x520 mm/kmsan/kmsan.c:402 kmsan_copy_to_user+0x9c/0xb0 mm/kmsan/kmsan_hooks.c:249 instrument_copy_to_user include/linux/instrumented.h:121 [inline] _copy_to_user+0x1ac/0x270 lib/usercopy.c:33 copy_to_user include/linux/uaccess.h:209 [inline] move_addr_to_user+0x3a2/0x640 net/socket.c:237 ____sys_recvmsg+0x696/0xd50 net/socket.c:2575 ___sys_recvmsg net/socket.c:2610 [inline] do_recvmmsg+0xa97/0x22d0 net/socket.c:2710 __sys_recvmmsg net/socket.c:2789 [inline] __do_sys_recvmmsg net/socket.c:2812 [inline] __se_sys_recvmmsg+0x24a/0x410 net/socket.c:2805 __x64_sys_recvmmsg+0x62/0x80 net/socket.c:2805 do_syscall_64+0x9f/0x140 arch/x86/entry/common.c:48 entry_SYSCALL_64_after_hwframe+0x44/0xa9 RIP: 0033:0x465f69 Code: ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 40 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f43659d6188 EFLAGS: 00000246 ORIG_RAX: 000000000000012b RAX: ffffffffffffffda RBX: 000000000056bf60 RCX: 0000000000465f69 RDX: 0000000000000008 RSI: 0000000020003e40 RDI: 0000000000000003 RBP: 00000000004bfa8f R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000010060 R11: 0000000000000246 R12: 000000000056bf60 R13: 0000000000a9fb1f R14: 00007f43659d6300 R15: 0000000000022000 Local variable ----addr@____sys_recvmsg created at: ____sys_recvmsg+0x168/0xd50 net/socket.c:2550 ____sys_recvmsg+0x168/0xd50 net/socket.c:2550 Bytes 2-3 of 12 are uninitialized Memory access of size 12 starts at ffff88817c627b40 Data copied to user address 0000000020000140 Fixes: bdabad3e363d ("net: Add Qualcomm IPC router") Signed-off-by: Eric Dumazet <edumazet@google.com> Cc: Courtney Cavin <courtney.cavin@sonymobile.com> Reported-by: syzbot <syzkaller@googlegroups.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: MagickExport Image *WaveImage(const Image *image,const double amplitude, const double wave_length,const PixelInterpolateMethod method, ExceptionInfo *exception) { #define WaveImageTag "Wave/Image" CacheView *canvas_image_view, *wave_view; float *sine_map; Image *canvas_image, *wave_image; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; /* Initialize wave image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); if ((canvas_image->alpha_trait == UndefinedPixelTrait) && (canvas_image->background_color.alpha != OpaqueAlpha)) (void) SetImageAlpha(canvas_image,OpaqueAlpha,exception); wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t) (canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception); if (wave_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); wave_image=DestroyImage(wave_image); return((Image *) NULL); } /* Allocate sine map. */ sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns, sizeof(*sine_map)); if (sine_map == (float *) NULL) { canvas_image=DestroyImage(canvas_image); wave_image=DestroyImage(wave_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) wave_image->columns; i++) sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double) ((2.0*MagickPI*i)/wave_length)); /* Wave image. */ status=MagickTrue; progress=0; canvas_image_view=AcquireVirtualCacheView(canvas_image,exception); wave_view=AcquireAuthenticCacheView(wave_image,exception); (void) SetCacheViewVirtualPixelMethod(canvas_image_view, BackgroundVirtualPixelMethod); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(canvas_image,wave_image,wave_image->rows,1) #endif for (y=0; y < (ssize_t) wave_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) wave_image->columns; x++) { status=InterpolatePixelChannels(canvas_image,canvas_image_view, wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception); if (status == MagickFalse) break; p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(wave_image); } if (SyncCacheViewAuthenticPixels(wave_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(canvas_image,WaveImageTag,progress, canvas_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } wave_view=DestroyCacheView(wave_view); canvas_image_view=DestroyCacheView(canvas_image_view); canvas_image=DestroyImage(canvas_image); sine_map=(float *) RelinquishMagickMemory(sine_map); if (status == MagickFalse) wave_image=DestroyImage(wave_image); return(wave_image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/3296'</s>
<s>[INST] Given the following code containing errors, provide 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 TransformSignature(SignatureInfo *signature_info) { #define Ch(x,y,z) (((x) & (y)) ^ (~(x) & (z))) #define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) #define RotateRight(x,n) (Trunc32(((x) >> n) | ((x) << (32-n)))) #define Sigma0(x) (RotateRight(x,7) ^ RotateRight(x,18) ^ Trunc32((x) >> 3)) #define Sigma1(x) (RotateRight(x,17) ^ RotateRight(x,19) ^ Trunc32((x) >> 10)) #define Suma0(x) (RotateRight(x,2) ^ RotateRight(x,13) ^ RotateRight(x,22)) #define Suma1(x) (RotateRight(x,6) ^ RotateRight(x,11) ^ RotateRight(x,25)) #define Trunc32(x) ((unsigned int) ((x) & 0xffffffffU)) ssize_t i; unsigned char *p; ssize_t j; static const unsigned int K[64] = { 0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU, 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U, 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U, 0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U, 0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU, 0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU, 0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, 0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U, 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U, 0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U, 0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U, 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U, 0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, 0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U, 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U, 0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U }; /* 32-bit fractional part of the cube root of the first 64 primes */ unsigned int A, B, C, D, E, F, G, H, shift, T, T1, T2, W[64]; shift=32; p=GetStringInfoDatum(signature_info->message); if (signature_info->lsb_first == MagickFalse) { DisableMSCWarning(4127) if (sizeof(unsigned int) <= 4) RestoreMSCWarning for (i=0; i < 16; i++) { T=(*((unsigned int *) p)); p+=4; W[i]=Trunc32(T); } else for (i=0; i < 16; i+=2) { T=(*((unsigned int *) p)); p+=8; W[i]=Trunc32(T >> shift); W[i+1]=Trunc32(T); } } else DisableMSCWarning(4127) if (sizeof(unsigned int) <= 4) RestoreMSCWarning for (i=0; i < 16; i++) { T=(*((unsigned int *) p)); p+=4; W[i]=((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); } else for (i=0; i < 16; i+=2) { T=(*((unsigned int *) p)); p+=8; W[i]=((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); T>>=shift; W[i+1]=((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); } /* Copy accumulator to registers. */ A=signature_info->accumulator[0]; B=signature_info->accumulator[1]; C=signature_info->accumulator[2]; D=signature_info->accumulator[3]; E=signature_info->accumulator[4]; F=signature_info->accumulator[5]; G=signature_info->accumulator[6]; H=signature_info->accumulator[7]; for (i=16; i < 64; i++) W[i]=Trunc32(Sigma1(W[i-2])+W[i-7]+Sigma0(W[i-15])+W[i-16]); for (j=0; j < 64; j++) { T1=Trunc32(H+Suma1(E)+Ch(E,F,G)+K[j]+W[j]); T2=Trunc32(Suma0(A)+Maj(A,B,C)); H=G; G=F; F=E; E=Trunc32(D+T1); D=C; C=B; B=A; A=Trunc32(T1+T2); } /* Add registers back to accumulator. */ signature_info->accumulator[0]=Trunc32(signature_info->accumulator[0]+A); signature_info->accumulator[1]=Trunc32(signature_info->accumulator[1]+B); signature_info->accumulator[2]=Trunc32(signature_info->accumulator[2]+C); signature_info->accumulator[3]=Trunc32(signature_info->accumulator[3]+D); signature_info->accumulator[4]=Trunc32(signature_info->accumulator[4]+E); signature_info->accumulator[5]=Trunc32(signature_info->accumulator[5]+F); signature_info->accumulator[6]=Trunc32(signature_info->accumulator[6]+G); signature_info->accumulator[7]=Trunc32(signature_info->accumulator[7]+H); /* Reset working registers. */ A=0; B=0; C=0; D=0; E=0; F=0; G=0; H=0; T=0; T1=0; T2=0; (void) memset(W,0,sizeof(W)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'possible divide by zero + clear buffers'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: virtual void seekg (Int64 pos) { if( pos < 0 ) { THROW (IEX_NAMESPACE::InputExc, "internal error: seek to " << pos << " requested"); } current = base + pos; if( current < base || current > end) { THROW (IEX_NAMESPACE::InputExc, "Out of range seek requested\n"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Handle xsampling and bad seekg() calls in exrcheck (#872) * fix exrcheck xsampling!=1 Signed-off-by: Peter Hillman <peterh@wetafx.co.nz> * fix handling bad seekg() calls in exrcheck Signed-off-by: Peter Hillman <peterh@wetafx.co.nz> * fix deeptile detection in multipart files Signed-off-by: Peter Hillman <peterh@wetafx.co.nz>'</s>
<s>[INST] Given the following code containing errors, provide 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 PackLinuxElf64::canUnpack() { if (super::canUnpack()) { return true; } if (Elf64_Ehdr::ET_DYN==get_te16(&ehdri.e_type)) { PackLinuxElf64help1(fi); Elf64_Phdr const *phdr = phdri, *last_LOAD = nullptr; for (unsigned j = 0; j < e_phnum; ++phdr, ++j) if (Elf64_Phdr::PT_LOAD==get_te32(&phdr->p_type)) { last_LOAD = phdr; } if (!last_LOAD) return false; off_t offset = get_te64(&last_LOAD->p_offset); unsigned filesz = get_te64(&last_LOAD->p_filesz); fi->seek(filesz+offset, SEEK_SET); MemBuffer buf(32 + sizeof(overlay_offset)); fi->readx(buf, buf.getSize()); return PackUnix::find_overlay_offset(buf); } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-415'], 'message': 'PackLinuxElf::canUnpack must checkEhdr() for ELF input https://github.com/upx/upx/issues/485 modified: p_lx_elf.cpp'</s>
<s>[INST] Given the following code containing errors, provide 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 posix_acl *fuse_get_acl(struct inode *inode, int type) { struct fuse_conn *fc = get_fuse_conn(inode); int size; const char *name; void *value = NULL; struct posix_acl *acl; if (!fc->posix_acl || fc->no_getxattr) return NULL; if (type == ACL_TYPE_ACCESS) name = XATTR_NAME_POSIX_ACL_ACCESS; else if (type == ACL_TYPE_DEFAULT) name = XATTR_NAME_POSIX_ACL_DEFAULT; else return ERR_PTR(-EOPNOTSUPP); value = kmalloc(PAGE_SIZE, GFP_KERNEL); if (!value) return ERR_PTR(-ENOMEM); size = fuse_getxattr(inode, name, value, PAGE_SIZE); if (size > 0) acl = posix_acl_from_xattr(fc->user_ns, value, size); else if ((size == 0) || (size == -ENODATA) || (size == -EOPNOTSUPP && fc->no_getxattr)) acl = NULL; else if (size == -ERANGE) acl = ERR_PTR(-E2BIG); else acl = ERR_PTR(size); kfree(value); return acl; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-459'], 'message': 'fuse: fix bad inode Jan Kara's analysis of the syzbot report (edited): The reproducer opens a directory on FUSE filesystem, it then attaches dnotify mark to the open directory. After that a fuse_do_getattr() call finds that attributes returned by the server are inconsistent, and calls make_bad_inode() which, among other things does: inode->i_mode = S_IFREG; This then confuses dnotify which doesn't tear down its structures properly and eventually crashes. Avoid calling make_bad_inode() on a live inode: switch to a private flag on the fuse inode. Also add the test to ops which the bad_inode_ops would have caught. This bug goes back to the initial merge of fuse in 2.6.14... Reported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com Signed-off-by: Miklos Szeredi <mszeredi@redhat.com> Tested-by: Jan Kara <jack@suse.cz> Cc: <stable@vger.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 ssize_t fuse_file_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *file = iocb->ki_filp; struct fuse_file *ff = file->private_data; struct inode *inode = file_inode(file); if (is_bad_inode(inode)) return -EIO; if (FUSE_IS_DAX(inode)) return fuse_dax_write_iter(iocb, from); if (!(ff->open_flags & FOPEN_DIRECT_IO)) return fuse_cache_write_iter(iocb, from); else return fuse_direct_write_iter(iocb, from); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-459'], 'message': 'fuse: fix bad inode Jan Kara's analysis of the syzbot report (edited): The reproducer opens a directory on FUSE filesystem, it then attaches dnotify mark to the open directory. After that a fuse_do_getattr() call finds that attributes returned by the server are inconsistent, and calls make_bad_inode() which, among other things does: inode->i_mode = S_IFREG; This then confuses dnotify which doesn't tear down its structures properly and eventually crashes. Avoid calling make_bad_inode() on a live inode: switch to a private flag on the fuse inode. Also add the test to ops which the bad_inode_ops would have caught. This bug goes back to the initial merge of fuse in 2.6.14... Reported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com Signed-off-by: Miklos Szeredi <mszeredi@redhat.com> Tested-by: Jan Kara <jack@suse.cz> Cc: <stable@vger.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 int fuse_unlink(struct inode *dir, struct dentry *entry) { int err; struct fuse_mount *fm = get_fuse_mount(dir); FUSE_ARGS(args); args.opcode = FUSE_UNLINK; args.nodeid = get_node_id(dir); args.in_numargs = 1; args.in_args[0].size = entry->d_name.len + 1; args.in_args[0].value = entry->d_name.name; err = fuse_simple_request(fm, &args); if (!err) { struct inode *inode = d_inode(entry); struct fuse_inode *fi = get_fuse_inode(inode); spin_lock(&fi->lock); fi->attr_version = atomic64_inc_return(&fm->fc->attr_version); /* * If i_nlink == 0 then unlink doesn't make sense, yet this can * happen if userspace filesystem is careless. It would be * difficult to enforce correct nlink usage so just ignore this * condition here */ if (inode->i_nlink > 0) drop_nlink(inode); spin_unlock(&fi->lock); fuse_invalidate_attr(inode); fuse_dir_changed(dir); fuse_invalidate_entry_cache(entry); fuse_update_ctime(inode); } else if (err == -EINTR) fuse_invalidate_entry(entry); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-459'], 'message': 'fuse: fix bad inode Jan Kara's analysis of the syzbot report (edited): The reproducer opens a directory on FUSE filesystem, it then attaches dnotify mark to the open directory. After that a fuse_do_getattr() call finds that attributes returned by the server are inconsistent, and calls make_bad_inode() which, among other things does: inode->i_mode = S_IFREG; This then confuses dnotify which doesn't tear down its structures properly and eventually crashes. Avoid calling make_bad_inode() on a live inode: switch to a private flag on the fuse inode. Also add the test to ops which the bad_inode_ops would have caught. This bug goes back to the initial merge of fuse in 2.6.14... Reported-by: syzbot+f427adf9324b92652ccc@syzkaller.appspotmail.com Signed-off-by: Miklos Szeredi <mszeredi@redhat.com> Tested-by: Jan Kara <jack@suse.cz> Cc: <stable@vger.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: BnGeneratePrimeForRSA( bigNum prime, // IN/OUT: points to the BN that will get the // random value UINT32 bits, // IN: number of bits to get UINT32 exponent, // IN: the exponent RAND_STATE *rand // IN: the random state ) { BOOL found = FALSE; // // Make sure that the prime is large enough pAssert(prime->allocated >= BITS_TO_CRYPT_WORDS(bits)); // Only try to handle specific sizes of keys in order to save overhead pAssert((bits % 32) == 0); prime->size = BITS_TO_CRYPT_WORDS(bits); while(!found) { // The change below is to make sure that all keys that are generated from the same // seed value will be the same regardless of the endianess or word size of the CPU. // DRBG_Generate(rand, (BYTE *)prime->d, (UINT16)BITS_TO_BYTES(bits));// old // if(g_inFailureMode) // old // libtpms changed begin switch (DRBG_GetSeedCompatLevel(rand)) { case SEED_COMPAT_LEVEL_ORIGINAL: DRBG_Generate(rand, (BYTE *)prime->d, (UINT16)BITS_TO_BYTES(bits)); if (g_inFailureMode) return TPM_RC_FAILURE; break; /* case SEED_COMPAT_LEVEL_LAST: */ case SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX: if(!BnGetRandomBits(prime, bits, rand)) // new return TPM_RC_FAILURE; break; default: FAIL(FATAL_ERROR_INTERNAL); } RsaAdjustPrimeCandidate(prime, DRBG_GetSeedCompatLevel(rand)); // libtpms changed end found = RsaCheckPrime(prime, exponent, rand) == TPM_RC_SUCCESS; } return TPM_RC_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-331'], 'message': 'tpm2: Activate SEED_COMPAT_LEVEL_RSA_PRIME_ADJUST_FIX Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ConnectionManagerImpl::ActiveStream::decodeHeaders(RequestHeaderMapPtr&& headers, bool end_stream) { ScopeTrackerScopeState scope(this, connection_manager_.read_callbacks_->connection().dispatcher()); request_headers_ = std::move(headers); filter_manager_.requestHeadersInitialized(); if (request_header_timer_ != nullptr) { request_header_timer_->disableTimer(); request_header_timer_.reset(); } Upstream::HostDescriptionConstSharedPtr upstream_host = connection_manager_.read_callbacks_->upstreamHost(); if (upstream_host != nullptr) { Upstream::ClusterRequestResponseSizeStatsOptRef req_resp_stats = upstream_host->cluster().requestResponseSizeStats(); if (req_resp_stats.has_value()) { req_resp_stats->get().upstream_rq_headers_size_.recordValue(request_headers_->byteSize()); } } // Both saw_connection_close_ and is_head_request_ affect local replies: set // them as early as possible. const Protocol protocol = connection_manager_.codec_->protocol(); state_.saw_connection_close_ = HeaderUtility::shouldCloseConnection(protocol, *request_headers_); // We need to snap snapped_route_config_ here as it's used in mutateRequestHeaders later. if (connection_manager_.config_.isRoutable()) { if (connection_manager_.config_.routeConfigProvider() != nullptr) { snapped_route_config_ = connection_manager_.config_.routeConfigProvider()->config(); } else if (connection_manager_.config_.scopedRouteConfigProvider() != nullptr) { snapped_scoped_routes_config_ = connection_manager_.config_.scopedRouteConfigProvider()->config<Router::ScopedConfig>(); snapScopedRouteConfig(); } } else { snapped_route_config_ = connection_manager_.config_.routeConfigProvider()->config(); } ENVOY_STREAM_LOG(debug, "request headers complete (end_stream={}):\n{}", *this, end_stream, *request_headers_); // We end the decode here only if the request is header only. If we convert the request to a // header only, the stream will be marked as done once a subsequent decodeData/decodeTrailers is // called with end_stream=true. filter_manager_.maybeEndDecode(end_stream); // Drop new requests when overloaded as soon as we have decoded the headers. if (connection_manager_.random_generator_.bernoulli( connection_manager_.overload_stop_accepting_requests_ref_.value())) { // In this one special case, do not create the filter chain. If there is a risk of memory // overload it is more important to avoid unnecessary allocation than to create the filters. filter_manager_.skipFilterChainCreation(); connection_manager_.stats_.named_.downstream_rq_overload_close_.inc(); sendLocalReply(Grpc::Common::isGrpcRequestHeaders(*request_headers_), Http::Code::ServiceUnavailable, "envoy overloaded", nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().Overload); return; } if (!connection_manager_.config_.proxy100Continue() && request_headers_->Expect() && request_headers_->Expect()->value() == Headers::get().ExpectValues._100Continue.c_str()) { // Note in the case Envoy is handling 100-Continue complexity, it skips the filter chain // and sends the 100-Continue directly to the encoder. chargeStats(continueHeader()); response_encoder_->encode100ContinueHeaders(continueHeader()); // Remove the Expect header so it won't be handled again upstream. request_headers_->removeExpect(); } connection_manager_.user_agent_.initializeFromHeaders(*request_headers_, connection_manager_.stats_.prefixStatName(), connection_manager_.stats_.scope_); // Make sure we are getting a codec version we support. if (protocol == Protocol::Http10) { // Assume this is HTTP/1.0. This is fine for HTTP/0.9 but this code will also affect any // requests with non-standard version numbers (0.9, 1.3), basically anything which is not // HTTP/1.1. // // The protocol may have shifted in the HTTP/1.0 case so reset it. filter_manager_.streamInfo().protocol(protocol); if (!connection_manager_.config_.http1Settings().accept_http_10_) { // Send "Upgrade Required" if HTTP/1.0 support is not explicitly configured on. sendLocalReply(false, Code::UpgradeRequired, "", nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().LowVersion); return; } if (!request_headers_->Host() && !connection_manager_.config_.http1Settings().default_host_for_http_10_.empty()) { // Add a default host if configured to do so. request_headers_->setHost( connection_manager_.config_.http1Settings().default_host_for_http_10_); } } if (!request_headers_->Host()) { // Require host header. For HTTP/1.1 Host has already been translated to :authority. sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::BadRequest, "", nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().MissingHost); return; } // Verify header sanity checks which should have been performed by the codec. ASSERT(HeaderUtility::requestHeadersValid(*request_headers_).has_value() == false); // Check for the existence of the :path header for non-CONNECT requests, or present-but-empty // :path header for CONNECT requests. We expect the codec to have broken the path into pieces if // applicable. NOTE: Currently the HTTP/1.1 codec only does this when the allow_absolute_url flag // is enabled on the HCM. if ((!HeaderUtility::isConnect(*request_headers_) || request_headers_->Path()) && request_headers_->getPathValue().empty()) { sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::NotFound, "", nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().MissingPath); return; } // Currently we only support relative paths at the application layer. if (!request_headers_->getPathValue().empty() && request_headers_->getPathValue()[0] != '/') { connection_manager_.stats_.named_.downstream_rq_non_relative_path_.inc(); sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::NotFound, "", nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().AbsolutePath); return; } // Path sanitization should happen before any path access other than the above sanity check. if (!ConnectionManagerUtility::maybeNormalizePath(*request_headers_, connection_manager_.config_)) { sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::BadRequest, "", nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().PathNormalizationFailed); return; } auto optional_port = ConnectionManagerUtility::maybeNormalizeHost( *request_headers_, connection_manager_.config_, localPort()); if (optional_port.has_value() && requestWasConnect(request_headers_, connection_manager_.codec_->protocol())) { filter_manager_.streamInfo().filterState()->setData( Router::OriginalConnectPort::key(), std::make_unique<Router::OriginalConnectPort>(optional_port.value()), StreamInfo::FilterState::StateType::ReadOnly, StreamInfo::FilterState::LifeSpan::Request); } if (!state_.is_internally_created_) { // Only sanitize headers on first pass. // Modify the downstream remote address depending on configuration and headers. filter_manager_.setDownstreamRemoteAddress(ConnectionManagerUtility::mutateRequestHeaders( *request_headers_, connection_manager_.read_callbacks_->connection(), connection_manager_.config_, *snapped_route_config_, connection_manager_.local_info_)); } ASSERT(filter_manager_.streamInfo().downstreamAddressProvider().remoteAddress() != nullptr); ASSERT(!cached_route_); refreshCachedRoute(); if (!state_.is_internally_created_) { // Only mutate tracing headers on first pass. filter_manager_.streamInfo().setTraceReason( ConnectionManagerUtility::mutateTracingRequestHeader( *request_headers_, connection_manager_.runtime_, connection_manager_.config_, cached_route_.value().get())); } filter_manager_.streamInfo().setRequestHeaders(*request_headers_); const bool upgrade_rejected = filter_manager_.createFilterChain() == false; // TODO if there are no filters when starting a filter iteration, the connection manager // should return 404. The current returns no response if there is no router filter. if (hasCachedRoute()) { // Do not allow upgrades if the route does not support it. if (upgrade_rejected) { // While downstream servers should not send upgrade payload without the upgrade being // accepted, err on the side of caution and refuse to process any further requests on this // connection, to avoid a class of HTTP/1.1 smuggling bugs where Upgrade or CONNECT payload // contains a smuggled HTTP request. state_.saw_connection_close_ = true; connection_manager_.stats_.named_.downstream_rq_ws_on_non_ws_route_.inc(); sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::Forbidden, "", nullptr, absl::nullopt, StreamInfo::ResponseCodeDetails::get().UpgradeFailed); return; } // Allow non websocket requests to go through websocket enabled routes. } if (hasCachedRoute()) { const Router::RouteEntry* route_entry = cached_route_.value()->routeEntry(); if (route_entry != nullptr && route_entry->idleTimeout()) { // TODO(mattklein123): Technically if the cached route changes, we should also see if the // route idle timeout has changed and update the value. idle_timeout_ms_ = route_entry->idleTimeout().value(); response_encoder_->getStream().setFlushTimeout(idle_timeout_ms_); if (idle_timeout_ms_.count()) { // If we have a route-level idle timeout but no global stream idle timeout, create a timer. if (stream_idle_timer_ == nullptr) { stream_idle_timer_ = connection_manager_.read_callbacks_->connection().dispatcher().createScaledTimer( Event::ScaledTimerType::HttpDownstreamIdleStreamTimeout, [this]() -> void { onIdleTimeout(); }); } } else if (stream_idle_timer_ != nullptr) { // If we had a global stream idle timeout but the route-level idle timeout is set to zero // (to override), we disable the idle timer. stream_idle_timer_->disableTimer(); stream_idle_timer_ = nullptr; } } } // Check if tracing is enabled at all. if (connection_manager_.config_.tracingConfig()) { traceRequest(); } filter_manager_.decodeHeaders(*request_headers_, end_stream); // Reset it here for both global and overridden cases. resetIdleTimer(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Implement handling of escaped slash characters in URL path Fixes: CVE-2021-29492 Signed-off-by: Yan Avlasov <yavlasov@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: sync_create_state_control(Slapi_Entry *e, LDAPControl **ctrlp, int type, Sync_Cookie *cookie, PRBool openldap_compat) { int rc; BerElement *ber; struct berval *bvp; char *uuid; Slapi_Attr *attr; Slapi_Value *val; if (type == LDAP_SYNC_NONE || ctrlp == NULL || (ber = der_alloc()) == NULL) { return (LDAP_OPERATIONS_ERROR); } *ctrlp = NULL; if (openldap_compat) { slapi_entry_attr_find(e, SLAPI_ATTR_ENTRYUUID, &attr); if (!attr) { /* * We can't proceed from here. We are in openldap mode, but some entries don't * have their UUID. This means that the tree could be corrupted on the openldap * server, so we have to stop now. */ slapi_log_err(SLAPI_LOG_ERR, SYNC_PLUGIN_SUBSYSTEM, "sync_create_state_control - Some entries are missing entryUUID. Unable to proceed. You may need to re-run the entryuuid fixup\n"); return (LDAP_OPERATIONS_ERROR); } slapi_attr_first_value(attr, &val); uuid = sync_entryuuid2uuid(slapi_value_get_string(val)); } else { slapi_entry_attr_find(e, SLAPI_ATTR_UNIQUEID, &attr); slapi_attr_first_value(attr, &val); uuid = sync_nsuniqueid2uuid(slapi_value_get_string(val)); } if ((rc = ber_printf(ber, "{eo", type, uuid, 16)) != -1) { if (cookie) { char *cookiestr = sync_cookie2str(cookie); rc = ber_printf(ber, "s}", cookiestr); slapi_ch_free((void **)&cookiestr); } else { rc = ber_printf(ber, "}"); } } if (rc != -1) { rc = ber_flatten(ber, &bvp); } ber_free(ber, 1); slapi_ch_free((void **)&uuid); if (rc == -1) { return (LDAP_OPERATIONS_ERROR); } *ctrlp = (LDAPControl *)slapi_ch_malloc(sizeof(LDAPControl)); (*ctrlp)->ldctl_iscritical = 0; (*ctrlp)->ldctl_oid = slapi_ch_strdup(LDAP_CONTROL_SYNC_STATE); (*ctrlp)->ldctl_value = *bvp; /* struct copy */ bvp->bv_val = NULL; ber_bvfree(bvp); return (LDAP_SUCCESS); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Issue 4711 - SIGSEV with sync_repl (#4738) Bug description: sync_repl sends back entries identified with a unique identifier that is 'nsuniqueid'. If 'nsuniqueid' is missing, then it may crash Fix description: Check a nsuniqueid is available else returns OP_ERR relates: https://github.com/389ds/389-ds-base/issues/4711 Reviewed by: Pierre Rogier, James Chapman, William Brown (Thanks!) Platforms tested: F33'</s>
<s>[INST] Given the following code containing errors, provide 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 sldns_str2wire_dname_buf_origin(const char* str, uint8_t* buf, size_t* len, uint8_t* origin, size_t origin_len) { size_t dlen = *len; int rel = 0; int s = sldns_str2wire_dname_buf_rel(str, buf, &dlen, &rel); if(s) return s; if(rel && origin && dlen > 0) { if(dlen + origin_len - 1 > LDNS_MAX_DOMAINLEN) return RET_ERR(LDNS_WIREPARSE_ERR_DOMAINNAME_OVERFLOW, LDNS_MAX_DOMAINLEN); if(dlen + origin_len - 1 > *len) return RET_ERR(LDNS_WIREPARSE_ERR_BUFFER_TOO_SMALL, *len); memmove(buf+dlen-1, origin, origin_len); *len = dlen + origin_len - 1; } else *len = dlen; return LDNS_WIREPARSE_ERR_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': '- Fix Integer Overflow to Buffer Overflow in sldns_str2wire_dname_buf_origin(), reported by X41 D-Sec.'</s>
<s>[INST] Given the following code containing errors, provide 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 usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p, uint8_t ep) { struct usb_redir_bulk_packet_header bulk_packet; size_t size = usb_packet_size(p); const int maxp = dev->endpoint[EP2I(ep)].max_packet_size; if (usbredir_already_in_flight(dev, p->id)) { p->status = USB_RET_ASYNC; return; } if (dev->endpoint[EP2I(ep)].bulk_receiving_enabled) { if (size != 0 && (size % maxp) == 0) { usbredir_handle_buffered_bulk_in_data(dev, p, ep); return; } WARNING("bulk recv invalid size %zd ep %02x, disabling\n", size, ep); assert(dev->endpoint[EP2I(ep)].pending_async_packet == NULL); usbredir_stop_bulk_receiving(dev, ep); dev->endpoint[EP2I(ep)].bulk_receiving_enabled = 0; } DPRINTF("bulk-out ep %02X stream %u len %zd id %"PRIu64"\n", ep, p->stream, size, p->id); bulk_packet.endpoint = ep; bulk_packet.length = size; bulk_packet.stream_id = p->stream; bulk_packet.length_high = size >> 16; assert(bulk_packet.length_high == 0 || usbredirparser_peer_has_cap(dev->parser, usb_redir_cap_32bits_bulk_length)); if (ep & USB_DIR_IN || size == 0) { usbredirparser_send_bulk_packet(dev->parser, p->id, &bulk_packet, NULL, 0); } else { uint8_t buf[size]; usb_packet_copy(p, buf, size); usbredir_log_data(dev, "bulk data out:", buf, size); usbredirparser_send_bulk_packet(dev->parser, p->id, &bulk_packet, buf, size); } usbredirparser_do_write(dev->parser); p->status = USB_RET_ASYNC; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'usb/redir: avoid dynamic stack allocation (CVE-2021-3527) Use autofree heap allocation instead. Fixes: 4f4321c11ff ("usb: use iovecs in USBPacket") Reviewed-by: Philippe Mathieu-Daudé <philmd@redhat.com> Signed-off-by: Gerd Hoffmann <kraxel@redhat.com> Tested-by: Philippe Mathieu-Daudé <philmd@redhat.com> Message-Id: <20210503132915.2335822-3-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: TEST(QueryProjectionTest, InvalidPositionalOperatorProjections) { assertInvalidProjection("{}", "{'a.$': 1}"); assertInvalidProjection("{a: 1}", "{'b.$': 1}"); assertInvalidProjection("{a: 1}", "{'a.$': 0}"); assertInvalidProjection("{a: 1}", "{'a.$.d.$': 1}"); assertInvalidProjection("{a: 1}", "{'a.$.$': 1}"); assertInvalidProjection("{a: 1, b: 1, c: 1}", "{'abc.$': 1}"); assertInvalidProjection("{$or: [{a: 1}, {$or: [{b: 1}, {c: 1}]}]}", "{'d.$': 1}"); assertInvalidProjection("{a: [1, 2, 3]}", "{'.$': 1}"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-732'], 'message': 'SERVER-53929 Add stricter parser checks around positional projection'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8 *buf, Py_ssize_t bytes) { UINT8 *ptr; int framesize; int c, chunks, advance; int l, lines; int i, j, x = 0, y, ymax; /* If not even the chunk size is present, we'd better leave */ if (bytes < 4) { return 0; } /* We don't decode anything unless we have a full chunk in the input buffer */ ptr = buf; framesize = I32(ptr); if (framesize < I32(ptr)) { return 0; } /* Make sure this is a frame chunk. The Python driver takes case of other chunk types. */ if (bytes < 8) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } if (I16(ptr + 4) != 0xF1FA) { state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } chunks = I16(ptr + 6); ptr += 16; bytes -= 16; /* Process subchunks */ for (c = 0; c < chunks; c++) { UINT8 *data; if (bytes < 10) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } data = ptr + 6; switch (I16(ptr + 4)) { case 4: case 11: /* FLI COLOR chunk */ break; /* ignored; handled by Python code */ case 7: /* FLI SS2 chunk (word delta) */ /* OOB ok, we've got 4 bytes min on entry */ lines = I16(data); data += 2; for (l = y = 0; l < lines && y < state->ysize; l++, y++) { UINT8 *local_buf = (UINT8 *)im->image[y]; int p, packets; ERR_IF_DATA_OOB(2) packets = I16(data); data += 2; while (packets & 0x8000) { /* flag word */ if (packets & 0x4000) { y += 65536 - packets; /* skip lines */ if (y >= state->ysize) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } local_buf = (UINT8 *)im->image[y]; } else { /* store last byte (used if line width is odd) */ local_buf[state->xsize - 1] = (UINT8)packets; } ERR_IF_DATA_OOB(2) packets = I16(data); data += 2; } for (p = x = 0; p < packets; p++) { ERR_IF_DATA_OOB(2) x += data[0]; /* pixel skip */ if (data[1] >= 128) { ERR_IF_DATA_OOB(4) i = 256 - data[1]; /* run */ if (x + i + i > state->xsize) { break; } for (j = 0; j < i; j++) { local_buf[x++] = data[2]; local_buf[x++] = data[3]; } data += 2 + 2; } else { i = 2 * (int)data[1]; /* chunk */ if (x + i > state->xsize) { break; } ERR_IF_DATA_OOB(2 + i) memcpy(local_buf + x, data + 2, i); data += 2 + i; x += i; } } if (p < packets) { break; /* didn't process all packets */ } } if (l < lines) { /* didn't process all lines */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } break; case 12: /* FLI LC chunk (byte delta) */ /* OOB Check ok, we have 4 bytes min here */ y = I16(data); ymax = y + I16(data + 2); data += 4; for (; y < ymax && y < state->ysize; y++) { UINT8 *out = (UINT8 *)im->image[y]; ERR_IF_DATA_OOB(1) int p, packets = *data++; for (p = x = 0; p < packets; p++, x += i) { ERR_IF_DATA_OOB(2) x += data[0]; /* skip pixels */ if (data[1] & 0x80) { i = 256 - data[1]; /* run */ if (x + i > state->xsize) { break; } ERR_IF_DATA_OOB(3) memset(out + x, data[2], i); data += 3; } else { i = data[1]; /* chunk */ if (x + i > state->xsize) { break; } ERR_IF_DATA_OOB(2 + i) memcpy(out + x, data + 2, i); data += i + 2; } } if (p < packets) { break; /* didn't process all packets */ } } if (y < ymax) { /* didn't process all lines */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } break; case 13: /* FLI BLACK chunk */ for (y = 0; y < state->ysize; y++) { memset(im->image[y], 0, state->xsize); } break; case 15: /* FLI BRUN chunk */ /* OOB, ok, we've got 4 bytes min on entry */ for (y = 0; y < state->ysize; y++) { UINT8 *out = (UINT8 *)im->image[y]; data += 1; /* ignore packetcount byte */ for (x = 0; x < state->xsize; x += i) { ERR_IF_DATA_OOB(2) if (data[0] & 0x80) { i = 256 - data[0]; if (x + i > state->xsize) { break; /* safety first */ } ERR_IF_DATA_OOB(i + 1) memcpy(out + x, data + 1, i); data += i + 1; } else { i = data[0]; if (x + i > state->xsize) { break; /* safety first */ } memset(out + x, data[1], i); data += 2; } } if (x != state->xsize) { /* didn't unpack whole line */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } } break; case 16: /* COPY chunk */ if (state->xsize > bytes / state->ysize) { /* not enough data for frame */ return ptr - buf; /* bytes consumed */ } for (y = 0; y < state->ysize; y++) { UINT8 *local_buf = (UINT8 *)im->image[y]; memcpy(local_buf, data, state->xsize); data += state->xsize; } break; case 18: /* PSTAMP chunk */ break; /* ignored */ default: /* unknown chunk */ /* printf("unknown FLI/FLC chunk: %d\n", I16(ptr+4)); */ state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } advance = I32(ptr); if (advance < 0 || advance > bytes) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } ptr += advance; bytes -= advance; } return -1; /* end of frame */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'Fix FLI DOS -- CVE-2021-28676 * FliDecode did not properly check that the block advance was non-zero, potentally leading to an infinite loop on load. * This dates to the PIL Fork * Found with oss-fuzz'</s>
<s>[INST] Given the following code containing errors, provide 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 *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size) { unsigned long cons_pos, prod_pos, new_prod_pos, flags; u32 len, pg_off; struct bpf_ringbuf_hdr *hdr; if (unlikely(size > RINGBUF_MAX_RECORD_SZ)) return NULL; len = round_up(size + BPF_RINGBUF_HDR_SZ, 8); cons_pos = smp_load_acquire(&rb->consumer_pos); if (in_nmi()) { if (!spin_trylock_irqsave(&rb->spinlock, flags)) return NULL; } else { spin_lock_irqsave(&rb->spinlock, flags); } prod_pos = rb->producer_pos; new_prod_pos = prod_pos + len; /* check for out of ringbuf space by ensuring producer position * doesn't advance more than (ringbuf_size - 1) ahead */ if (new_prod_pos - cons_pos > rb->mask) { spin_unlock_irqrestore(&rb->spinlock, flags); return NULL; } hdr = (void *)rb->data + (prod_pos & rb->mask); pg_off = bpf_ringbuf_rec_pg_off(rb, hdr); hdr->len = size | BPF_RINGBUF_BUSY_BIT; hdr->pg_off = pg_off; /* pairs with consumer's smp_load_acquire() */ smp_store_release(&rb->producer_pos, new_prod_pos); spin_unlock_irqrestore(&rb->spinlock, flags); return (void *)hdr + BPF_RINGBUF_HDR_SZ; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'bpf, ringbuf: Deny reserve of buffers larger than ringbuf A BPF program might try to reserve a buffer larger than the ringbuf size. If the consumer pointer is way ahead of the producer, that would be successfully reserved, allowing the BPF program to read or write out of the ringbuf allocated area. Reported-by: Ryota Shiga (Flatt Security) Fixes: 457f44363a88 ("bpf: Implement BPF ring buffer and verifier support for it") Signed-off-by: Thadeu Lima de Souza Cascardo <cascardo@canonical.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Acked-by: Andrii Nakryiko <andrii@kernel.org> Acked-by: Alexei Starovoitov <ast@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 int calipso_doi_remove(u32 doi, struct netlbl_audit *audit_info) { int ret_val; struct calipso_doi *doi_def; struct audit_buffer *audit_buf; spin_lock(&calipso_doi_list_lock); doi_def = calipso_doi_search(doi); if (!doi_def) { spin_unlock(&calipso_doi_list_lock); ret_val = -ENOENT; goto doi_remove_return; } if (!refcount_dec_and_test(&doi_def->refcount)) { spin_unlock(&calipso_doi_list_lock); ret_val = -EBUSY; goto doi_remove_return; } list_del_rcu(&doi_def->list); spin_unlock(&calipso_doi_list_lock); call_rcu(&doi_def->rcu, calipso_doi_free_rcu); ret_val = 0; doi_remove_return: audit_buf = netlbl_audit_start(AUDIT_MAC_CALIPSO_DEL, audit_info); if (audit_buf) { audit_log_format(audit_buf, " calipso_doi=%u res=%u", doi, ret_val == 0 ? 1 : 0); audit_log_end(audit_buf); } return ret_val; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'cipso,calipso: resolve a number of problems with the DOI refcounts The current CIPSO and CALIPSO refcounting scheme for the DOI definitions is a bit flawed in that we: 1. Don't correctly match gets/puts in netlbl_cipsov4_list(). 2. Decrement the refcount on each attempt to remove the DOI from the DOI list, only removing it from the list once the refcount drops to zero. This patch fixes these problems by adding the missing "puts" to netlbl_cipsov4_list() and introduces a more conventional, i.e. not-buggy, refcounting mechanism to the DOI definitions. Upon the addition of a DOI to the DOI list, it is initialized with a refcount of one, removing a DOI from the list removes it from the list and drops the refcount by one; "gets" and "puts" behave as expected with respect to refcounts, increasing and decreasing the DOI's refcount by one. Fixes: b1edeb102397 ("netlabel: Replace protocol/NetLabel linking with refrerence counts") Fixes: d7cce01504a0 ("netlabel: Add support for removing a CALIPSO DOI.") Reported-by: syzbot+9ec037722d2603a9f52e@syzkaller.appspotmail.com Signed-off-by: Paul Moore <paul@paul-moore.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: XSetCommand ( Display *dpy, Window w, char **argv, int argc) { register int i; size_t nbytes; register char *buf, *bp; for (i = 0, nbytes = 0; i < argc; i++) { nbytes += safestrlen(argv[i]) + 1; } if ((bp = buf = Xmalloc(nbytes))) { /* copy arguments into single buffer */ for (i = 0; i < argc; i++) { if (argv[i]) { (void) strcpy(bp, argv[i]); bp += strlen(argv[i]) + 1; } else *bp++ = '\0'; } XChangeProperty (dpy, w, XA_WM_COMMAND, XA_STRING, 8, PropModeReplace, (unsigned char *)buf, nbytes); Xfree(buf); } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Reject string longer than USHRT_MAX before sending them on the wire The X protocol uses CARD16 values to represent the length so this would overflow. CVE-2021-31535 Signed-off-by: Matthieu Herrb <matthieu@herrb.eu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: XQueryExtension( register Display *dpy, _Xconst char *name, int *major_opcode, /* RETURN */ int *first_event, /* RETURN */ int *first_error) /* RETURN */ { xQueryExtensionReply rep; register xQueryExtensionReq *req; LockDisplay(dpy); GetReq(QueryExtension, req); req->nbytes = name ? (CARD16) strlen(name) : 0; req->length += (req->nbytes+(unsigned)3)>>2; _XSend(dpy, name, (long)req->nbytes); (void) _XReply (dpy, (xReply *)&rep, 0, xTrue); *major_opcode = rep.major_opcode; *first_event = rep.first_event; *first_error = rep.first_error; UnlockDisplay(dpy); SyncHandle(); return (rep.present); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Reject string longer than USHRT_MAX before sending them on the wire The X protocol uses CARD16 values to represent the length so this would overflow. CVE-2021-31535 Signed-off-by: Matthieu Herrb <matthieu@herrb.eu>'</s>
<s>[INST] Given the following code containing errors, provide 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 testCacheManager::setUp() { Mem::Init(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Bug 5106: Broken cache manager URL parsing (#788) Use already parsed request-target URL in cache manager and update CacheManager to Tokanizer based URL parse Removing use of sscan() and regex string processing which have proven to be problematic on many levels. Most particularly with regards to tolerance of normally harmless garbage syntax in URLs received. Support for generic URI schemes is added possibly resolving some issues reported with ftp:// URL and manager access via ftp_port sockets. Truly generic support for /squid-internal-mgr/ path prefix is added, fixing some user confusion about its use on cache_object: scheme URLs. TODO: support for single-name parameters and URL #fragments are left to future updates. As is refactoring the QueryParams data storage to avoid SBuf data copying.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Http::Stream::buildRangeHeader(HttpReply *rep) { HttpHeader *hdr = rep ? &rep->header : nullptr; const char *range_err = nullptr; HttpRequest *request = http->request; assert(request->range); /* check if we still want to do ranges */ int64_t roffLimit = request->getRangeOffsetLimit(); auto contentRange = rep ? rep->contentRange() : nullptr; if (!rep) range_err = "no [parse-able] reply"; else if ((rep->sline.status() != Http::scOkay) && (rep->sline.status() != Http::scPartialContent)) range_err = "wrong status code"; else if (rep->sline.status() == Http::scPartialContent) range_err = "too complex response"; // probably contains what the client needs else if (rep->sline.status() != Http::scOkay) range_err = "wrong status code"; else if (hdr->has(Http::HdrType::CONTENT_RANGE)) { Must(!contentRange); // this is a 200, not 206 response range_err = "meaningless response"; // the status code or the header is wrong } else if (rep->content_length < 0) range_err = "unknown length"; else if (rep->content_length != http->memObject()->getReply()->content_length) range_err = "INCONSISTENT length"; /* a bug? */ /* hits only - upstream CachePeer determines correct behaviour on misses, * and client_side_reply determines hits candidates */ else if (http->logType.isTcpHit() && http->request->header.has(Http::HdrType::IF_RANGE) && !clientIfRangeMatch(http, rep)) range_err = "If-Range match failed"; else if (!http->request->range->canonize(rep)) range_err = "canonization failed"; else if (http->request->range->isComplex()) range_err = "too complex range header"; else if (!http->logType.isTcpHit() && http->request->range->offsetLimitExceeded(roffLimit)) range_err = "range outside range_offset_limit"; /* get rid of our range specs on error */ if (range_err) { /* XXX We do this here because we need canonisation etc. However, this current * code will lead to incorrect store offset requests - the store will have the * offset data, but we won't be requesting it. * So, we can either re-request, or generate an error */ http->request->ignoreRange(range_err); } else { /* XXX: TODO: Review, this unconditional set may be wrong. */ rep->sline.set(rep->sline.version, Http::scPartialContent); // web server responded with a valid, but unexpected range. // will (try-to) forward as-is. //TODO: we should cope with multirange request/responses // TODO: review, since rep->content_range is always nil here. bool replyMatchRequest = contentRange != nullptr ? request->range->contains(contentRange->spec) : true; const int spec_count = http->request->range->specs.size(); int64_t actual_clen = -1; debugs(33, 3, "range spec count: " << spec_count << " virgin clen: " << rep->content_length); assert(spec_count > 0); /* append appropriate header(s) */ if (spec_count == 1) { if (!replyMatchRequest) { hdr->putContRange(contentRange); actual_clen = rep->content_length; //http->range_iter.pos = rep->content_range->spec.begin(); (*http->range_iter.pos)->offset = contentRange->spec.offset; (*http->range_iter.pos)->length = contentRange->spec.length; } else { HttpHdrRange::iterator pos = http->request->range->begin(); assert(*pos); /* append Content-Range */ if (!contentRange) { /* No content range, so this was a full object we are * sending parts of. */ httpHeaderAddContRange(hdr, **pos, rep->content_length); } /* set new Content-Length to the actual number of bytes * transmitted in the message-body */ actual_clen = (*pos)->length; } } else { /* multipart! */ /* generate boundary string */ http->range_iter.boundary = http->rangeBoundaryStr(); /* delete old Content-Type, add ours */ hdr->delById(Http::HdrType::CONTENT_TYPE); httpHeaderPutStrf(hdr, Http::HdrType::CONTENT_TYPE, "multipart/byteranges; boundary=\"" SQUIDSTRINGPH "\"", SQUIDSTRINGPRINT(http->range_iter.boundary)); /* Content-Length is not required in multipart responses * but it is always nice to have one */ actual_clen = http->mRangeCLen(); /* http->out needs to start where we want data at */ http->out.offset = http->range_iter.currentSpec()->offset; } /* replace Content-Length header */ assert(actual_clen >= 0); hdr->delById(Http::HdrType::CONTENT_LENGTH); hdr->putInt64(Http::HdrType::CONTENT_LENGTH, actual_clen); debugs(33, 3, "actual content length: " << actual_clen); /* And start the range iter off */ http->range_iter.updateSpec(); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-116'], 'message': 'Handle more Range requests (#790) Also removed some effectively unused code.'</s>
<s>[INST] Given the following code containing errors, provide 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_yin_leaflist(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin, int options, struct unres_schema *unres) { struct ly_ctx *ctx = module->ctx; struct lys_node *retval; struct lys_node_leaflist *llist; struct lyxml_elem *sub, *next; const char *value; char *endptr; unsigned long val; int r, has_type = 0; int c_must = 0, c_ftrs = 0, c_dflt = 0, c_ext = 0; int f_ordr = 0, f_min = 0, f_max = 0; void *reallocated; llist = calloc(1, sizeof *llist); LY_CHECK_ERR_RETURN(!llist, LOGMEM(ctx), NULL); llist->nodetype = LYS_LEAFLIST; llist->prev = (struct lys_node *)llist; retval = (struct lys_node *)llist; if (read_yin_common(module, parent, retval, LYEXT_PAR_NODE, yin, OPT_IDENT | OPT_MODULE | ((options & LYS_PARSE_OPT_CFG_IGNORE) ? OPT_CFG_IGNORE : (options & LYS_PARSE_OPT_CFG_NOINHERIT) ? OPT_CFG_PARSE : OPT_CFG_PARSE | OPT_CFG_INHERIT), unres)) { goto error; } LOGDBG(LY_LDGYIN, "parsing %s statement \"%s\"", yin->name, retval->name); /* insert the node into the schema tree */ if (lys_node_addchild(parent, lys_main_module(module), retval, options)) { goto error; } LY_TREE_FOR_SAFE(yin->child, next, sub) { if (strcmp(sub->ns->value, LY_NSYIN)) { /* extension */ YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, "extensions", "leaf-list", error); c_ext++; continue; } else if (!strcmp(sub->name, "type")) { if (has_type) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } /* HACK for unres */ llist->type.der = (struct lys_tpdf *)sub; llist->type.parent = (struct lys_tpdf *)llist; /* postpone type resolution when if-feature parsing is done since we need * if-feature for check_leafref_features() */ has_type = 1; } else if (!strcmp(sub->name, "units")) { if (llist->units) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } GETVAL(ctx, value, sub, "name"); llist->units = lydict_insert(ctx, value, strlen(value)); if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_UNITS, 0, unres)) { goto error; } } else if (!strcmp(sub->name, "ordered-by")) { if (f_ordr) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } /* just checking the flags in llist is not sufficient, we would * allow multiple ordered-by statements with the "system" value */ f_ordr = 1; if (llist->flags & LYS_CONFIG_R) { /* RFC 6020, 7.7.5 - ignore ordering when the list represents * state data */ lyxml_free(ctx, sub); continue; } GETVAL(ctx, value, sub, "value"); if (!strcmp(value, "user")) { llist->flags |= LYS_USERORDERED; } else if (strcmp(value, "system")) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); goto error; } /* else system is the default value, so we can ignore it */ if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_ORDEREDBY, 0, unres)) { goto error; } } else if (!strcmp(sub->name, "must")) { YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_must, llist->must_size, "musts", "leaf-list", error); c_must++; continue; } else if (!strcmp(sub->name, "if-feature")) { YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ftrs, retval->iffeature_size, "if-features", "leaf-list", error); c_ftrs++; continue; } else if ((module->version >= 2) && !strcmp(sub->name, "default")) { /* read the default's extension instances */ if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_DEFAULT, c_dflt, unres)) { goto error; } YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_dflt, llist->dflt_size, "defaults", "leaf-list", error); c_dflt++; continue; } else if (!strcmp(sub->name, "min-elements")) { if (f_min) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } f_min = 1; GETVAL(ctx, value, sub, "value"); while (isspace(value[0])) { value++; } /* convert it to uint32_t */ errno = 0; endptr = NULL; val = strtoul(value, &endptr, 10); if (*endptr || value[0] == '-' || errno || val > UINT32_MAX) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); goto error; } llist->min = (uint32_t) val; if (llist->max && (llist->min > llist->max)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"min-elements\" is bigger than \"max-elements\"."); goto error; } if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MIN, 0, unres)) { goto error; } } else if (!strcmp(sub->name, "max-elements")) { if (f_max) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } f_max = 1; GETVAL(ctx, value, sub, "value"); while (isspace(value[0])) { value++; } if (!strcmp(value, "unbounded")) { llist->max = 0; } else { /* convert it to uint32_t */ errno = 0; endptr = NULL; val = strtoul(value, &endptr, 10); if (*endptr || value[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); goto error; } llist->max = (uint32_t) val; if (llist->min > llist->max) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"max-elements\" is smaller than \"min-elements\"."); goto error; } } if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MAX, 0, unres)) { goto error; } } else if (!strcmp(sub->name, "when")) { if (llist->when) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } llist->when = read_yin_when(module, sub, unres); if (!llist->when) { goto error; } } else { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name); goto error; } /* do not free sub, it could have been unlinked and stored in unres */ } /* check constraints */ if (!has_type) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, retval, "type", yin->name); goto error; } /* middle part - process nodes with cardinality of 0..n */ if (c_must) { llist->must = calloc(c_must, sizeof *llist->must); LY_CHECK_ERR_GOTO(!llist->must, LOGMEM(ctx), error); } if (c_ftrs) { llist->iffeature = calloc(c_ftrs, sizeof *llist->iffeature); LY_CHECK_ERR_GOTO(!llist->iffeature, LOGMEM(ctx), error); } if (c_dflt) { llist->dflt = calloc(c_dflt, sizeof *llist->dflt); LY_CHECK_ERR_GOTO(!llist->dflt, LOGMEM(ctx), error); } if (c_ext) { /* some extensions may be already present from the substatements */ reallocated = realloc(retval->ext, (c_ext + retval->ext_size) * sizeof *retval->ext); LY_CHECK_ERR_GOTO(!reallocated, LOGMEM(ctx), error); retval->ext = reallocated; /* init memory */ memset(&retval->ext[retval->ext_size], 0, c_ext * sizeof *retval->ext); } LY_TREE_FOR_SAFE(yin->child, next, sub) { if (strcmp(sub->ns->value, LY_NSYIN)) { /* extension */ r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres); if (r) { goto error; } } else if (!strcmp(sub->name, "must")) { r = fill_yin_must(module, sub, &llist->must[llist->must_size], unres); llist->must_size++; if (r) { goto error; } } else if (!strcmp(sub->name, "if-feature")) { r = fill_yin_iffeature(retval, 0, sub, &llist->iffeature[llist->iffeature_size], unres); llist->iffeature_size++; if (r) { goto error; } } else if (!strcmp(sub->name, "default")) { GETVAL(ctx, value, sub, "value"); /* check for duplicity in case of configuration data, * in case of status data duplicities are allowed */ if (llist->flags & LYS_CONFIG_W) { for (r = 0; r < llist->dflt_size; r++) { if (ly_strequal(llist->dflt[r], value, 1)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, "default"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Duplicated default value \"%s\".", value); goto error; } } } llist->dflt[llist->dflt_size++] = lydict_insert(ctx, value, strlen(value)); } } lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size); /* finalize type parsing */ if (unres_schema_add_node(module, unres, &llist->type, UNRES_TYPE_DER, retval) == -1) { llist->type.der = NULL; goto error; } if (llist->dflt_size && llist->min) { LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, retval, "min-elements", "leaf-list"); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement."); goto error; } /* check default value (if not defined, there still could be some restrictions * that need to be checked against a default value from a derived type) */ for (r = 0; r < llist->dflt_size; r++) { if (!(ctx->models.flags & LY_CTX_TRUSTED) && (unres_schema_add_node(module, unres, &llist->type, UNRES_TYPE_DFLT, (struct lys_node *)(&llist->dflt[r])) == -1)) { goto error; } } /* check XPath dependencies */ if (!(ctx->models.flags & LY_CTX_TRUSTED) && (llist->when || llist->must)) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax(retval)) { goto error; } } else { if (unres_schema_add_node(module, unres, retval, UNRES_XPATH, NULL) == -1) { goto error; } } } for (r = 0; r < retval->ext_size; ++r) { /* set flag, which represent LYEXT_OPT_VALID */ if (retval->ext[r]->flags & LYEXT_OPT_VALID) { retval->flags |= LYS_VALID_EXT; break; } } return retval; error: lys_node_free(ctx, retval, NULL, 0); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-252'], 'message': 'yin parser BUGFIX invalid memory access ... in case there were some unresolved extensions. Fixes #1454 Fixes #1455'</s>
<s>[INST] Given the following code containing errors, provide 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_yin_list(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin, int options, struct unres_schema *unres) { struct ly_ctx *ctx = module->ctx; struct lys_node *retval, *node; struct lys_node_list *list; struct lyxml_elem *sub, *next, root, uniq; int r; int c_tpdf = 0, c_must = 0, c_uniq = 0, c_ftrs = 0, c_ext = 0; int f_ordr = 0, f_max = 0, f_min = 0; const char *value; char *auxs; unsigned long val; void *reallocated; /* init */ memset(&root, 0, sizeof root); memset(&uniq, 0, sizeof uniq); list = calloc(1, sizeof *list); LY_CHECK_ERR_RETURN(!list, LOGMEM(ctx), NULL); list->nodetype = LYS_LIST; list->prev = (struct lys_node *)list; retval = (struct lys_node *)list; if (read_yin_common(module, parent, retval, LYEXT_PAR_NODE, yin, OPT_IDENT | OPT_MODULE | ((options & LYS_PARSE_OPT_CFG_IGNORE) ? OPT_CFG_IGNORE : (options & LYS_PARSE_OPT_CFG_NOINHERIT) ? OPT_CFG_PARSE : OPT_CFG_PARSE | OPT_CFG_INHERIT), unres)) { goto error; } LOGDBG(LY_LDGYIN, "parsing %s statement \"%s\"", yin->name, retval->name); /* insert the node into the schema tree */ if (lys_node_addchild(parent, lys_main_module(module), retval, options)) { goto error; } /* process list's specific children */ LY_TREE_FOR_SAFE(yin->child, next, sub) { if (strcmp(sub->ns->value, LY_NSYIN)) { /* extension */ YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, "extensions", "list", error); c_ext++; continue; /* data statements */ } else if (!strcmp(sub->name, "container") || !strcmp(sub->name, "leaf-list") || !strcmp(sub->name, "leaf") || !strcmp(sub->name, "list") || !strcmp(sub->name, "choice") || !strcmp(sub->name, "uses") || !strcmp(sub->name, "grouping") || !strcmp(sub->name, "anyxml") || !strcmp(sub->name, "anydata") || !strcmp(sub->name, "action") || !strcmp(sub->name, "notification")) { lyxml_unlink_elem(ctx, sub, 2); lyxml_add_child(ctx, &root, sub); /* array counters */ } else if (!strcmp(sub->name, "key")) { /* check cardinality 0..1 */ if (list->keys_size) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, list->name); goto error; } /* count the number of keys */ GETVAL(ctx, value, sub, "value"); list->keys_str = lydict_insert(ctx, value, 0); while ((value = strpbrk(value, " \t\n"))) { list->keys_size++; while (isspace(*value)) { value++; } } list->keys_size++; list->keys = calloc(list->keys_size, sizeof *list->keys); LY_CHECK_ERR_GOTO(!list->keys, LOGMEM(ctx), error); if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_KEY, 0, unres)) { goto error; } lyxml_free(ctx, sub); } else if (!strcmp(sub->name, "unique")) { YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_uniq, list->unique_size, "uniques", "list", error); c_uniq++; lyxml_unlink_elem(ctx, sub, 2); lyxml_add_child(ctx, &uniq, sub); } else if (!strcmp(sub->name, "typedef")) { YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_tpdf, list->tpdf_size, "typedefs", "list", error); c_tpdf++; } else if (!strcmp(sub->name, "must")) { YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_must, list->must_size, "musts", "list", error); c_must++; } else if (!strcmp(sub->name, "if-feature")) { YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ftrs, retval->iffeature_size, "if-features", "list", error); c_ftrs++; /* optional stetments */ } else if (!strcmp(sub->name, "ordered-by")) { if (f_ordr) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } /* just checking the flags in llist is not sufficient, we would * allow multiple ordered-by statements with the "system" value */ f_ordr = 1; if (list->flags & LYS_CONFIG_R) { /* RFC 6020, 7.7.5 - ignore ordering when the list represents * state data */ lyxml_free(ctx, sub); continue; } GETVAL(ctx, value, sub, "value"); if (!strcmp(value, "user")) { list->flags |= LYS_USERORDERED; } else if (strcmp(value, "system")) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); goto error; } /* else system is the default value, so we can ignore it */ if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_ORDEREDBY, 0, unres)) { goto error; } lyxml_free(ctx, sub); } else if (!strcmp(sub->name, "min-elements")) { if (f_min) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } f_min = 1; GETVAL(ctx, value, sub, "value"); while (isspace(value[0])) { value++; } /* convert it to uint32_t */ errno = 0; auxs = NULL; val = strtoul(value, &auxs, 10); if (*auxs || value[0] == '-' || errno || val > UINT32_MAX) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); goto error; } list->min = (uint32_t) val; if (list->max && (list->min > list->max)) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"min-elements\" is bigger than \"max-elements\"."); lyxml_free(ctx, sub); goto error; } if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MIN, 0, unres)) { goto error; } lyxml_free(ctx, sub); } else if (!strcmp(sub->name, "max-elements")) { if (f_max) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } f_max = 1; GETVAL(ctx, value, sub, "value"); while (isspace(value[0])) { value++; } if (!strcmp(value, "unbounded")) { list->max = 0;; } else { /* convert it to uint32_t */ errno = 0; auxs = NULL; val = strtoul(value, &auxs, 10); if (*auxs || value[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); goto error; } list->max = (uint32_t) val; if (list->min > list->max) { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "\"max-elements\" is smaller than \"min-elements\"."); goto error; } } if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MAX, 0, unres)) { goto error; } lyxml_free(ctx, sub); } else if (!strcmp(sub->name, "when")) { if (list->when) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } list->when = read_yin_when(module, sub, unres); if (!list->when) { lyxml_free(ctx, sub); goto error; } lyxml_free(ctx, sub); } else { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name); goto error; } } /* check - if list is configuration, key statement is mandatory * (but only if we are not in a grouping or augment, then the check is deferred) */ for (node = retval; node && !(node->nodetype & (LYS_GROUPING | LYS_AUGMENT | LYS_EXT)); node = node->parent); if (!node && (list->flags & LYS_CONFIG_W) && !list->keys_str) { LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, retval, "key", "list"); goto error; } /* middle part - process nodes with cardinality of 0..n except the data nodes */ if (c_tpdf) { list->tpdf = calloc(c_tpdf, sizeof *list->tpdf); LY_CHECK_ERR_GOTO(!list->tpdf, LOGMEM(ctx), error); } if (c_must) { list->must = calloc(c_must, sizeof *list->must); LY_CHECK_ERR_GOTO(!list->must, LOGMEM(ctx), error); } if (c_ftrs) { list->iffeature = calloc(c_ftrs, sizeof *list->iffeature); LY_CHECK_ERR_GOTO(!list->iffeature, LOGMEM(ctx), error); } if (c_ext) { /* some extensions may be already present from the substatements */ reallocated = realloc(retval->ext, (c_ext + retval->ext_size) * sizeof *retval->ext); LY_CHECK_ERR_GOTO(!reallocated, LOGMEM(ctx), error); retval->ext = reallocated; /* init memory */ memset(&retval->ext[retval->ext_size], 0, c_ext * sizeof *retval->ext); } LY_TREE_FOR_SAFE(yin->child, next, sub) { if (strcmp(sub->ns->value, LY_NSYIN)) { /* extension */ r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres); if (r) { goto error; } } else if (!strcmp(sub->name, "typedef")) { r = fill_yin_typedef(module, retval, sub, &list->tpdf[list->tpdf_size], unres); list->tpdf_size++; if (r) { goto error; } } else if (!strcmp(sub->name, "if-feature")) { r = fill_yin_iffeature(retval, 0, sub, &list->iffeature[list->iffeature_size], unres); list->iffeature_size++; if (r) { goto error; } } else if (!strcmp(sub->name, "must")) { r = fill_yin_must(module, sub, &list->must[list->must_size], unres); list->must_size++; if (r) { goto error; } } } lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size); /* last part - process data nodes */ LY_TREE_FOR_SAFE(root.child, next, sub) { if (!strcmp(sub->name, "container")) { node = read_yin_container(module, retval, sub, options, unres); } else if (!strcmp(sub->name, "leaf-list")) { node = read_yin_leaflist(module, retval, sub, options, unres); } else if (!strcmp(sub->name, "leaf")) { node = read_yin_leaf(module, retval, sub, options, unres); } else if (!strcmp(sub->name, "list")) { node = read_yin_list(module, retval, sub, options, unres); } else if (!strcmp(sub->name, "choice")) { node = read_yin_choice(module, retval, sub, options, unres); } else if (!strcmp(sub->name, "uses")) { node = read_yin_uses(module, retval, sub, options, unres); } else if (!strcmp(sub->name, "grouping")) { node = read_yin_grouping(module, retval, sub, options, unres); } else if (!strcmp(sub->name, "anyxml")) { node = read_yin_anydata(module, retval, sub, LYS_ANYXML, options, unres); } else if (!strcmp(sub->name, "anydata")) { node = read_yin_anydata(module, retval, sub, LYS_ANYDATA, options, unres); } else if (!strcmp(sub->name, "action")) { node = read_yin_rpc_action(module, retval, sub, options, unres); } else if (!strcmp(sub->name, "notification")) { node = read_yin_notif(module, retval, sub, options, unres); } else { LOGINT(ctx); goto error; } if (!node) { goto error; } lyxml_free(ctx, sub); } if (list->keys_str) { if (unres_schema_add_node(module, unres, list, UNRES_LIST_KEYS, NULL) == -1) { goto error; } } /* else config false list without a key, key_str presence in case of config true is checked earlier */ /* process unique statements */ if (c_uniq) { list->unique = calloc(c_uniq, sizeof *list->unique); LY_CHECK_ERR_GOTO(!list->unique, LOGMEM(ctx), error); LY_TREE_FOR_SAFE(uniq.child, next, sub) { r = fill_yin_unique(module, retval, sub, &list->unique[list->unique_size], unres); list->unique_size++; if (r) { goto error; } if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_UNIQUE, list->unique_size - 1, unres)) { goto error; } lyxml_free(ctx, sub); } } /* check XPath dependencies */ if (!(ctx->models.flags & LY_CTX_TRUSTED) && (list->when || list->must)) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax(retval)) { goto error; } } else { if (unres_schema_add_node(module, unres, retval, UNRES_XPATH, NULL) == -1) { goto error; } } } for (r = 0; r < retval->ext_size; ++r) { /* set flag, which represent LYEXT_OPT_VALID */ if (retval->ext[r]->flags & LYEXT_OPT_VALID) { retval->flags |= LYS_VALID_EXT; if (retval->ext[r]->flags & LYEXT_OPT_VALID_SUBTREE) { retval->flags |= LYS_VALID_EXT_SUBTREE; break; } } } return retval; error: lys_node_free(retval, NULL, 0); while (root.child) { lyxml_free(ctx, root.child); } while (uniq.child) { lyxml_free(ctx, uniq.child); } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'schema tree BUGFIX freeing nodes with no module set Context must be passed explicitly for these cases. Fixes #1452'</s>
<s>[INST] Given the following code containing errors, provide 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_yin_anydata(struct lys_module *module, struct lys_node *parent, struct lyxml_elem *yin, LYS_NODE type, int options, struct unres_schema *unres) { struct ly_ctx *ctx = module->ctx; struct lys_node *retval; struct lys_node_anydata *anyxml; struct lyxml_elem *sub, *next; const char *value; int r; int f_mand = 0; int c_must = 0, c_ftrs = 0, c_ext = 0; void *reallocated; anyxml = calloc(1, sizeof *anyxml); LY_CHECK_ERR_RETURN(!anyxml, LOGMEM(ctx), NULL); anyxml->nodetype = type; anyxml->prev = (struct lys_node *)anyxml; retval = (struct lys_node *)anyxml; if (read_yin_common(module, parent, retval, LYEXT_PAR_NODE, yin, OPT_IDENT | OPT_MODULE | ((options & LYS_PARSE_OPT_CFG_IGNORE) ? OPT_CFG_IGNORE : (options & LYS_PARSE_OPT_CFG_NOINHERIT) ? OPT_CFG_PARSE : OPT_CFG_PARSE | OPT_CFG_INHERIT), unres)) { goto error; } LOGDBG(LY_LDGYIN, "parsing %s statement \"%s\"", yin->name, retval->name); /* insert the node into the schema tree */ if (lys_node_addchild(parent, lys_main_module(module), retval, options)) { goto error; } LY_TREE_FOR_SAFE(yin->child, next, sub) { if (strcmp(sub->ns->value, LY_NSYIN)) { /* extension */ YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ext, retval->ext_size, "extensions", "anydata", error); c_ext++; } else if (!strcmp(sub->name, "mandatory")) { if (f_mand) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } /* just checking the flags in leaf is not sufficient, we would allow * multiple mandatory statements with the "false" value */ f_mand = 1; GETVAL(ctx, value, sub, "value"); if (!strcmp(value, "true")) { anyxml->flags |= LYS_MAND_TRUE; } else if (!strcmp(value, "false")) { anyxml->flags |= LYS_MAND_FALSE; } else { LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, value, sub->name); goto error; } /* else false is the default value, so we can ignore it */ if (lyp_yin_parse_subnode_ext(module, retval, LYEXT_PAR_NODE, sub, LYEXT_SUBSTMT_MANDATORY, 0, unres)) { goto error; } lyxml_free(ctx, sub); } else if (!strcmp(sub->name, "when")) { if (anyxml->when) { LOGVAL(ctx, LYE_TOOMANY, LY_VLOG_LYS, retval, sub->name, yin->name); goto error; } anyxml->when = read_yin_when(module, sub, unres); if (!anyxml->when) { lyxml_free(ctx, sub); goto error; } lyxml_free(ctx, sub); } else if (!strcmp(sub->name, "must")) { YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_must, anyxml->must_size, "musts", "anydata", error); c_must++; } else if (!strcmp(sub->name, "if-feature")) { YIN_CHECK_ARRAY_OVERFLOW_GOTO(ctx, c_ftrs, retval->iffeature_size, "if-features", "anydata", error); c_ftrs++; } else { LOGVAL(ctx, LYE_INSTMT, LY_VLOG_LYS, retval, sub->name); goto error; } } /* middle part - process nodes with cardinality of 0..n */ if (c_must) { anyxml->must = calloc(c_must, sizeof *anyxml->must); LY_CHECK_ERR_GOTO(!anyxml->must, LOGMEM(ctx), error); } if (c_ftrs) { anyxml->iffeature = calloc(c_ftrs, sizeof *anyxml->iffeature); LY_CHECK_ERR_GOTO(!anyxml->iffeature, LOGMEM(ctx), error); } if (c_ext) { /* some extensions may be already present from the substatements */ reallocated = realloc(retval->ext, (c_ext + retval->ext_size) * sizeof *retval->ext); LY_CHECK_ERR_GOTO(!reallocated, LOGMEM(ctx), error); retval->ext = reallocated; /* init memory */ memset(&retval->ext[retval->ext_size], 0, c_ext * sizeof *retval->ext); } LY_TREE_FOR_SAFE(yin->child, next, sub) { if (strcmp(sub->ns->value, LY_NSYIN)) { /* extension */ r = lyp_yin_fill_ext(retval, LYEXT_PAR_NODE, 0, 0, module, sub, &retval->ext, &retval->ext_size, unres); if (r) { goto error; } } else if (!strcmp(sub->name, "must")) { r = fill_yin_must(module, sub, &anyxml->must[anyxml->must_size], unres); anyxml->must_size++; if (r) { goto error; } } else if (!strcmp(sub->name, "if-feature")) { r = fill_yin_iffeature(retval, 0, sub, &anyxml->iffeature[anyxml->iffeature_size], unres); anyxml->iffeature_size++; if (r) { goto error; } } } lyp_reduce_ext_list(&retval->ext, retval->ext_size, c_ext + retval->ext_size); /* check XPath dependencies */ if (!(ctx->models.flags & LY_CTX_TRUSTED) && (anyxml->when || anyxml->must)) { if (options & LYS_PARSE_OPT_INGRP) { if (lyxp_node_check_syntax(retval)) { goto error; } } else { if (unres_schema_add_node(module, unres, retval, UNRES_XPATH, NULL) == -1) { goto error; } } } for (r = 0; r < retval->ext_size; ++r) { /* set flag, which represent LYEXT_OPT_VALID */ if (retval->ext[r]->flags & LYEXT_OPT_VALID) { retval->flags |= LYS_VALID_EXT; break; } } return retval; error: lys_node_free(retval, NULL, 0); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'schema tree BUGFIX freeing nodes with no module set Context must be passed explicitly for these cases. Fixes #1452'</s>
<s>[INST] Given the following code containing errors, provide 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 tool_rc key_import(ESYS_CONTEXT *ectx, TPM2B_PUBLIC *parent_pub, TPM2B_SENSITIVE *privkey, TPM2B_PUBLIC *pubkey, TPM2B_ENCRYPTED_SECRET *encrypted_seed, TPM2B_PRIVATE **imported_private) { TPMI_ALG_HASH name_alg = pubkey->publicArea.nameAlg; TPM2B_DIGEST *seed = &privkey->sensitiveArea.seedValue; /* * Create the protection encryption key that gets encrypted with the parents public key. */ TPM2B_DATA enc_sensitive_key = { .size = parent_pub->publicArea.parameters.rsaDetail.symmetric.keyBits.sym / 8 }; memset(enc_sensitive_key.buffer, 0xFF, enc_sensitive_key.size); /* * Calculate the object name. */ TPM2B_NAME pubname = TPM2B_TYPE_INIT(TPM2B_NAME, name); bool res = tpm2_identity_create_name(pubkey, &pubname); if (!res) { return false; } TPM2B_MAX_BUFFER hmac_key; TPM2B_MAX_BUFFER enc_key; tpm2_identity_util_calc_outer_integrity_hmac_key_and_dupsensitive_enc_key( parent_pub, &pubname, seed, &hmac_key, &enc_key); TPM2B_MAX_BUFFER encrypted_inner_integrity = TPM2B_EMPTY_INIT; tpm2_identity_util_calculate_inner_integrity(name_alg, privkey, &pubname, &enc_sensitive_key, &parent_pub->publicArea.parameters.rsaDetail.symmetric, &encrypted_inner_integrity); TPM2B_DIGEST outer_hmac = TPM2B_EMPTY_INIT; TPM2B_MAX_BUFFER encrypted_duplicate_sensitive = TPM2B_EMPTY_INIT; tpm2_identity_util_calculate_outer_integrity(parent_pub->publicArea.nameAlg, &pubname, &encrypted_inner_integrity, &hmac_key, &enc_key, &parent_pub->publicArea.parameters.rsaDetail.symmetric, &encrypted_duplicate_sensitive, &outer_hmac); TPM2B_PRIVATE private = TPM2B_EMPTY_INIT; res = create_import_key_private_data(&private, parent_pub->publicArea.nameAlg, &encrypted_duplicate_sensitive, &outer_hmac); if (!res) { return tool_rc_general_error; } TPMT_SYM_DEF_OBJECT *sym_alg = &parent_pub->publicArea.parameters.rsaDetail.symmetric; if (!ctx.cp_hash_path) { return tpm2_import(ectx, &ctx.parent.object, &enc_sensitive_key, pubkey, &private, encrypted_seed, sym_alg, imported_private, NULL); } TPM2B_DIGEST cp_hash = { .size = 0 }; tool_rc rc = tpm2_import(ectx, &ctx.parent.object, &enc_sensitive_key, pubkey, &private, encrypted_seed, sym_alg, imported_private, &cp_hash); if (rc != tool_rc_success) { return rc; } bool result = files_save_digest(&cp_hash, ctx.cp_hash_path); if (!result) { rc = tool_rc_general_error; } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-798'], 'message': 'tpm2_import: fix fixed AES key CVE-2021-3565 tpm2_import used a fixed AES key for the inner wrapper, which means that a MITM attack would be able to unwrap the imported key. Even the use of an encrypted session will not prevent this. The TPM only encrypts the first parameter which is the fixed symmetric key. To fix this, ensure the key size is 16 bytes or bigger and use OpenSSL to generate a secure random AES key. Fixes: #2738 Signed-off-by: William Roberts <william.c.roberts@intel.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 apr_status_t session_identity_decode(request_rec * r, session_rec * z) { char *last = NULL; char *encoded, *pair; const char *sep = "&"; /* sanity check - anything to decode? */ if (!z->encoded) { return OK; } /* decode what we have */ encoded = apr_pstrdup(r->pool, z->encoded); pair = apr_strtok(encoded, sep, &last); while (pair && pair[0]) { char *plast = NULL; const char *psep = "="; char *key = apr_strtok(pair, psep, &plast); char *val = apr_strtok(NULL, psep, &plast); if (key && *key) { if (!val || !*val) { apr_table_unset(z->entries, key); } else if (!ap_unescape_urlencoded(key) && !ap_unescape_urlencoded(val)) { if (!strcmp(SESSION_EXPIRY, key)) { z->expiry = (apr_time_t) apr_atoi64(val); } else { apr_table_set(z->entries, key, val); } } } pair = apr_strtok(NULL, sep, &last); } z->encoded = NULL; return OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'mod_session: save one apr_strtok() in session_identity_decode(). When the encoding is invalid (missing '='), no need to parse further. git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1887050 13f79535-47bb-0310-9956-ffa450edef68'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _rsa_sec_compute_root_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, mp_limb_t *x, const mp_limb_t *m, size_t mn) { mpz_t mz; mpz_t xz; int res; mpz_init(mz); mpz_init(xz); mpn_copyi(mpz_limbs_write(mz, mn), m, mn); mpz_limbs_finish(mz, mn); res = rsa_compute_root_tr(pub, key, random_ctx, random, xz, mz); if (res) mpz_limbs_copy(x, xz, mpz_size(pub->n)); mpz_clear(mz); mpz_clear(xz); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Change _rsa_sec_compute_root_tr to take a fix input size. Improves consistency with _rsa_sec_compute_root, and fixes zero-input bug.'</s>
<s>[INST] Given the following code containing errors, provide 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 hci_extended_inquiry_result_evt(struct hci_dev *hdev, struct sk_buff *skb) { struct inquiry_data data; struct extended_inquiry_info *info = (void *) (skb->data + 1); int num_rsp = *((__u8 *) skb->data); size_t eir_len; BT_DBG("%s num_rsp %d", hdev->name, num_rsp); if (!num_rsp) return; if (hci_dev_test_flag(hdev, HCI_PERIODIC_INQ)) return; hci_dev_lock(hdev); for (; num_rsp; num_rsp--, info++) { u32 flags; bool name_known; bacpy(&data.bdaddr, &info->bdaddr); data.pscan_rep_mode = info->pscan_rep_mode; data.pscan_period_mode = info->pscan_period_mode; data.pscan_mode = 0x00; memcpy(data.dev_class, info->dev_class, 3); data.clock_offset = info->clock_offset; data.rssi = info->rssi; data.ssp_mode = 0x01; if (hci_dev_test_flag(hdev, HCI_MGMT)) name_known = eir_get_data(info->data, sizeof(info->data), EIR_NAME_COMPLETE, NULL); else name_known = true; flags = hci_inquiry_cache_update(hdev, &data, name_known); eir_len = eir_get_length(info->data, sizeof(info->data)); mgmt_device_found(hdev, &info->bdaddr, ACL_LINK, 0x00, info->dev_class, info->rssi, flags, info->data, eir_len, NULL, 0); } hci_dev_unlock(hdev); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Bluetooth: Fix slab-out-of-bounds read in hci_extended_inquiry_result_evt() Check upon `num_rsp` is insufficient. A malformed event packet with a large `num_rsp` number makes hci_extended_inquiry_result_evt() go out of bounds. Fix it. This patch fixes the following syzbot bug: https://syzkaller.appspot.com/bug?id=4bf11aa05c4ca51ce0df86e500fce486552dc8d2 Reported-by: syzbot+d8489a79b781849b9c46@syzkaller.appspotmail.com Cc: stable@vger.kernel.org Signed-off-by: Peilin Ye <yepeilin.cs@gmail.com> Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Marcel Holtmann <marcel@holtmann.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 sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p, size_t msg_len, struct sock **orig_sk) { struct sock *sk = asoc->base.sk; int err = 0; long current_timeo = *timeo_p; DEFINE_WAIT(wait); pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc, *timeo_p, msg_len); /* Increment the association's refcnt. */ sctp_association_hold(asoc); /* Wait on the association specific sndbuf space. */ for (;;) { prepare_to_wait_exclusive(&asoc->wait, &wait, TASK_INTERRUPTIBLE); if (asoc->base.dead) goto do_dead; if (!*timeo_p) goto do_nonblock; if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING) goto do_error; if (signal_pending(current)) goto do_interrupted; if (msg_len <= sctp_wspace(asoc)) break; /* Let another process have a go. Since we are going * to sleep anyway. */ release_sock(sk); current_timeo = schedule_timeout(current_timeo); lock_sock(sk); if (sk != asoc->base.sk) { release_sock(sk); sk = asoc->base.sk; lock_sock(sk); } *timeo_p = current_timeo; } out: *orig_sk = sk; finish_wait(&asoc->wait, &wait); /* Release the association's refcnt. */ sctp_association_put(asoc); return err; do_dead: err = -ESRCH; goto out; do_error: err = -EPIPE; goto out; do_interrupted: err = sock_intr_errno(*timeo_p); goto out; do_nonblock: err = -EAGAIN; goto out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'sctp: return error if the asoc has been peeled off in sctp_wait_for_sndbuf After commit cea0cc80a677 ("sctp: use the right sk after waking up from wait_buf sleep"), it may change to lock another sk if the asoc has been peeled off in sctp_wait_for_sndbuf. However, the asoc's new sk could be already closed elsewhere, as it's in the sendmsg context of the old sk that can't avoid the new sk's closing. If the sk's last one refcnt is held by this asoc, later on after putting this asoc, the new sk will be freed, while under it's own lock. This patch is to revert that commit, but fix the old issue by returning error under the old sk's lock. Fixes: cea0cc80a677 ("sctp: use the right sk after waking up from wait_buf sleep") Reported-by: syzbot+ac6ea7baa4432811eb50@syzkaller.appspotmail.com Signed-off-by: Xin Long <lucien.xin@gmail.com> Acked-by: Neil Horman <nhorman@tuxdriver.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 void unzzip_cat_file(ZZIP_DIR* disk, char* name, FILE* out) { ZZIP_FILE* file = zzip_file_open (disk, name, 0); if (file) { char buffer[1024]; int len; while ((len = zzip_file_read (file, buffer, 1024))) { fwrite (buffer, 1, len, out); } zzip_file_close (file); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': '#68 ssize_t return value of zzip_file_read is a signed value being possibly -1'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: errno_t sssctl_run_command(const char *command) { int ret; DEBUG(SSSDBG_TRACE_FUNC, "Running %s\n", command); ret = system(command); if (ret == -1) { DEBUG(SSSDBG_CRIT_FAILURE, "Unable to execute %s\n", command); ERROR("Error while executing external command\n"); return EFAULT; } else if (WEXITSTATUS(ret) != 0) { DEBUG(SSSDBG_CRIT_FAILURE, "Command %s failed with [%d]\n", command, WEXITSTATUS(ret)); ERROR("Error while executing external command\n"); return EIO; } return EOK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'TOOLS: replace system() with execvp() to avoid execution of user supplied command :relnote: A flaw was found in SSSD, where the sssctl command was vulnerable to shell command injection via the logs-fetch and cache-expire subcommands. This flaw allows an attacker to trick the root user into running a specially crafted sssctl command, such as via sudo, to gain root access. The highest threat from this vulnerability is to confidentiality, integrity, as well as system availability. This patch fixes a flaw by replacing system() with execvp(). :fixes: CVE-2021-3621 Reviewed-by: Pavel Březina <pbrezina@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void WebPImage::doWriteMetadata(BasicIo& outIo) { if (!io_->isopen()) throw Error(kerInputDataReadFailed); if (!outIo.isopen()) throw Error(kerImageWriteFailed); #ifdef EXIV2_DEBUG_MESSAGES std::cout << "Writing metadata" << std::endl; #endif byte data [WEBP_TAG_SIZE*3]; DataBuf chunkId(WEBP_TAG_SIZE+1); chunkId.pData_ [WEBP_TAG_SIZE] = '\0'; io_->read(data, WEBP_TAG_SIZE * 3); uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian); /* Set up header */ if (outIo.write(data, WEBP_TAG_SIZE * 3) != WEBP_TAG_SIZE * 3) throw Error(kerImageWriteFailed); /* Parse Chunks */ bool has_size = false; bool has_xmp = false; bool has_exif = false; bool has_vp8x = false; bool has_alpha = false; bool has_icc = iccProfileDefined(); int width = 0; int height = 0; byte size_buff[WEBP_TAG_SIZE]; Blob blob; if (exifData_.count() > 0) { ExifParser::encode(blob, littleEndian, exifData_); if (blob.size() > 0) { has_exif = true; } } if (xmpData_.count() > 0 && !writeXmpFromPacket()) { XmpParser::encode(xmpPacket_, xmpData_, XmpParser::useCompactFormat | XmpParser::omitAllFormatting); } has_xmp = xmpPacket_.size() > 0; std::string xmp(xmpPacket_); /* Verify for a VP8X Chunk First before writing in case we have any exif or xmp data, also check for any chunks with alpha frame/layer set */ while ( !io_->eof() && (uint64_t) io_->tell() < filesize) { io_->read(chunkId.pData_, WEBP_TAG_SIZE); io_->read(size_buff, WEBP_TAG_SIZE); long size = Exiv2::getULong(size_buff, littleEndian); DataBuf payload(size); io_->read(payload.pData_, payload.size_); byte c; if ( payload.size_ % 2 ) io_->read(&c,1); /* Chunk with information about features used in the file. */ if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_vp8x) { has_vp8x = true; } if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_size) { has_size = true; byte size_buf[WEBP_TAG_SIZE]; // Fetch width - stored in 24bits memcpy(&size_buf, &payload.pData_[4], 3); size_buf[3] = 0; width = Exiv2::getULong(size_buf, littleEndian) + 1; // Fetch height - stored in 24bits memcpy(&size_buf, &payload.pData_[7], 3); size_buf[3] = 0; height = Exiv2::getULong(size_buf, littleEndian) + 1; } /* Chunk with with animation control data. */ #ifdef __CHECK_FOR_ALPHA__ // Maybe in the future if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANIM) && !has_alpha) { has_alpha = true; } #endif /* Chunk with with lossy image data. */ #ifdef __CHECK_FOR_ALPHA__ // Maybe in the future if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_alpha) { has_alpha = true; } #endif if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_size) { has_size = true; byte size_buf[2]; /* Refer to this https://tools.ietf.org/html/rfc6386 for height and width reference for VP8 chunks */ // Fetch width - stored in 16bits memcpy(&size_buf, &payload.pData_[6], 2); width = Exiv2::getUShort(size_buf, littleEndian) & 0x3fff; // Fetch height - stored in 16bits memcpy(&size_buf, &payload.pData_[8], 2); height = Exiv2::getUShort(size_buf, littleEndian) & 0x3fff; } /* Chunk with with lossless image data. */ if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_alpha) { if ((payload.pData_[4] & WEBP_VP8X_ALPHA_BIT) == WEBP_VP8X_ALPHA_BIT) { has_alpha = true; } } if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_size) { has_size = true; byte size_buf_w[2]; byte size_buf_h[3]; /* For VP8L chunks width & height are stored in 28 bits of a 32 bit field requires bitshifting to get actual sizes. Width and height are split even into 14 bits each. Refer to this https://goo.gl/bpgMJf */ // Fetch width - 14 bits wide memcpy(&size_buf_w, &payload.pData_[1], 2); size_buf_w[1] &= 0x3F; width = Exiv2::getUShort(size_buf_w, littleEndian) + 1; // Fetch height - 14 bits wide memcpy(&size_buf_h, &payload.pData_[2], 3); size_buf_h[0] = ((size_buf_h[0] >> 6) & 0x3) | ((size_buf_h[1] & 0x3F) << 0x2); size_buf_h[1] = ((size_buf_h[1] >> 6) & 0x3) | ((size_buf_h[2] & 0xF) << 0x2); height = Exiv2::getUShort(size_buf_h, littleEndian) + 1; } /* Chunk with animation frame. */ if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_alpha) { if ((payload.pData_[5] & 0x2) == 0x2) { has_alpha = true; } } if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_size) { has_size = true; byte size_buf[WEBP_TAG_SIZE]; // Fetch width - stored in 24bits memcpy(&size_buf, &payload.pData_[6], 3); size_buf[3] = 0; width = Exiv2::getULong(size_buf, littleEndian) + 1; // Fetch height - stored in 24bits memcpy(&size_buf, &payload.pData_[9], 3); size_buf[3] = 0; height = Exiv2::getULong(size_buf, littleEndian) + 1; } /* Chunk with alpha data. */ if (equalsWebPTag(chunkId, "ALPH") && !has_alpha) { has_alpha = true; } } /* Inject a VP8X chunk if one isn't available. */ if (!has_vp8x) { inject_VP8X(outIo, has_xmp, has_exif, has_alpha, has_icc, width, height); } io_->seek(12, BasicIo::beg); while ( !io_->eof() && (uint64_t) io_->tell() < filesize) { io_->read(chunkId.pData_, 4); io_->read(size_buff, 4); long size = Exiv2::getULong(size_buff, littleEndian); DataBuf payload(size); io_->read(payload.pData_, size); if ( io_->tell() % 2 ) io_->seek(+1,BasicIo::cur); // skip pad if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X)) { if (has_icc){ payload.pData_[0] |= WEBP_VP8X_ICC_BIT; } else { payload.pData_[0] &= ~WEBP_VP8X_ICC_BIT; } if (has_xmp){ payload.pData_[0] |= WEBP_VP8X_XMP_BIT; } else { payload.pData_[0] &= ~WEBP_VP8X_XMP_BIT; } if (has_exif) { payload.pData_[0] |= WEBP_VP8X_EXIF_BIT; } else { payload.pData_[0] &= ~WEBP_VP8X_EXIF_BIT; } if (outIo.write(chunkId.pData_, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(payload.pData_, payload.size_) != payload.size_) throw Error(kerImageWriteFailed); if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } if (has_icc) { if (outIo.write((const byte*)WEBP_CHUNK_HEADER_ICCP, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); ul2Data(data, (uint32_t) iccProfile_.size_, littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(iccProfile_.pData_, iccProfile_.size_) != iccProfile_.size_) { throw Error(kerImageWriteFailed); } has_icc = false; } } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP)) { // Skip it altogether handle it prior to here :) } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF)) { // Skip and add new data afterwards } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP)) { // Skip and add new data afterwards } else { if (outIo.write(chunkId.pData_, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(payload.pData_, payload.size_) != payload.size_) throw Error(kerImageWriteFailed); } // Encoder required to pad odd sized data with a null byte if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } } if (has_exif) { if (outIo.write((const byte*)WEBP_CHUNK_HEADER_EXIF, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); us2Data(data, (uint16_t) blob.size()+8, bigEndian); ul2Data(data, (uint32_t) blob.size(), littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write((const byte*)&blob[0], static_cast<long>(blob.size())) != (long)blob.size()) { throw Error(kerImageWriteFailed); } if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } } if (has_xmp) { if (outIo.write((const byte*)WEBP_CHUNK_HEADER_XMP, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); ul2Data(data, (uint32_t) xmpPacket().size(), littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write((const byte*)xmp.data(), static_cast<long>(xmp.size())) != (long)xmp.size()) { throw Error(kerImageWriteFailed); } if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } } // Fix File Size Payload Data outIo.seek(0, BasicIo::beg); filesize = outIo.size() - 8; outIo.seek(4, BasicIo::beg); ul2Data(data, (uint32_t) filesize, littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); } // WebPImage::writeMetadata ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'Improve bound checking in WebPImage::doWriteMetadata()'</s>
<s>[INST] Given the following code containing errors, provide 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 cil_reset_classpermission(struct cil_classpermission *cp) { if (cp == NULL) { return; } cil_reset_classperms_list(cp->classperms); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'libsepol/cil: Destroy classperms list when resetting classpermission Nicolas Iooss reports: A few months ago, OSS-Fuzz found a crash in the CIL compiler, which got reported as https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=28648 (the title is misleading, or is caused by another issue that conflicts with the one I report in this message). Here is a minimized CIL policy which reproduces the issue: (class CLASS (PERM)) (classorder (CLASS)) (sid SID) (sidorder (SID)) (user USER) (role ROLE) (type TYPE) (category CAT) (categoryorder (CAT)) (sensitivity SENS) (sensitivityorder (SENS)) (sensitivitycategory SENS (CAT)) (allow TYPE self (CLASS (PERM))) (roletype ROLE TYPE) (userrole USER ROLE) (userlevel USER (SENS)) (userrange USER ((SENS)(SENS (CAT)))) (sidcontext SID (USER ROLE TYPE ((SENS)(SENS)))) (classpermission CLAPERM) (optional OPT (roletype nonexistingrole nonexistingtype) (classpermissionset CLAPERM (CLASS (PERM))) ) The CIL policy fuzzer (which mimics secilc built with clang Address Sanitizer) reports: ==36541==ERROR: AddressSanitizer: heap-use-after-free on address 0x603000004f98 at pc 0x56445134c842 bp 0x7ffe2a256590 sp 0x7ffe2a256588 READ of size 8 at 0x603000004f98 thread T0 #0 0x56445134c841 in __cil_verify_classperms /selinux/libsepol/src/../cil/src/cil_verify.c:1620:8 #1 0x56445134a43e in __cil_verify_classpermission /selinux/libsepol/src/../cil/src/cil_verify.c:1650:9 #2 0x56445134a43e in __cil_pre_verify_helper /selinux/libsepol/src/../cil/src/cil_verify.c:1715:8 #3 0x5644513225ac in cil_tree_walk_core /selinux/libsepol/src/../cil/src/cil_tree.c:272:9 #4 0x564451322ab1 in cil_tree_walk /selinux/libsepol/src/../cil/src/cil_tree.c:316:7 #5 0x5644513226af in cil_tree_walk_core /selinux/libsepol/src/../cil/src/cil_tree.c:284:9 #6 0x564451322ab1 in cil_tree_walk /selinux/libsepol/src/../cil/src/cil_tree.c:316:7 #7 0x5644512b88fd in cil_pre_verify /selinux/libsepol/src/../cil/src/cil_post.c:2510:7 #8 0x5644512b88fd in cil_post_process /selinux/libsepol/src/../cil/src/cil_post.c:2524:7 #9 0x5644511856ff in cil_compile /selinux/libsepol/src/../cil/src/cil.c:564:7 The classperms list of a classpermission rule is created and filled in when classpermissionset rules are processed, so it doesn't own any part of the list and shouldn't retain any of it when it is reset. Destroy the classperms list (without destroying the data in it) when resetting a classpermission rule. Reported-by: Nicolas Iooss <nicolas.iooss@m4x.org> Signed-off-by: James Carter <jwcart2@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void xt_compat_match_from_user(struct xt_entry_match *m, void **dstptr, unsigned int *size) { const struct xt_match *match = m->u.kernel.match; struct compat_xt_entry_match *cm = (struct compat_xt_entry_match *)m; int pad, off = xt_compat_match_offset(match); u_int16_t msize = cm->u.user.match_size; char name[sizeof(m->u.user.name)]; m = *dstptr; memcpy(m, cm, sizeof(*cm)); if (match->compat_from_user) match->compat_from_user(m->data, cm->data); else memcpy(m->data, cm->data, msize - sizeof(*cm)); pad = XT_ALIGN(match->matchsize) - match->matchsize; if (pad > 0) memset(m->data + match->matchsize, 0, pad); msize += off; m->u.user.match_size = msize; strlcpy(name, match->name, sizeof(name)); module_put(match->me); strncpy(m->u.user.name, name, sizeof(m->u.user.name)); *size += off; *dstptr += msize; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'netfilter: x_tables: fix compat match/target pad out-of-bound write xt_compat_match/target_from_user doesn't check that zeroing the area to start of next rule won't write past end of allocated ruleset blob. Remove this code and zero the entire blob beforehand. Reported-by: syzbot+cfc0247ac173f597aaaa@syzkaller.appspotmail.com Reported-by: Andy Nguyen <theflow@google.com> Fixes: 9fa492cdc160c ("[NETFILTER]: x_tables: simplify compat API") Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.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: compat_calc_match(struct ipt_entry_match *m, int * size) { if (m->u.kernel.match->compat) m->u.kernel.match->compat(m, NULL, size, COMPAT_CALC_SIZE); else xt_compat_match(m, NULL, size, COMPAT_CALC_SIZE); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': '[NETFILTER]: x_tables: simplify compat API Split the xt_compat_match/xt_compat_target into smaller type-safe functions performing just one operation. Handle all alignment and size-related conversions centrally in these function instead of requiring each module to implement a full-blown conversion function. Replace ->compat callback by ->compat_from_user and ->compat_to_user callbacks, responsible for converting just a single private structure. Signed-off-by: Patrick McHardy <kaber@trash.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cockpit_auth_login_finish (CockpitAuth *self, GAsyncResult *result, GIOStream *connection, GHashTable *headers, GError **error) { JsonObject *body = NULL; CockpitCreds *creds = NULL; CockpitSession *session = NULL; gboolean force_secure; gchar *cookie_name; gchar *cookie_b64; gchar *header; gchar *id; g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (self), cockpit_auth_login_async), NULL); g_object_ref (result); session = g_simple_async_result_get_op_res_gpointer (G_SIMPLE_ASYNC_RESULT (result)); if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result), error)) goto out; g_return_val_if_fail (session != NULL, NULL); g_return_val_if_fail (session->result == NULL, NULL); cockpit_session_reset (session); if (session->authorize) { if (build_authorize_challenge (self, session->authorize, connection, headers, &body, &session->conversation)) { if (session->conversation) { reset_authorize_timeout (session, TRUE); g_hash_table_replace (self->conversations, session->conversation, cockpit_session_ref (session)); } } } if (session->initialized) { /* Start off in the idling state, and begin a timeout during which caller must do something else */ on_web_service_idling (session->service, session); creds = cockpit_web_service_get_creds (session->service); id = cockpit_auth_nonce (self); session->cookie = g_strdup_printf ("v=2;k=%s", id); g_hash_table_insert (self->sessions, session->cookie, cockpit_session_ref (session)); g_free (id); if (headers) { if (self->flags & COCKPIT_AUTH_FOR_TLS_PROXY) force_secure = TRUE; else force_secure = connection ? !G_IS_SOCKET_CONNECTION (connection) : TRUE; cookie_name = application_cookie_name (cockpit_creds_get_application (creds)); cookie_b64 = g_base64_encode ((guint8 *)session->cookie, strlen (session->cookie)); header = g_strdup_printf ("%s=%s; Path=/; %s HttpOnly", cookie_name, cookie_b64, force_secure ? " Secure;" : ""); g_free (cookie_b64); g_free (cookie_name); g_hash_table_insert (headers, g_strdup ("Set-Cookie"), header); } if (body) json_object_unref (body); body = cockpit_creds_to_json (creds); } else { g_set_error (error, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED, "Authentication failed"); } out: self->startups--; g_object_unref (result); /* Successful login */ if (creds) g_info ("User %s logged into session %s", cockpit_creds_get_user (creds), cockpit_web_service_get_id (session->service)); return body; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-1021'], 'message': 'ws: Restrict our cookie to the login host only Mark our cookie as `SameSite: Strict` [1]. The current `None` default will soon be moved to `Lax` by Firefox and Chromium, and recent versions started to throw a warning about it. [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite https://bugzilla.redhat.com/show_bug.cgi?id=1891944'</s>
<s>[INST] Given the following code containing errors, provide 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 nested_vmcb02_prepare_control(struct vcpu_svm *svm) { const u32 mask = V_INTR_MASKING_MASK | V_GIF_ENABLE_MASK | V_GIF_MASK; struct kvm_vcpu *vcpu = &svm->vcpu; /* * Filled at exit: exit_code, exit_code_hi, exit_info_1, exit_info_2, * exit_int_info, exit_int_info_err, next_rip, insn_len, insn_bytes. */ /* * Also covers avic_vapic_bar, avic_backing_page, avic_logical_id, * avic_physical_id. */ WARN_ON(kvm_apicv_activated(svm->vcpu.kvm)); /* Copied from vmcb01. msrpm_base can be overwritten later. */ svm->vmcb->control.nested_ctl = svm->vmcb01.ptr->control.nested_ctl; svm->vmcb->control.iopm_base_pa = svm->vmcb01.ptr->control.iopm_base_pa; svm->vmcb->control.msrpm_base_pa = svm->vmcb01.ptr->control.msrpm_base_pa; /* Done at vmrun: asid. */ /* Also overwritten later if necessary. */ svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING; /* nested_cr3. */ if (nested_npt_enabled(svm)) nested_svm_init_mmu_context(vcpu); svm->vmcb->control.tsc_offset = vcpu->arch.tsc_offset = vcpu->arch.l1_tsc_offset + svm->nested.ctl.tsc_offset; svm->vmcb->control.int_ctl = (svm->nested.ctl.int_ctl & ~mask) | (svm->vmcb01.ptr->control.int_ctl & mask); svm->vmcb->control.virt_ext = svm->nested.ctl.virt_ext; svm->vmcb->control.int_vector = svm->nested.ctl.int_vector; svm->vmcb->control.int_state = svm->nested.ctl.int_state; svm->vmcb->control.event_inj = svm->nested.ctl.event_inj; svm->vmcb->control.event_inj_err = svm->nested.ctl.event_inj_err; svm->vmcb->control.pause_filter_count = svm->nested.ctl.pause_filter_count; svm->vmcb->control.pause_filter_thresh = svm->nested.ctl.pause_filter_thresh; nested_svm_transition_tlb_flush(vcpu); /* Enter Guest-Mode */ enter_guest_mode(vcpu); /* * Merge guest and host intercepts - must be called with vcpu in * guest-mode to take effect. */ recalc_intercepts(svm); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-862'], 'message': 'KVM: nSVM: avoid picking up unsupported bits from L2 in int_ctl (CVE-2021-3653) * Invert the mask of bits that we pick from L2 in nested_vmcb02_prepare_control * Invert and explicitly use VIRQ related bits bitmask in svm_clear_vintr This fixes a security issue that allowed a malicious L1 to run L2 with AVIC enabled, which allowed the L2 to exploit the uninitialized and enabled AVIC to read/write the host physical memory at some offsets. Fixes: 3d6368ef580a ("KVM: SVM: Add VMRUN handler") Signed-off-by: Maxim Levitsky <mlevitsk@redhat.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: Pl_AES_PDF::flush(bool strip_padding) { assert(this->offset == this->buf_size); if (first) { first = false; bool return_after_init = false; if (this->cbc_mode) { if (encrypt) { // Set cbc_block to the initialization vector, and if // not zero, write it to the output stream. initializeVector(); if (! (this->use_zero_iv || this->use_specified_iv)) { getNext()->write(this->cbc_block, this->buf_size); } } else if (this->use_zero_iv || this->use_specified_iv) { // Initialize vector with zeroes; zero vector was not // written to the beginning of the input file. initializeVector(); } else { // Take the first block of input as the initialization // vector. There's nothing to write at this time. memcpy(this->cbc_block, this->inbuf, this->buf_size); this->offset = 0; return_after_init = true; } } this->crypto->rijndael_init( encrypt, this->key.get(), key_bytes, this->cbc_mode, this->cbc_block); if (return_after_init) { return; } } if (this->encrypt) { this->crypto->rijndael_process(this->inbuf, this->outbuf); } else { this->crypto->rijndael_process(this->inbuf, this->outbuf); } unsigned int bytes = this->buf_size; if (strip_padding) { unsigned char last = this->outbuf[this->buf_size - 1]; if (last <= this->buf_size) { bool strip = true; for (unsigned int i = 1; i <= last; ++i) { if (this->outbuf[this->buf_size - i] != last) { strip = false; break; } } if (strip) { bytes -= last; } } } getNext()->write(this->outbuf, bytes); this->offset = 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix some pipelines to be safe if downstream write fails (fuzz issue 28262)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: decodeJsonStructure(void *dst, const UA_DataType *type, CtxJson *ctx, ParseCtx *parseCtx, UA_Boolean moveToken) { (void) moveToken; /* Check the recursion limit */ if(ctx->depth > UA_JSON_ENCODING_MAX_RECURSION) return UA_STATUSCODE_BADENCODINGERROR; ctx->depth++; uintptr_t ptr = (uintptr_t)dst; status ret = UA_STATUSCODE_GOOD; u8 membersSize = type->membersSize; const UA_DataType *typelists[2] = { UA_TYPES, &type[-type->typeIndex] }; UA_STACKARRAY(DecodeEntry, entries, membersSize); for(size_t i = 0; i < membersSize && ret == UA_STATUSCODE_GOOD; ++i) { const UA_DataTypeMember *m = &type->members[i]; const UA_DataType *mt = &typelists[!m->namespaceZero][m->memberTypeIndex]; entries[i].type = mt; if(!m->isArray) { ptr += m->padding; entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = decodeJsonJumpTable[mt->typeKind]; entries[i].found = false; ptr += mt->memSize; } else { ptr += m->padding; ptr += sizeof(size_t); entries[i].fieldName = m->memberName; entries[i].fieldPointer = (void*)ptr; entries[i].function = (decodeJsonSignature)Array_decodeJson; entries[i].found = false; ptr += sizeof(void*); } } ret = decodeFields(ctx, parseCtx, entries, membersSize, type); ctx->depth--; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-787'], 'message': 'fix(json): Check max recursion depth in more places'</s>
<s>[INST] Given the following code containing errors, provide 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 oidc_cache_crypto_decrypt_impl(request_rec *r, unsigned char *ciphertext, int ciphertext_len, const unsigned char *aad, int aad_len, const unsigned char *tag, int tag_len, unsigned char *key, const unsigned char *iv, int iv_len, unsigned char *plaintext) { EVP_CIPHER_CTX *ctx; int len; int plaintext_len; int ret; /* create and initialize the context */ if (!(ctx = EVP_CIPHER_CTX_new())) { oidc_cache_crypto_openssl_error(r, "EVP_CIPHER_CTX_new"); return -1; } /* initialize the decryption cipher */ if (!EVP_DecryptInit_ex(ctx, OIDC_CACHE_CIPHER, NULL, NULL, NULL)) { oidc_cache_crypto_openssl_error(r, "EVP_DecryptInit_ex"); return -1; } /* set IV length */ if (!EVP_CIPHER_CTX_ctrl(ctx, OIDC_CACHE_CRYPTO_SET_IVLEN, iv_len, NULL)) { oidc_cache_crypto_openssl_error(r, "EVP_CIPHER_CTX_ctrl"); return -1; } /* initialize key and IV */ if (!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) { oidc_cache_crypto_openssl_error(r, "EVP_DecryptInit_ex"); return -1; } /* provide AAD data */ if (!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len)) { oidc_cache_crypto_openssl_error(r, "EVP_DecryptUpdate aad: aad_len=%d", aad_len); return -1; } /* provide the message to be decrypted and obtain the plaintext output */ if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) { oidc_cache_crypto_openssl_error(r, "EVP_DecryptUpdate ciphertext"); return -1; } plaintext_len = len; /* set expected tag value; works in OpenSSL 1.0.1d and later */ if (!EVP_CIPHER_CTX_ctrl(ctx, OIDC_CACHE_CRYPTO_SET_TAG, tag_len, (void *) tag)) { oidc_cache_crypto_openssl_error(r, "EVP_CIPHER_CTX_ctrl"); return -1; } /* * finalize the decryption; a positive return value indicates success, * anything else is a failure - the plaintext is not trustworthy */ ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len); /* clean up */ EVP_CIPHER_CTX_free(ctx); if (ret > 0) { /* success */ plaintext_len += len; return plaintext_len; } else { /* verify failed */ oidc_cache_crypto_openssl_error(r, "EVP_DecryptFinal_ex"); return -1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'use encrypted JWTs for storing encrypted cache contents - avoid using static AAD/IV; thanks @niebardzo - bump to 2.4.9-dev Signed-off-by: Hans Zandbelt <hans.zandbelt@zmartzone.eu>'</s>
<s>[INST] Given the following code containing errors, provide 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 pj_bool_t on_accept_complete2(pj_ssl_sock_t *ssock, pj_ssl_sock_t *new_ssock, const pj_sockaddr_t *src_addr, int src_addr_len, pj_status_t accept_status) { struct tls_listener *listener; struct tls_transport *tls; pj_ssl_sock_info ssl_info; char addr[PJ_INET6_ADDRSTRLEN+10]; pjsip_tp_state_callback state_cb; pj_sockaddr tmp_src_addr; pj_bool_t is_shutdown; pj_status_t status; char addr_buf[PJ_INET6_ADDRSTRLEN+10]; PJ_UNUSED_ARG(src_addr_len); listener = (struct tls_listener*) pj_ssl_sock_get_user_data(ssock); if (accept_status != PJ_SUCCESS) { if (listener && listener->tls_setting.on_accept_fail_cb) { pjsip_tls_on_accept_fail_param param; pj_ssl_sock_info ssi; pj_bzero(&param, sizeof(param)); param.status = accept_status; param.local_addr = &listener->factory.local_addr; param.remote_addr = src_addr; if (new_ssock && pj_ssl_sock_get_info(new_ssock, &ssi) == PJ_SUCCESS) { param.last_native_err = ssi.last_native_err; } (*listener->tls_setting.on_accept_fail_cb) (&param); } return PJ_FALSE; } PJ_ASSERT_RETURN(new_ssock, PJ_TRUE); if (!listener->is_registered) { if (listener->tls_setting.on_accept_fail_cb) { pjsip_tls_on_accept_fail_param param; pj_bzero(&param, sizeof(param)); param.status = PJSIP_TLS_EACCEPT; param.local_addr = &listener->factory.local_addr; param.remote_addr = src_addr; (*listener->tls_setting.on_accept_fail_cb) (&param); } return PJ_FALSE; } PJ_LOG(4,(listener->factory.obj_name, "TLS listener %s: got incoming TLS connection " "from %s, sock=%d", pj_addr_str_print(&listener->factory.addr_name.host, listener->factory.addr_name.port, addr_buf, sizeof(addr_buf), 1), pj_sockaddr_print(src_addr, addr, sizeof(addr), 3), new_ssock)); /* Retrieve SSL socket info, close the socket if this is failed * as the SSL socket info availability is rather critical here. */ status = pj_ssl_sock_get_info(new_ssock, &ssl_info); if (status != PJ_SUCCESS) { pj_ssl_sock_close(new_ssock); if (listener->tls_setting.on_accept_fail_cb) { pjsip_tls_on_accept_fail_param param; pj_bzero(&param, sizeof(param)); param.status = status; param.local_addr = &listener->factory.local_addr; param.remote_addr = src_addr; (*listener->tls_setting.on_accept_fail_cb) (&param); } return PJ_TRUE; } /* Copy to larger buffer, just in case */ pj_bzero(&tmp_src_addr, sizeof(tmp_src_addr)); pj_sockaddr_cp(&tmp_src_addr, src_addr); /* * Incoming connection! * Create TLS transport for the new socket. */ status = tls_create( listener, NULL, new_ssock, PJ_TRUE, &ssl_info.local_addr, &tmp_src_addr, NULL, ssl_info.grp_lock, &tls); if (status != PJ_SUCCESS) { if (listener->tls_setting.on_accept_fail_cb) { pjsip_tls_on_accept_fail_param param; pj_bzero(&param, sizeof(param)); param.status = status; param.local_addr = &listener->factory.local_addr; param.remote_addr = src_addr; (*listener->tls_setting.on_accept_fail_cb) (&param); } return PJ_TRUE; } /* Set the "pending" SSL socket user data */ pj_ssl_sock_set_user_data(new_ssock, tls); /* Prevent immediate transport destroy as application may access it * (getting info, etc) in transport state notification callback. */ pjsip_transport_add_ref(&tls->base); /* If there is verification error and verification is mandatory, shutdown * and destroy the transport. */ if (ssl_info.verify_status && listener->tls_setting.verify_client) { if (tls->close_reason == PJ_SUCCESS) tls->close_reason = PJSIP_TLS_ECERTVERIF; pjsip_transport_shutdown(&tls->base); } /* Notify transport state to application */ state_cb = pjsip_tpmgr_get_state_cb(tls->base.tpmgr); if (state_cb) { pjsip_transport_state_info state_info; pjsip_tls_state_info tls_info; pjsip_transport_state tp_state; /* Init transport state info */ pj_bzero(&tls_info, sizeof(tls_info)); pj_bzero(&state_info, sizeof(state_info)); tls_info.ssl_sock_info = &ssl_info; state_info.ext_info = &tls_info; /* Set transport state based on verification status */ if (ssl_info.verify_status && listener->tls_setting.verify_client) { tp_state = PJSIP_TP_STATE_DISCONNECTED; state_info.status = PJSIP_TLS_ECERTVERIF; } else { tp_state = PJSIP_TP_STATE_CONNECTED; state_info.status = PJ_SUCCESS; } (*state_cb)(&tls->base, tp_state, &state_info); } /* Release transport reference. If transport is shutting down, it may * get destroyed here. */ is_shutdown = tls->base.is_shutdown; pjsip_transport_dec_ref(&tls->base); if (is_shutdown) return PJ_TRUE; status = tls_start_read(tls); if (status != PJ_SUCCESS) { PJ_LOG(3,(tls->base.obj_name, "New transport cancelled")); tls_init_shutdown(tls, status); tls_destroy(&tls->base, status); } else { /* Start keep-alive timer */ if (pjsip_cfg()->tls.keep_alive_interval) { pj_time_val delay = {0}; delay.sec = pjsip_cfg()->tls.keep_alive_interval; pjsip_endpt_schedule_timer(listener->endpt, &tls->ka_timer, &delay); tls->ka_timer.id = PJ_TRUE; pj_gettimeofday(&tls->last_activity); } } return PJ_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-703'], 'message': 'Merge pull request from GHSA-cv8x-p47p-99wr * - Avoid SSL socket parent/listener getting destroyed during handshake by increasing parent's reference count. - Add missing SSL socket close when the newly accepted SSL socket is discarded in SIP TLS transport. * - Fix silly mistake: accepted active socket created without group lock in SSL socket. - Replace assertion with normal validation check of SSL socket instance in OpenSSL verification callback (verify_cb()) to avoid crash, e.g: if somehow race condition with SSL socket destroy happens or OpenSSL application data index somehow gets corrupted.'</s>
<s>[INST] Given the following code containing errors, provide 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 rb_per_cpu_empty(struct ring_buffer_per_cpu *cpu_buffer) { struct buffer_page *reader = cpu_buffer->reader_page; struct buffer_page *head = rb_set_head_page(cpu_buffer); struct buffer_page *commit = cpu_buffer->commit_page; /* In case of error, head will be NULL */ if (unlikely(!head)) return true; return reader->read == rb_page_commit(reader) && (commit == reader || (commit == head && head->read == rb_page_commit(commit))); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'tracing: Fix bug in rb_per_cpu_empty() that might cause deadloop. The "rb_per_cpu_empty()" misinterpret the condition (as not-empty) when "head_page" and "commit_page" of "struct ring_buffer_per_cpu" points to the same buffer page, whose "buffer_data_page" is empty and "read" field is non-zero. An error scenario could be constructed as followed (kernel perspective): 1. All pages in the buffer has been accessed by reader(s) so that all of them will have non-zero "read" field. 2. Read and clear all buffer pages so that "rb_num_of_entries()" will return 0 rendering there's no more data to read. It is also required that the "read_page", "commit_page" and "tail_page" points to the same page, while "head_page" is the next page of them. 3. Invoke "ring_buffer_lock_reserve()" with large enough "length" so that it shot pass the end of current tail buffer page. Now the "head_page", "commit_page" and "tail_page" points to the same page. 4. Discard current event with "ring_buffer_discard_commit()", so that "head_page", "commit_page" and "tail_page" points to a page whose buffer data page is now empty. When the error scenario has been constructed, "tracing_read_pipe" will be trapped inside a deadloop: "trace_empty()" returns 0 since "rb_per_cpu_empty()" returns 0 when it hits the CPU containing such constructed ring buffer. Then "trace_find_next_entry_inc()" always return NULL since "rb_num_of_entries()" reports there's no more entry to read. Finally "trace_seq_to_user()" returns "-EBUSY" spanking "tracing_read_pipe" back to the start of the "waitagain" loop. I've also written a proof-of-concept script to construct the scenario and trigger the bug automatically, you can use it to trace and validate my reasoning above: https://github.com/aegistudio/RingBufferDetonator.git Tests has been carried out on linux kernel 5.14-rc2 (2734d6c1b1a089fb593ef6a23d4b70903526fe0c), my fixed version of kernel (for testing whether my update fixes the bug) and some older kernels (for range of affected kernels). Test result is also attached to the proof-of-concept repository. Link: https://lore.kernel.org/linux-trace-devel/YPaNxsIlb2yjSi5Y@aegistudio/ Link: https://lore.kernel.org/linux-trace-devel/YPgrN85WL9VyrZ55@aegistudio Cc: stable@vger.kernel.org Fixes: bf41a158cacba ("ring-buffer: make reentrant") Suggested-by: Linus Torvalds <torvalds@linuxfoundation.org> Signed-off-by: Haoran Luo <www@aegistudio.net> Signed-off-by: Steven Rostedt (VMware) <rostedt@goodmis.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 APar_ExtractDetails(FILE *isofile, uint8_t optional_output) { char uint32_buffer[5]; Trackage track = {0}; AtomicInfo *mvhdAtom = APar_FindAtom("moov.mvhd", false, VERSIONED_ATOM, 0); if (mvhdAtom != NULL) { APar_ExtractMovieDetails(uint32_buffer, isofile, mvhdAtom); fprintf(stdout, "Movie duration: %.3lf seconds (%s) - %.2lf* kbp/sec bitrate " "(*=approximate)\n", movie_info.seconds, secsTOtime(movie_info.seconds), movie_info.simple_bitrate_calc); if (optional_output & SHOW_DATE_INFO) { fprintf(stdout, " Presentation Creation Date (UTC): %s\n", APar_extract_UTC(movie_info.creation_time)); fprintf(stdout, " Presentation Modification Date (UTC): %s\n", APar_extract_UTC(movie_info.modified_time)); } } AtomicInfo *iodsAtom = APar_FindAtom("moov.iods", false, VERSIONED_ATOM, 0); if (iodsAtom != NULL) { movie_info.contains_iods = true; APar_Extract_iods_Info(isofile, iodsAtom); } if (optional_output & SHOW_TRACK_INFO) { APar_TrackLevelInfo(&track, NULL); // With track_num set to 0, it will return the // total trak atom into total_tracks here. fprintf( stdout, "Low-level details. Total tracks: %u\n", track.total_tracks); fprintf(stdout, "Trk Type Handler Kind Lang Bytes\n"); if (track.total_tracks > 0) { while (track.total_tracks > track.track_num) { track.track_num += 1; TrackInfo track_info = {0}; // tracknum, handler type, handler name APar_ExtractTrackDetails(uint32_buffer, isofile, &track, &track_info); uint16_t more_whitespace = purge_extraneous_characters(track_info.track_hdlr_name); if (strlen(track_info.track_hdlr_name) == 0) { memcpy(track_info.track_hdlr_name, "[none listed]", 13); } fprintf(stdout, "%u %s %s", track.track_num, uint32tochar4(track_info.track_type, uint32_buffer), track_info.track_hdlr_name); uint16_t handler_len = strlen(track_info.track_hdlr_name); if (handler_len < 25 + more_whitespace) { for (uint16_t i = handler_len; i < 25 + more_whitespace; i++) { fprintf(stdout, " "); } } // codec, language fprintf(stdout, " %s %s %" PRIu64, uint32tochar4(track_info.track_codec, uint32_buffer), track_info.unpacked_lang, track_info.sample_aggregate); if (track_info.encoder_name[0] != 0 && track_info.contains_esds) { purge_extraneous_characters(track_info.encoder_name); fprintf(stdout, " Encoder: %s", track_info.encoder_name); } if (track_info.type_of_track & DRM_PROTECTED_TRACK) { fprintf(stdout, " (protected %s)", uint32tochar4(track_info.protected_codec, uint32_buffer)); } fprintf(stdout, "\n"); /*---------------------------------*/ if (track_info.type_of_track & VIDEO_TRACK || track_info.type_of_track & AUDIO_TRACK) { APar_Print_TrackDetails(&track_info); } if (optional_output & SHOW_DATE_INFO) { fprintf(stdout, " Creation Date (UTC): %s\n", APar_extract_UTC(track_info.creation_time)); fprintf(stdout, " Modification Date (UTC): %s\n", APar_extract_UTC(track_info.modified_time)); } } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Avoid stack overflow refs: https://github.com/wez/atomicparsley/issues/32'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: process_copy_in () { FILE *tty_in = NULL; /* Interactive file for rename option. */ FILE *tty_out = NULL; /* Interactive file for rename option. */ FILE *rename_in = NULL; /* Batch file for rename option. */ struct stat file_stat; /* Output file stat record. */ struct cpio_file_stat file_hdr = CPIO_FILE_STAT_INITIALIZER; /* Output header information. */ int in_file_des; /* Input file descriptor. */ char skip_file; /* Flag for use with patterns. */ int i; /* Loop index variable. */ newdir_umask = umask (0); /* Reset umask to preserve modes of created files */ /* Initialize the copy in. */ if (pattern_file_name) { read_pattern_file (); } if (rename_batch_file) { rename_in = fopen (rename_batch_file, "r"); if (rename_in == NULL) { error (PAXEXIT_FAILURE, errno, TTY_NAME); } } else if (rename_flag) { /* Open interactive file pair for rename operation. */ tty_in = fopen (TTY_NAME, "r"); if (tty_in == NULL) { error (PAXEXIT_FAILURE, errno, TTY_NAME); } tty_out = fopen (TTY_NAME, "w"); if (tty_out == NULL) { error (PAXEXIT_FAILURE, errno, TTY_NAME); } } /* Get date and time if needed for processing the table option. */ if (table_flag && verbose_flag) { time (&current_time); } /* Check whether the input file might be a tape. */ in_file_des = archive_des; if (_isrmt (in_file_des)) { input_is_special = 1; input_is_seekable = 0; } else { if (fstat (in_file_des, &file_stat)) error (PAXEXIT_FAILURE, errno, _("standard input is closed")); input_is_special = #ifdef S_ISBLK S_ISBLK (file_stat.st_mode) || #endif S_ISCHR (file_stat.st_mode); input_is_seekable = S_ISREG (file_stat.st_mode); } output_is_seekable = true; change_dir (); /* While there is more input in the collection, process the input. */ while (1) { swapping_halfwords = swapping_bytes = false; /* Start processing the next file by reading the header. */ read_in_header (&file_hdr, in_file_des); #ifdef DEBUG_CPIO if (debug_flag) { struct cpio_file_stat *h; h = &file_hdr; fprintf (stderr, "magic = 0%o, ino = %ld, mode = 0%o, uid = %d, gid = %d\n", h->c_magic, (long)h->c_ino, h->c_mode, h->c_uid, h->c_gid); fprintf (stderr, "nlink = %d, mtime = %d, filesize = %d, dev_maj = 0x%x\n", h->c_nlink, h->c_mtime, h->c_filesize, h->c_dev_maj); fprintf (stderr, "dev_min = 0x%x, rdev_maj = 0x%x, rdev_min = 0x%x, namesize = %d\n", h->c_dev_min, h->c_rdev_maj, h->c_rdev_min, h->c_namesize); fprintf (stderr, "chksum = %d, name = \"%s\", tar_linkname = \"%s\"\n", h->c_chksum, h->c_name, h->c_tar_linkname ? h->c_tar_linkname : "(null)" ); } #endif if (file_hdr.c_namesize == 0) skip_file = true; else { /* Is this the header for the TRAILER file? */ if (strcmp (CPIO_TRAILER_NAME, file_hdr.c_name) == 0) break; cpio_safer_name_suffix (file_hdr.c_name, false, !no_abs_paths_flag, false); /* Does the file name match one of the given patterns? */ if (num_patterns <= 0) skip_file = false; else { skip_file = copy_matching_files; for (i = 0; i < num_patterns && skip_file == copy_matching_files; i++) { if (fnmatch (save_patterns[i], file_hdr.c_name, 0) == 0) skip_file = !copy_matching_files; } } } if (skip_file) { /* If we're skipping a file with links, there might be other links that we didn't skip, and this file might have the data for the links. If it does, we'll copy in the data to the links, but not to this file. */ if (file_hdr.c_nlink > 1 && (archive_format == arf_newascii || archive_format == arf_crcascii) ) { if (create_defered_links_to_skipped(&file_hdr, in_file_des) < 0) { tape_toss_input (in_file_des, file_hdr.c_filesize); tape_skip_padding (in_file_des, file_hdr.c_filesize); } } else { tape_toss_input (in_file_des, file_hdr.c_filesize); tape_skip_padding (in_file_des, file_hdr.c_filesize); } } else if (table_flag) { list_file (&file_hdr, in_file_des); } else if (append_flag) { tape_toss_input (in_file_des, file_hdr.c_filesize); tape_skip_padding (in_file_des, file_hdr.c_filesize); } else if (only_verify_crc_flag) { #ifdef CP_IFLNK if ((file_hdr.c_mode & CP_IFMT) == CP_IFLNK) { if (archive_format != arf_tar && archive_format != arf_ustar) { tape_toss_input (in_file_des, file_hdr.c_filesize); tape_skip_padding (in_file_des, file_hdr.c_filesize); continue; } } #endif crc = 0; tape_toss_input (in_file_des, file_hdr.c_filesize); tape_skip_padding (in_file_des, file_hdr.c_filesize); if (crc != file_hdr.c_chksum) { error (0, 0, _("%s: checksum error (0x%x, should be 0x%x)"), file_hdr.c_name, crc, file_hdr.c_chksum); } /* Debian hack: -v and -V now work with --only-verify-crc. (99/11/10) -BEM */ if (verbose_flag) { fprintf (stderr, "%s\n", file_hdr.c_name); } if (dot_flag) { fputc ('.', stderr); } } else { /* Copy the input file into the directory structure. */ /* Do we need to rename the file? */ if (rename_flag || rename_batch_file) { if (query_rename(&file_hdr, tty_in, tty_out, rename_in) < 0) { tape_toss_input (in_file_des, file_hdr.c_filesize); tape_skip_padding (in_file_des, file_hdr.c_filesize); continue; } } copyin_file(&file_hdr, in_file_des); if (verbose_flag) fprintf (stderr, "%s\n", file_hdr.c_name); if (dot_flag) fputc ('.', stderr); } } if (dot_flag) fputc ('\n', stderr); apply_delayed_set_stat (); cpio_file_stat_free (&file_hdr); if (append_flag) return; if (archive_format == arf_newascii || archive_format == arf_crcascii) { create_final_defers (); } if (!quiet_flag) { size_t blocks; blocks = (input_bytes + io_block_size - 1) / io_block_size; fprintf (stderr, ngettext ("%lu block\n", "%lu blocks\n", (unsigned long) blocks), (unsigned long) blocks); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Rewrite dynamic string support. * src/dstring.c (ds_init): Take a single argument. (ds_free): New function. (ds_resize): Take a single argument. Use x2nrealloc to expand the storage. (ds_reset,ds_append,ds_concat,ds_endswith): New function. (ds_fgetstr): Rewrite. In particular, this fixes integer overflow. * src/dstring.h (dynamic_string): Keep both the allocated length (ds_size) and index of the next free byte in the string (ds_idx). (ds_init,ds_resize): Change signature. (ds_len): New macro. (ds_free,ds_reset,ds_append,ds_concat,ds_endswith): New protos. * src/copyin.c: Use new ds_ functions. * src/copyout.c: Likewise. * src/copypass.c: Likewise. * src/util.c: Likewise.'</s>
<s>[INST] Given the following code containing errors, provide 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 check_system_chunk(struct btrfs_trans_handle *trans, u64 type) { struct btrfs_transaction *cur_trans = trans->transaction; struct btrfs_fs_info *fs_info = trans->fs_info; struct btrfs_space_info *info; u64 left; u64 thresh; int ret = 0; u64 num_devs; /* * Needed because we can end up allocating a system chunk and for an * atomic and race free space reservation in the chunk block reserve. */ lockdep_assert_held(&fs_info->chunk_mutex); info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM); again: spin_lock(&info->lock); left = info->total_bytes - btrfs_space_info_used(info, true); spin_unlock(&info->lock); num_devs = get_profile_num_devs(fs_info, type); /* num_devs device items to update and 1 chunk item to add or remove */ thresh = btrfs_calc_metadata_size(fs_info, num_devs) + btrfs_calc_insert_metadata_size(fs_info, 1); if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) { btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu", left, thresh, type); btrfs_dump_space_info(fs_info, info, 0, 0); } if (left < thresh) { u64 flags = btrfs_system_alloc_profile(fs_info); u64 reserved = atomic64_read(&cur_trans->chunk_bytes_reserved); /* * If there's not available space for the chunk tree (system * space) and there are other tasks that reserved space for * creating a new system block group, wait for them to complete * the creation of their system block group and release excess * reserved space. We do this because: * * *) We can end up allocating more system chunks than necessary * when there are multiple tasks that are concurrently * allocating block groups, which can lead to exhaustion of * the system array in the superblock; * * *) If we allocate extra and unnecessary system block groups, * despite being empty for a long time, and possibly forever, * they end not being added to the list of unused block groups * because that typically happens only when deallocating the * last extent from a block group - which never happens since * we never allocate from them in the first place. The few * exceptions are when mounting a filesystem or running scrub, * which add unused block groups to the list of unused block * groups, to be deleted by the cleaner kthread. * And even when they are added to the list of unused block * groups, it can take a long time until they get deleted, * since the cleaner kthread might be sleeping or busy with * other work (deleting subvolumes, running delayed iputs, * defrag scheduling, etc); * * This is rare in practice, but can happen when too many tasks * are allocating blocks groups in parallel (via fallocate()) * and before the one that reserved space for a new system block * group finishes the block group creation and releases the space * reserved in excess (at btrfs_create_pending_block_groups()), * other tasks end up here and see free system space temporarily * not enough for updating the chunk tree. * * We unlock the chunk mutex before waiting for such tasks and * lock it again after the wait, otherwise we would deadlock. * It is safe to do so because allocating a system chunk is the * first thing done while allocating a new block group. */ if (reserved > trans->chunk_bytes_reserved) { const u64 min_needed = reserved - thresh; mutex_unlock(&fs_info->chunk_mutex); wait_event(cur_trans->chunk_reserve_wait, atomic64_read(&cur_trans->chunk_bytes_reserved) <= min_needed); mutex_lock(&fs_info->chunk_mutex); goto again; } /* * Ignore failure to create system chunk. We might end up not * needing it, as we might not need to COW all nodes/leafs from * the paths we visit in the chunk tree (they were already COWed * or created in the current transaction for example). */ ret = btrfs_alloc_chunk(trans, flags); } if (!ret) { ret = btrfs_block_rsv_add(fs_info->chunk_root, &fs_info->chunk_block_rsv, thresh, BTRFS_RESERVE_NO_FLUSH); if (!ret) { atomic64_add(thresh, &cur_trans->chunk_bytes_reserved); trans->chunk_bytes_reserved += thresh; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-667'], 'message': 'btrfs: fix deadlock with concurrent chunk allocations involving system chunks When a task attempting to allocate a new chunk verifies that there is not currently enough free space in the system space_info and there is another task that allocated a new system chunk but it did not finish yet the creation of the respective block group, it waits for that other task to finish creating the block group. This is to avoid exhaustion of the system chunk array in the superblock, which is limited, when we have a thundering herd of tasks allocating new chunks. This problem was described and fixed by commit eafa4fd0ad0607 ("btrfs: fix exhaustion of the system chunk array due to concurrent allocations"). However there are two very similar scenarios where this can lead to a deadlock: 1) Task B allocated a new system chunk and task A is waiting on task B to finish creation of the respective system block group. However before task B ends its transaction handle and finishes the creation of the system block group, it attempts to allocate another chunk (like a data chunk for an fallocate operation for a very large range). Task B will be unable to progress and allocate the new chunk, because task A set space_info->chunk_alloc to 1 and therefore it loops at btrfs_chunk_alloc() waiting for task A to finish its chunk allocation and set space_info->chunk_alloc to 0, but task A is waiting on task B to finish creation of the new system block group, therefore resulting in a deadlock; 2) Task B allocated a new system chunk and task A is waiting on task B to finish creation of the respective system block group. By the time that task B enter the final phase of block group allocation, which happens at btrfs_create_pending_block_groups(), when it modifies the extent tree, the device tree or the chunk tree to insert the items for some new block group, it needs to allocate a new chunk, so it ends up at btrfs_chunk_alloc() and keeps looping there because task A has set space_info->chunk_alloc to 1, but task A is waiting for task B to finish creation of the new system block group and release the reserved system space, therefore resulting in a deadlock. In short, the problem is if a task B needs to allocate a new chunk after it previously allocated a new system chunk and if another task A is currently waiting for task B to complete the allocation of the new system chunk. Unfortunately this deadlock scenario introduced by the previous fix for the system chunk array exhaustion problem does not have a simple and short fix, and requires a big change to rework the chunk allocation code so that chunk btree updates are all made in the first phase of chunk allocation. And since this deadlock regression is being frequently hit on zoned filesystems and the system chunk array exhaustion problem is triggered in more extreme cases (originally observed on PowerPC with a node size of 64K when running the fallocate tests from stress-ng), revert the changes from that commit. The next patch in the series, with a subject of "btrfs: rework chunk allocation to avoid exhaustion of the system chunk array" does the necessary changes to fix the system chunk array exhaustion problem. Reported-by: Naohiro Aota <naohiro.aota@wdc.com> Link: https://lore.kernel.org/linux-btrfs/20210621015922.ewgbffxuawia7liz@naota-xeon/ Fixes: eafa4fd0ad0607 ("btrfs: fix exhaustion of the system chunk array due to concurrent allocations") CC: stable@vger.kernel.org # 5.12+ Tested-by: Shin'ichiro Kawasaki <shinichiro.kawasaki@wdc.com> Tested-by: Naohiro Aota <naohiro.aota@wdc.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Tested-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.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 nf_conntrack_standalone_init_sysctl(struct net *net) { struct nf_conntrack_net *cnet = net_generic(net, nf_conntrack_net_id); struct nf_udp_net *un = nf_udp_pernet(net); struct ctl_table *table; BUILD_BUG_ON(ARRAY_SIZE(nf_ct_sysctl_table) != NF_SYSCTL_CT_LAST_SYSCTL); table = kmemdup(nf_ct_sysctl_table, sizeof(nf_ct_sysctl_table), GFP_KERNEL); if (!table) return -ENOMEM; table[NF_SYSCTL_CT_COUNT].data = &net->ct.count; table[NF_SYSCTL_CT_CHECKSUM].data = &net->ct.sysctl_checksum; table[NF_SYSCTL_CT_LOG_INVALID].data = &net->ct.sysctl_log_invalid; table[NF_SYSCTL_CT_ACCT].data = &net->ct.sysctl_acct; table[NF_SYSCTL_CT_HELPER].data = &net->ct.sysctl_auto_assign_helper; #ifdef CONFIG_NF_CONNTRACK_EVENTS table[NF_SYSCTL_CT_EVENTS].data = &net->ct.sysctl_events; #endif #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP table[NF_SYSCTL_CT_TIMESTAMP].data = &net->ct.sysctl_tstamp; #endif table[NF_SYSCTL_CT_PROTO_TIMEOUT_GENERIC].data = &nf_generic_pernet(net)->timeout; table[NF_SYSCTL_CT_PROTO_TIMEOUT_ICMP].data = &nf_icmp_pernet(net)->timeout; table[NF_SYSCTL_CT_PROTO_TIMEOUT_ICMPV6].data = &nf_icmpv6_pernet(net)->timeout; table[NF_SYSCTL_CT_PROTO_TIMEOUT_UDP].data = &un->timeouts[UDP_CT_UNREPLIED]; table[NF_SYSCTL_CT_PROTO_TIMEOUT_UDP_STREAM].data = &un->timeouts[UDP_CT_REPLIED]; nf_conntrack_standalone_init_tcp_sysctl(net, table); nf_conntrack_standalone_init_sctp_sysctl(net, table); nf_conntrack_standalone_init_dccp_sysctl(net, table); nf_conntrack_standalone_init_gre_sysctl(net, table); /* Don't allow unprivileged users to alter certain sysctls */ if (net->user_ns != &init_user_ns) { table[NF_SYSCTL_CT_MAX].mode = 0444; table[NF_SYSCTL_CT_EXPECT_MAX].mode = 0444; table[NF_SYSCTL_CT_HELPER].mode = 0444; #ifdef CONFIG_NF_CONNTRACK_EVENTS table[NF_SYSCTL_CT_EVENTS].mode = 0444; #endif table[NF_SYSCTL_CT_BUCKETS].mode = 0444; } else if (!net_eq(&init_net, net)) { table[NF_SYSCTL_CT_BUCKETS].mode = 0444; } cnet->sysctl_header = register_net_sysctl(net, "net/netfilter", table); if (!cnet->sysctl_header) goto out_unregister_netfilter; return 0; out_unregister_netfilter: kfree(table); return -ENOMEM; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-203'], 'message': 'netfilter: conntrack: Make global sysctls readonly in non-init netns These sysctls point to global variables: - NF_SYSCTL_CT_MAX (&nf_conntrack_max) - NF_SYSCTL_CT_EXPECT_MAX (&nf_ct_expect_max) - NF_SYSCTL_CT_BUCKETS (&nf_conntrack_htable_size_user) Because their data pointers are not updated to point to per-netns structures, they must be marked read-only in a non-init_net ns. Otherwise, changes in any net namespace are reflected in (leaked into) all other net namespaces. This problem has existed since the introduction of net namespaces. The current logic marks them read-only only if the net namespace is owned by an unprivileged user (other than init_user_ns). Commit d0febd81ae77 ("netfilter: conntrack: re-visit sysctls in unprivileged namespaces") "exposes all sysctls even if the namespace is unpriviliged." Since we need to mark them readonly in any case, we can forego the unprivileged user check altogether. Fixes: d0febd81ae77 ("netfilter: conntrack: re-visit sysctls in unprivileged namespaces") Signed-off-by: Jonathon Reinhart <Jonathon.Reinhart@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int h2_make_htx_request(struct http_hdr *list, struct htx *htx, unsigned int *msgf, unsigned long long *body_len) { struct ist phdr_val[H2_PHDR_NUM_ENTRIES]; uint32_t fields; /* bit mask of H2_PHDR_FND_* */ uint32_t idx; int ck, lck; /* cookie index and last cookie index */ int phdr; int ret; int i; struct htx_sl *sl = NULL; unsigned int sl_flags = 0; const char *ctl; lck = ck = -1; // no cookie for now fields = 0; for (idx = 0; list[idx].n.len != 0; idx++) { if (!list[idx].n.ptr) { /* this is an indexed pseudo-header */ phdr = list[idx].n.len; } else { /* this can be any type of header */ /* RFC7540#8.1.2: upper case not allowed in header field names. * #10.3: header names must be valid (i.e. match a token). * For pseudo-headers we check from 2nd char and for other ones * from the first char, because HTTP_IS_TOKEN() also excludes * the colon. */ phdr = h2_str_to_phdr(list[idx].n); for (i = !!phdr; i < list[idx].n.len; i++) if ((uint8_t)(list[idx].n.ptr[i] - 'A') < 'Z' - 'A' || !HTTP_IS_TOKEN(list[idx].n.ptr[i])) goto fail; } /* RFC7540#10.3: intermediaries forwarding to HTTP/1 must take care of * rejecting NUL, CR and LF characters. */ ctl = ist_find_ctl(list[idx].v); if (unlikely(ctl) && has_forbidden_char(list[idx].v, ctl)) goto fail; if (phdr > 0 && phdr < H2_PHDR_NUM_ENTRIES) { /* insert a pseudo header by its index (in phdr) and value (in value) */ if (fields & ((1 << phdr) | H2_PHDR_FND_NONE)) { if (fields & H2_PHDR_FND_NONE) { /* pseudo header field after regular headers */ goto fail; } else { /* repeated pseudo header field */ goto fail; } } fields |= 1 << phdr; phdr_val[phdr] = list[idx].v; continue; } else if (phdr != 0) { /* invalid pseudo header -- should never happen here */ goto fail; } /* regular header field in (name,value) */ if (unlikely(!(fields & H2_PHDR_FND_NONE))) { /* no more pseudo-headers, time to build the request line */ sl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf); if (!sl) goto fail; fields |= H2_PHDR_FND_NONE; } if (isteq(list[idx].n, ist("host"))) fields |= H2_PHDR_FND_HOST; if (isteq(list[idx].n, ist("content-length"))) { ret = h2_parse_cont_len_header(msgf, &list[idx].v, body_len); if (ret < 0) goto fail; sl_flags |= HTX_SL_F_CLEN; if (ret == 0) continue; // skip this duplicate } /* these ones are forbidden in requests (RFC7540#8.1.2.2) */ if (isteq(list[idx].n, ist("connection")) || isteq(list[idx].n, ist("proxy-connection")) || isteq(list[idx].n, ist("keep-alive")) || isteq(list[idx].n, ist("upgrade")) || isteq(list[idx].n, ist("transfer-encoding"))) goto fail; if (isteq(list[idx].n, ist("te")) && !isteq(list[idx].v, ist("trailers"))) goto fail; /* cookie requires special processing at the end */ if (isteq(list[idx].n, ist("cookie"))) { list[idx].n.len = -1; if (ck < 0) ck = idx; else list[lck].n.len = idx; lck = idx; continue; } if (!htx_add_header(htx, list[idx].n, list[idx].v)) goto fail; } /* RFC7540#8.1.2.1 mandates to reject response pseudo-headers (:status) */ if (fields & H2_PHDR_FND_STAT) goto fail; /* Let's dump the request now if not yet emitted. */ if (!(fields & H2_PHDR_FND_NONE)) { sl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf); if (!sl) goto fail; } if (*msgf & H2_MSGF_BODY_TUNNEL) *msgf &= ~(H2_MSGF_BODY|H2_MSGF_BODY_CL); if (!(*msgf & H2_MSGF_BODY) || ((*msgf & H2_MSGF_BODY_CL) && *body_len == 0) || (*msgf & H2_MSGF_BODY_TUNNEL)) { /* Request without body or tunnel requested */ sl_flags |= HTX_SL_F_BODYLESS; htx->flags |= HTX_FL_EOM; } if (*msgf & H2_MSGF_EXT_CONNECT) { if (!htx_add_header(htx, ist("upgrade"), phdr_val[H2_PHDR_IDX_PROT])) goto fail; if (!htx_add_header(htx, ist("connection"), ist("upgrade"))) goto fail; sl_flags |= HTX_SL_F_CONN_UPG; } /* update the start line with last detected header info */ sl->flags |= sl_flags; /* complete with missing Host if needed */ if ((fields & (H2_PHDR_FND_HOST|H2_PHDR_FND_AUTH)) == H2_PHDR_FND_AUTH) { /* missing Host field, use :authority instead */ if (!htx_add_header(htx, ist("host"), phdr_val[H2_PHDR_IDX_AUTH])) goto fail; } /* now we may have to build a cookie list. We'll dump the values of all * visited headers. */ if (ck >= 0) { uint32_t fs; // free space uint32_t bs; // block size uint32_t vl; // value len uint32_t tl; // total length struct htx_blk *blk; blk = htx_add_header(htx, ist("cookie"), list[ck].v); if (!blk) goto fail; tl = list[ck].v.len; fs = htx_free_data_space(htx); bs = htx_get_blksz(blk); /* for each extra cookie, we'll extend the cookie's value and * insert "; " before the new value. */ fs += tl; // first one is already counted while ((ck = list[ck].n.len) >= 0) { vl = list[ck].v.len; tl += vl + 2; if (tl > fs) goto fail; htx_change_blk_value_len(htx, blk, tl); *(char *)(htx_get_blk_ptr(htx, blk) + bs + 0) = ';'; *(char *)(htx_get_blk_ptr(htx, blk) + bs + 1) = ' '; memcpy(htx_get_blk_ptr(htx, blk) + bs + 2, list[ck].v.ptr, vl); bs += vl + 2; } } /* now send the end of headers marker */ if (!htx_add_endof(htx, HTX_BLK_EOH)) goto fail; /* proceed to scheme-based normalization on target-URI */ if (fields & H2_PHDR_FND_SCHM) http_scheme_based_normalize(htx); ret = 1; return ret; fail: return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-755'], 'message': 'BUG/MEDIUM: h2: give :authority precedence over Host The wording regarding Host vs :authority in RFC7540 is ambiguous as it says that an intermediary must produce a host header from :authority if Host is missing, but, contrary to HTTP/1.1, doesn't say anything regarding the possibility that Host and :authority differ, which leaves Host with higher precedence there. In addition it mentions that clients should use :authority *instead* of Host, and that H1->H2 should use :authority only if the original request was in authority form. This leaves some gray area in the middle of the chain for fully valid H2 requests arboring a Host header that are forwarded to the other side where it's possible to drop the Host header and use the authority only after forwarding to a second H2 layer, thus possibly seeing two different values of Host at a different stage. There's no such issue when forwarding from H2 to H1 as the authority is dropped only only the Host is kept. Note that the following request is sufficient to re-normalize such a request: http-request set-header host %[req.hdr(host)] The new spec in progress (draft-ietf-httpbis-http2bis-03) addresses this trouble by being a bit is stricter on these rules. It clarifies that :authority must always be used instead of Host and that Host ought to be ignored. This is much saner as it avoids to convey two distinct values along the chain. This becomes the protocol-level equivalent of: http-request set-uri %[url] So this patch does exactly this, which we were initially a bit reluctant to do initially by lack of visibility about other implementations' expectations. In addition it slightly simplifies the Host header field creation by always placing it first in the list of headers instead of last; this could also speed up the look up a little bit. This needs to be backported to 2.0. Non-HTX versions are safe regarding this because they drop the URI during the conversion to HTTP/1.1 so only Host is used and transmitted. Thanks to Tim D�sterhus for reporting that one.'</s>
<s>[INST] Given the following code containing errors, provide 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 dir *squashfs_opendir(unsigned int block_start, unsigned int offset, struct inode **i) { squashfs_dir_header_3 dirh; char buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1] __attribute__((aligned)); squashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer; long long start; int bytes; int dir_count, size; struct dir_ent *new_dir; struct dir *dir; TRACE("squashfs_opendir: inode start block %d, offset %d\n", block_start, offset); *i = read_inode(block_start, offset); dir = malloc(sizeof(struct dir)); if(dir == NULL) EXIT_UNSQUASH("squashfs_opendir: malloc failed!\n"); dir->dir_count = 0; dir->cur_entry = 0; dir->mode = (*i)->mode; dir->uid = (*i)->uid; dir->guid = (*i)->gid; dir->mtime = (*i)->time; dir->xattr = (*i)->xattr; dir->dirs = NULL; if ((*i)->data == 3) /* * if the directory is empty, skip the unnecessary * lookup_entry, this fixes the corner case with * completely empty filesystems where lookup_entry correctly * returning -1 is incorrectly treated as an error */ return dir; start = sBlk.s.directory_table_start + (*i)->start; bytes = lookup_entry(directory_table_hash, start); if(bytes == -1) EXIT_UNSQUASH("squashfs_opendir: directory block %d not " "found!\n", block_start); bytes += (*i)->offset; size = (*i)->data + bytes - 3; while(bytes < size) { if(swap) { squashfs_dir_header_3 sdirh; memcpy(&sdirh, directory_table + bytes, sizeof(sdirh)); SQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh); } else memcpy(&dirh, directory_table + bytes, sizeof(dirh)); dir_count = dirh.count + 1; TRACE("squashfs_opendir: Read directory header @ byte position " "%d, %d directory entries\n", bytes, dir_count); bytes += sizeof(dirh); /* dir_count should never be larger than SQUASHFS_DIR_COUNT */ if(dir_count > SQUASHFS_DIR_COUNT) { ERROR("File system corrupted: too many entries in directory\n"); goto corrupted; } while(dir_count--) { if(swap) { squashfs_dir_entry_3 sdire; memcpy(&sdire, directory_table + bytes, sizeof(sdire)); SQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire); } else memcpy(dire, directory_table + bytes, sizeof(*dire)); bytes += sizeof(*dire); /* size should never be SQUASHFS_NAME_LEN or larger */ if(dire->size >= SQUASHFS_NAME_LEN) { ERROR("File system corrupted: filename too long\n"); goto corrupted; } memcpy(dire->name, directory_table + bytes, dire->size + 1); dire->name[dire->size + 1] = '\0'; TRACE("squashfs_opendir: directory entry %s, inode " "%d:%d, type %d\n", dire->name, dirh.start_block, dire->offset, dire->type); if((dir->dir_count % DIR_ENT_SIZE) == 0) { new_dir = realloc(dir->dirs, (dir->dir_count + DIR_ENT_SIZE) * sizeof(struct dir_ent)); if(new_dir == NULL) EXIT_UNSQUASH("squashfs_opendir: " "realloc failed!\n"); dir->dirs = new_dir; } strcpy(dir->dirs[dir->dir_count].name, dire->name); dir->dirs[dir->dir_count].start_block = dirh.start_block; dir->dirs[dir->dir_count].offset = dire->offset; dir->dirs[dir->dir_count].type = dire->type; dir->dir_count ++; bytes += dire->size + 1; } } return dir; corrupted: free(dir->dirs); free(dir); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'Unsquashfs: fix write outside destination directory exploit An issue on Github (https://github.com/plougher/squashfs-tools/issues/72) shows how some specially crafted Squashfs filesystems containing invalid file names (with '/' and ..) can cause Unsquashfs to write files outside of the destination directory. This commit fixes this exploit by checking all names for validity. In doing so I have also added checks for '.' and for names that are shorter than they should be (names in the file system should not have '\0' terminators). Signed-off-by: Phillip Lougher <phillip@squashfs.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: static int dissect_dvb_s2_bb(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) { proto_item *ti; proto_tree *dvb_s2_bb_tree; guint8 input8, matype1; guint8 sync_flag = 0; guint16 input16, bb_data_len = 0, user_packet_length; int sub_dissected = 0, flag_is_ms = 0, new_off = 0; static int * const bb_header_bitfields[] = { &hf_dvb_s2_bb_matype1_gs, &hf_dvb_s2_bb_matype1_mis, &hf_dvb_s2_bb_matype1_acm, &hf_dvb_s2_bb_matype1_issyi, &hf_dvb_s2_bb_matype1_npd, &hf_dvb_s2_bb_matype1_low_ro, NULL }; col_append_str(pinfo->cinfo, COL_PROTOCOL, "BB "); col_append_str(pinfo->cinfo, COL_INFO, "Baseband "); /* create display subtree for the protocol */ ti = proto_tree_add_item(tree, proto_dvb_s2_bb, tvb, 0, DVB_S2_BB_HEADER_LEN, ENC_NA); dvb_s2_bb_tree = proto_item_add_subtree(ti, ett_dvb_s2_bb); matype1 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1); new_off += 1; if (BIT_IS_CLEAR(matype1, DVB_S2_BB_MIS_POS)) flag_is_ms = 1; proto_tree_add_bitmask_with_flags(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_MATYPE1, hf_dvb_s2_bb_matype1, ett_dvb_s2_bb_matype1, bb_header_bitfields, ENC_BIG_ENDIAN, BMT_NO_FLAGS); input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE1); if ((pinfo->fd->num == 1) && (_use_low_rolloff_value != 0)) { _use_low_rolloff_value = 0; } if (((input8 & 0x03) == 3) && !_use_low_rolloff_value) { _use_low_rolloff_value = 1; } if (_use_low_rolloff_value) { proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_low_ro, tvb, DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN); } else { proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_matype1_high_ro, tvb, DVB_S2_BB_OFFS_MATYPE1, 1, ENC_BIG_ENDIAN); } input8 = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_MATYPE2); new_off += 1; if (flag_is_ms) { proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb, DVB_S2_BB_OFFS_MATYPE2, 1, input8, "Input Stream Identifier (ISI): %d", input8); } else { proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_matype2, tvb, DVB_S2_BB_OFFS_MATYPE2, 1, input8, "reserved"); } user_packet_length = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_UPL); new_off += 2; proto_tree_add_uint_format(dvb_s2_bb_tree, hf_dvb_s2_bb_upl, tvb, DVB_S2_BB_OFFS_UPL, 2, input16, "User Packet Length: %d bits (%d bytes)", (guint16) input16, (guint16) input16 / 8); bb_data_len = input16 = tvb_get_ntohs(tvb, DVB_S2_BB_OFFS_DFL); bb_data_len /= 8; new_off += 2; proto_tree_add_uint_format_value(dvb_s2_bb_tree, hf_dvb_s2_bb_dfl, tvb, DVB_S2_BB_OFFS_DFL, 2, input16, "%d bits (%d bytes)", input16, input16 / 8); new_off += 1; sync_flag = tvb_get_guint8(tvb, DVB_S2_BB_OFFS_SYNC); proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_sync, tvb, DVB_S2_BB_OFFS_SYNC, 1, ENC_BIG_ENDIAN); new_off += 2; proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_syncd, tvb, DVB_S2_BB_OFFS_SYNCD, 2, ENC_BIG_ENDIAN); new_off += 1; proto_tree_add_checksum(dvb_s2_bb_tree, tvb, DVB_S2_BB_OFFS_CRC, hf_dvb_s2_bb_crc, hf_dvb_s2_bb_crc_status, &ei_dvb_s2_bb_crc, pinfo, compute_crc8(tvb, DVB_S2_BB_HEADER_LEN - 1, 0), ENC_NA, PROTO_CHECKSUM_VERIFY); switch (matype1 & DVB_S2_BB_TSGS_MASK) { case DVB_S2_BB_TSGS_GENERIC_CONTINUOUS: /* Check GSE constraints on the BB header per 9.2.1 of ETSI TS 102 771 */ if (BIT_IS_SET(matype1, DVB_S2_BB_ISSYI_POS)) { expert_add_info(pinfo, ti, &ei_dvb_s2_bb_issy_invalid); } if (BIT_IS_SET(matype1, DVB_S2_BB_NPD_POS)) { expert_add_info(pinfo, ti, &ei_dvb_s2_bb_npd_invalid); } if (user_packet_length != 0x0000) { expert_add_info_format(pinfo, ti, &ei_dvb_s2_bb_upl_invalid, "UPL is 0x%04x. It must be 0x0000 for GSE packets.", user_packet_length); } if (dvb_s2_df_dissection) { while (bb_data_len) { if (sync_flag == DVB_S2_BB_SYNC_EIP_CRC32 && bb_data_len == DVB_S2_BB_EIP_CRC32_LEN) { proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_eip_crc32, tvb, new_off, bb_data_len, ENC_NA); bb_data_len = 0; new_off += DVB_S2_BB_EIP_CRC32_LEN; } else { /* start DVB-GSE dissector */ sub_dissected = dissect_dvb_s2_gse(tvb_new_subset_length(tvb, new_off, bb_data_len), pinfo, tree, NULL); new_off += sub_dissected; if ((sub_dissected <= bb_data_len) && (sub_dissected >= DVB_S2_GSE_MINSIZE)) { bb_data_len -= sub_dissected; if (bb_data_len < DVB_S2_GSE_MINSIZE) bb_data_len = 0; } } } } else { proto_tree_add_item(dvb_s2_bb_tree, hf_dvb_s2_bb_df, tvb, new_off, bb_data_len, ENC_NA); new_off += bb_data_len; } break; case DVB_S2_BB_TSGS_GENERIC_PACKETIZED: proto_tree_add_item(tree, hf_dvb_s2_bb_packetized, tvb, new_off, bb_data_len, ENC_NA); new_off += bb_data_len; break; case DVB_S2_BB_TSGS_TRANSPORT_STREAM: proto_tree_add_item(tree, hf_dvb_s2_bb_transport, tvb, new_off, bb_data_len, ENC_NA); new_off += bb_data_len; break; default: proto_tree_add_item(tree, hf_dvb_s2_bb_reserved, tvb, new_off, bb_data_len, ENC_NA); new_off += bb_data_len; expert_add_info(pinfo, ti, &ei_dvb_s2_bb_reserved); break; } return new_off; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'DVB-S2-BB: Prevent infinite loop Commit 4bf4ee88f0544727e7f89f3f288c6afd2f650a4c removed an else statement that broke out of the BBFrame processing loop. Without it, infinite loops might be possible if the GSE frames have bit errors in the length field.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pipe_fopen(gx_io_device * iodev, const char *fname, const char *access, gp_file ** pfile, char *rfname, uint rnamelen, gs_memory_t *mem) { #ifdef GS_NO_FILESYSTEM return 0; #else gs_lib_ctx_t *ctx = mem->gs_lib_ctx; gs_fs_list_t *fs = ctx->core->fs; if (gp_validate_path(mem, fname, access) != 0) return gs_error_invalidfileaccess; /* * Some platforms allow opening a pipe with a '+' in the access * mode, even though pipes are not positionable. Detect this here. */ if (strchr(access, '+')) return_error(gs_error_invalidfileaccess); *pfile = NULL; for (fs = ctx->core->fs; fs != NULL; fs = fs->next) { int code = 0; if (fs->fs.open_pipe) code = fs->fs.open_pipe(mem, fs->secret, fname, rfname, access, pfile); if (code < 0) return code; if (*pfile != NULL) break; } return 0; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Bug 704342: Include device specifier strings in access validation for the "%pipe%", %handle%" and %printer% io devices. We previously validated only the part after the "%pipe%" Postscript device specifier, but this proved insufficient. This rebuilds the original file name string, and validates it complete. The slight complication for "%pipe%" is it can be reached implicitly using "|" so we have to check both prefixes. Addresses CVE-2021-3781'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: nv_replace(cmdarg_T *cap) { char_u *ptr; int had_ctrl_v; long n; if (checkclearop(cap->oap)) return; #ifdef FEAT_JOB_CHANNEL if (bt_prompt(curbuf) && !prompt_curpos_editable()) { clearopbeep(cap->oap); return; } #endif // get another character if (cap->nchar == Ctrl_V) { had_ctrl_v = Ctrl_V; cap->nchar = get_literal(FALSE); // Don't redo a multibyte character with CTRL-V. if (cap->nchar > DEL) had_ctrl_v = NUL; } else had_ctrl_v = NUL; // Abort if the character is a special key. if (IS_SPECIAL(cap->nchar)) { clearopbeep(cap->oap); return; } // Visual mode "r" if (VIsual_active) { if (got_int) reset_VIsual(); if (had_ctrl_v) { // Use a special (negative) number to make a difference between a // literal CR or NL and a line break. if (cap->nchar == CAR) cap->nchar = REPLACE_CR_NCHAR; else if (cap->nchar == NL) cap->nchar = REPLACE_NL_NCHAR; } nv_operator(cap); return; } // Break tabs, etc. if (virtual_active()) { if (u_save_cursor() == FAIL) return; if (gchar_cursor() == NUL) { // Add extra space and put the cursor on the first one. coladvance_force((colnr_T)(getviscol() + cap->count1)); curwin->w_cursor.col -= cap->count1; } else if (gchar_cursor() == TAB) coladvance_force(getviscol()); } // Abort if not enough characters to replace. ptr = ml_get_cursor(); if (STRLEN(ptr) < (unsigned)cap->count1 || (has_mbyte && mb_charlen(ptr) < cap->count1)) { clearopbeep(cap->oap); return; } /* * Replacing with a TAB is done by edit() when it is complicated because * 'expandtab' or 'smarttab' is set. CTRL-V TAB inserts a literal TAB. * Other characters are done below to avoid problems with things like * CTRL-V 048 (for edit() this would be R CTRL-V 0 ESC). */ if (had_ctrl_v != Ctrl_V && cap->nchar == '\t' && (curbuf->b_p_et || p_sta)) { stuffnumReadbuff(cap->count1); stuffcharReadbuff('R'); stuffcharReadbuff('\t'); stuffcharReadbuff(ESC); return; } // save line for undo if (u_save_cursor() == FAIL) return; if (had_ctrl_v != Ctrl_V && (cap->nchar == '\r' || cap->nchar == '\n')) { /* * Replace character(s) by a single newline. * Strange vi behaviour: Only one newline is inserted. * Delete the characters here. * Insert the newline with an insert command, takes care of * autoindent. The insert command depends on being on the last * character of a line or not. */ (void)del_chars(cap->count1, FALSE); // delete the characters stuffcharReadbuff('\r'); stuffcharReadbuff(ESC); // Give 'r' to edit(), to get the redo command right. invoke_edit(cap, TRUE, 'r', FALSE); } else { prep_redo(cap->oap->regname, cap->count1, NUL, 'r', NUL, had_ctrl_v, cap->nchar); curbuf->b_op_start = curwin->w_cursor; if (has_mbyte) { int old_State = State; if (cap->ncharC1 != 0) AppendCharToRedobuff(cap->ncharC1); if (cap->ncharC2 != 0) AppendCharToRedobuff(cap->ncharC2); // This is slow, but it handles replacing a single-byte with a // multi-byte and the other way around. Also handles adding // composing characters for utf-8. for (n = cap->count1; n > 0; --n) { State = REPLACE; if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) { int c = ins_copychar(curwin->w_cursor.lnum + (cap->nchar == Ctrl_Y ? -1 : 1)); if (c != NUL) ins_char(c); else // will be decremented further down ++curwin->w_cursor.col; } else ins_char(cap->nchar); State = old_State; if (cap->ncharC1 != 0) ins_char(cap->ncharC1); if (cap->ncharC2 != 0) ins_char(cap->ncharC2); } } else { /* * Replace the characters within one line. */ for (n = cap->count1; n > 0; --n) { /* * Get ptr again, because u_save and/or showmatch() will have * released the line. At the same time we let know that the * line will be changed. */ ptr = ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE); if (cap->nchar == Ctrl_E || cap->nchar == Ctrl_Y) { int c = ins_copychar(curwin->w_cursor.lnum + (cap->nchar == Ctrl_Y ? -1 : 1)); if (c != NUL) ptr[curwin->w_cursor.col] = c; } else ptr[curwin->w_cursor.col] = cap->nchar; if (p_sm && msg_silent == 0) showmatch(cap->nchar); ++curwin->w_cursor.col; } #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { colnr_T start = (colnr_T)(curwin->w_cursor.col - cap->count1); netbeans_removed(curbuf, curwin->w_cursor.lnum, start, (long)cap->count1); netbeans_inserted(curbuf, curwin->w_cursor.lnum, start, &ptr[start], (int)cap->count1); } #endif // mark the buffer as changed and prepare for displaying changed_bytes(curwin->w_cursor.lnum, (colnr_T)(curwin->w_cursor.col - cap->count1)); } --curwin->w_cursor.col; // cursor on the last replaced char // if the character on the left of the current cursor is a multi-byte // character, move two characters left if (has_mbyte) mb_adjust_cursor(); curbuf->b_op_end = curwin->w_cursor; curwin->w_set_curswant = TRUE; set_last_insert(cap->nchar); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'patch 8.2.3428: using freed memory when replacing Problem: Using freed memory when replacing. (Dhiraj Mishra) Solution: Get the line pointer after calling ins_copychar().'</s>
<s>[INST] Given the following code containing errors, provide 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 timerqueue_del(struct timerqueue_head *head, struct timerqueue_node *node) { WARN_ON_ONCE(RB_EMPTY_NODE(&node->node)); /* update next pointer */ if (head->next == node) { struct rb_node *rbn = rb_next(&node->node); head->next = rb_entry_safe(rbn, struct timerqueue_node, node); } rb_erase(&node->node, &head->head); RB_CLEAR_NODE(&node->node); return head->next != NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-665'], 'message': 'lib/timerqueue: Rely on rbtree semantics for next timer Simplify the timerqueue code by using cached rbtrees and rely on the tree leftmost node semantics to get the timer with earliest expiration time. This is a drop in conversion, and therefore semantics remain untouched. The runtime overhead of cached rbtrees is be pretty much the same as the current head->next method, noting that when removing the leftmost node, a common operation for the timerqueue, the rb_next(leftmost) is O(1) as well, so the next timer will either be the right node or its parent. Therefore no extra pointer chasing. Finally, the size of the struct timerqueue_head remains the same. Passes several hours of rcutorture. Signed-off-by: Davidlohr Bueso <dbueso@suse.de> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Link: https://lkml.kernel.org/r/20190724152323.bojciei3muvfxalm@linux-r8p5'</s>
<s>[INST] Given the following code containing errors, provide 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 processMultibulkBuffer(client *c) { char *newline = NULL; int ok; long long ll; if (c->multibulklen == 0) { /* The client should have been reset */ serverAssertWithInfo(c,NULL,c->argc == 0); /* Multi bulk length cannot be read without a \r\n */ newline = strchr(c->querybuf+c->qb_pos,'\r'); if (newline == NULL) { if (sdslen(c->querybuf)-c->qb_pos > PROTO_INLINE_MAX_SIZE) { addReplyError(c,"Protocol error: too big mbulk count string"); setProtocolError("too big mbulk count string",c); } return C_ERR; } /* Buffer should also contain \n */ if (newline-(c->querybuf+c->qb_pos) > (ssize_t)(sdslen(c->querybuf)-c->qb_pos-2)) return C_ERR; /* We know for sure there is a whole line since newline != NULL, * so go ahead and find out the multi bulk length. */ serverAssertWithInfo(c,NULL,c->querybuf[c->qb_pos] == '*'); ok = string2ll(c->querybuf+1+c->qb_pos,newline-(c->querybuf+1+c->qb_pos),&ll); if (!ok || ll > 1024*1024) { addReplyError(c,"Protocol error: invalid multibulk length"); setProtocolError("invalid mbulk count",c); return C_ERR; } c->qb_pos = (newline-c->querybuf)+2; if (ll <= 0) return C_OK; c->multibulklen = ll; /* Setup argv array on client structure */ if (c->argv) zfree(c->argv); c->argv = zmalloc(sizeof(robj*)*c->multibulklen); c->argv_len_sum = 0; } serverAssertWithInfo(c,NULL,c->multibulklen > 0); while(c->multibulklen) { /* Read bulk length if unknown */ if (c->bulklen == -1) { newline = strchr(c->querybuf+c->qb_pos,'\r'); if (newline == NULL) { if (sdslen(c->querybuf)-c->qb_pos > PROTO_INLINE_MAX_SIZE) { addReplyError(c, "Protocol error: too big bulk count string"); setProtocolError("too big bulk count string",c); return C_ERR; } break; } /* Buffer should also contain \n */ if (newline-(c->querybuf+c->qb_pos) > (ssize_t)(sdslen(c->querybuf)-c->qb_pos-2)) break; if (c->querybuf[c->qb_pos] != '$') { addReplyErrorFormat(c, "Protocol error: expected '$', got '%c'", c->querybuf[c->qb_pos]); setProtocolError("expected $ but got something else",c); return C_ERR; } ok = string2ll(c->querybuf+c->qb_pos+1,newline-(c->querybuf+c->qb_pos+1),&ll); if (!ok || ll < 0 || (!(c->flags & CLIENT_MASTER) && ll > server.proto_max_bulk_len)) { addReplyError(c,"Protocol error: invalid bulk length"); setProtocolError("invalid bulk length",c); return C_ERR; } c->qb_pos = newline-c->querybuf+2; if (ll >= PROTO_MBULK_BIG_ARG) { /* If we are going to read a large object from network * try to make it likely that it will start at c->querybuf * boundary so that we can optimize object creation * avoiding a large copy of data. * * But only when the data we have not parsed is less than * or equal to ll+2. If the data length is greater than * ll+2, trimming querybuf is just a waste of time, because * at this time the querybuf contains not only our bulk. */ if (sdslen(c->querybuf)-c->qb_pos <= (size_t)ll+2) { sdsrange(c->querybuf,c->qb_pos,-1); c->qb_pos = 0; /* Hint the sds library about the amount of bytes this string is * going to contain. */ c->querybuf = sdsMakeRoomFor(c->querybuf,ll+2-sdslen(c->querybuf)); } } c->bulklen = ll; } /* Read bulk argument */ if (sdslen(c->querybuf)-c->qb_pos < (size_t)(c->bulklen+2)) { /* Not enough data (+2 == trailing \r\n) */ break; } else { /* Optimization: if the buffer contains JUST our bulk element * instead of creating a new object by *copying* the sds we * just use the current sds string. */ if (c->qb_pos == 0 && c->bulklen >= PROTO_MBULK_BIG_ARG && sdslen(c->querybuf) == (size_t)(c->bulklen+2)) { c->argv[c->argc++] = createObject(OBJ_STRING,c->querybuf); c->argv_len_sum += c->bulklen; sdsIncrLen(c->querybuf,-2); /* remove CRLF */ /* Assume that if we saw a fat argument we'll see another one * likely... */ c->querybuf = sdsnewlen(SDS_NOINIT,c->bulklen+2); sdsclear(c->querybuf); } else { c->argv[c->argc++] = createStringObject(c->querybuf+c->qb_pos,c->bulklen); c->argv_len_sum += c->bulklen; c->qb_pos += c->bulklen+2; } c->bulklen = -1; c->multibulklen--; } } /* We're done when c->multibulk == 0 */ if (c->multibulklen == 0) return C_OK; /* Still not ready to process the command */ return C_ERR; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-770'], 'message': 'Prevent unauthenticated client from easily consuming lots of memory (CVE-2021-32675) This change sets a low limit for multibulk and bulk length in the protocol for unauthenticated connections, so that they can't easily cause redis to allocate massive amounts of memory by sending just a few characters on the network. The new limits are 10 arguments of 16kb each (instead of 1m of 512mb)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: REDIS_STATIC void _quicklistInsert(quicklist *quicklist, quicklistEntry *entry, void *value, const size_t sz, int after) { int full = 0, at_tail = 0, at_head = 0, full_next = 0, full_prev = 0; int fill = quicklist->fill; quicklistNode *node = entry->node; quicklistNode *new_node = NULL; if (!node) { /* we have no reference node, so let's create only node in the list */ D("No node given!"); new_node = quicklistCreateNode(); new_node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_HEAD); __quicklistInsertNode(quicklist, NULL, new_node, after); new_node->count++; quicklist->count++; return; } /* Populate accounting flags for easier boolean checks later */ if (!_quicklistNodeAllowInsert(node, fill, sz)) { D("Current node is full with count %d with requested fill %lu", node->count, fill); full = 1; } if (after && (entry->offset == node->count)) { D("At Tail of current ziplist"); at_tail = 1; if (!_quicklistNodeAllowInsert(node->next, fill, sz)) { D("Next node is full too."); full_next = 1; } } if (!after && (entry->offset == 0)) { D("At Head"); at_head = 1; if (!_quicklistNodeAllowInsert(node->prev, fill, sz)) { D("Prev node is full too."); full_prev = 1; } } /* Now determine where and how to insert the new element */ if (!full && after) { D("Not full, inserting after current position."); quicklistDecompressNodeForUse(node); unsigned char *next = ziplistNext(node->zl, entry->zi); if (next == NULL) { node->zl = ziplistPush(node->zl, value, sz, ZIPLIST_TAIL); } else { node->zl = ziplistInsert(node->zl, next, value, sz); } node->count++; quicklistNodeUpdateSz(node); quicklistRecompressOnly(quicklist, node); } else if (!full && !after) { D("Not full, inserting before current position."); quicklistDecompressNodeForUse(node); node->zl = ziplistInsert(node->zl, entry->zi, value, sz); node->count++; quicklistNodeUpdateSz(node); quicklistRecompressOnly(quicklist, node); } else if (full && at_tail && node->next && !full_next && after) { /* If we are: at tail, next has free space, and inserting after: * - insert entry at head of next node. */ D("Full and tail, but next isn't full; inserting next node head"); new_node = node->next; quicklistDecompressNodeForUse(new_node); new_node->zl = ziplistPush(new_node->zl, value, sz, ZIPLIST_HEAD); new_node->count++; quicklistNodeUpdateSz(new_node); quicklistRecompressOnly(quicklist, new_node); } else if (full && at_head && node->prev && !full_prev && !after) { /* If we are: at head, previous has free space, and inserting before: * - insert entry at tail of previous node. */ D("Full and head, but prev isn't full, inserting prev node tail"); new_node = node->prev; quicklistDecompressNodeForUse(new_node); new_node->zl = ziplistPush(new_node->zl, value, sz, ZIPLIST_TAIL); new_node->count++; quicklistNodeUpdateSz(new_node); quicklistRecompressOnly(quicklist, new_node); } else if (full && ((at_tail && node->next && full_next && after) || (at_head && node->prev && full_prev && !after))) { /* If we are: full, and our prev/next is full, then: * - create new node and attach to quicklist */ D("\tprovisioning new node..."); new_node = quicklistCreateNode(); new_node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_HEAD); new_node->count++; quicklistNodeUpdateSz(new_node); __quicklistInsertNode(quicklist, node, new_node, after); } else if (full) { /* else, node is full we need to split it. */ /* covers both after and !after cases */ D("\tsplitting node..."); quicklistDecompressNodeForUse(node); new_node = _quicklistSplitNode(node, entry->offset, after); new_node->zl = ziplistPush(new_node->zl, value, sz, after ? ZIPLIST_HEAD : ZIPLIST_TAIL); new_node->count++; quicklistNodeUpdateSz(new_node); __quicklistInsertNode(quicklist, node, new_node, after); _quicklistMergeNodes(quicklist, node); } quicklist->count++; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix ziplist and listpack overflows and truncations (CVE-2021-32627, CVE-2021-32628) - fix possible heap corruption in ziplist and listpack resulting by trying to allocate more than the maximum size of 4GB. - prevent ziplist (hash and zset) from reaching size of above 1GB, will be converted to HT encoding, that's not a useful size. - prevent listpack (stream) from reaching size of above 1GB. - XADD will start a new listpack if the new record may cause the previous listpack to grow over 1GB. - XADD will respond with an error if a single stream record is over 1GB - List type (ziplist in quicklist) was truncating strings that were over 4GB, now it'll respond with an error.'</s>
<s>[INST] Given the following code containing errors, provide 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 quicklistPushTail(quicklist *quicklist, void *value, size_t sz) { quicklistNode *orig_tail = quicklist->tail; if (likely( _quicklistNodeAllowInsert(quicklist->tail, quicklist->fill, sz))) { quicklist->tail->zl = ziplistPush(quicklist->tail->zl, value, sz, ZIPLIST_TAIL); quicklistNodeUpdateSz(quicklist->tail); } else { quicklistNode *node = quicklistCreateNode(); node->zl = ziplistPush(ziplistNew(), value, sz, ZIPLIST_TAIL); quicklistNodeUpdateSz(node); _quicklistInsertNodeAfter(quicklist, quicklist->tail, node); } quicklist->count++; quicklist->tail->count++; return (orig_tail != quicklist->tail); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix ziplist and listpack overflows and truncations (CVE-2021-32627, CVE-2021-32628) - fix possible heap corruption in ziplist and listpack resulting by trying to allocate more than the maximum size of 4GB. - prevent ziplist (hash and zset) from reaching size of above 1GB, will be converted to HT encoding, that's not a useful size. - prevent listpack (stream) from reaching size of above 1GB. - XADD will start a new listpack if the new record may cause the previous listpack to grow over 1GB. - XADD will respond with an error if a single stream record is over 1GB - List type (ziplist in quicklist) was truncating strings that were over 4GB, now it'll respond with an error.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tgs_build_reply(astgs_request_t priv, hdb_entry_ex *krbtgt, krb5_enctype krbtgt_etype, const krb5_keyblock *replykey, int rk_is_subkey, krb5_ticket *ticket, const char **e_text, AuthorizationData **auth_data, const struct sockaddr *from_addr) { krb5_context context = priv->context; krb5_kdc_configuration *config = priv->config; KDC_REQ *req = &priv->req; KDC_REQ_BODY *b = &priv->req.req_body; const char *from = priv->from; krb5_error_code ret, ret2; krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL; krb5_principal krbtgt_out_principal = NULL; char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL; hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL; HDB *clientdb, *s4u2self_impersonated_clientdb; krb5_realm ref_realm = NULL; EncTicketPart *tgt = &ticket->ticket; krb5_principals spp = NULL; const EncryptionKey *ekey; krb5_keyblock sessionkey; krb5_kvno kvno; krb5_data rspac; const char *tgt_realm = /* Realm of TGT issuer */ krb5_principal_get_realm(context, krbtgt->entry.principal); const char *our_realm = /* Realm of this KDC */ krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1); char **capath = NULL; size_t num_capath = 0; hdb_entry_ex *krbtgt_out = NULL; METHOD_DATA enc_pa_data; PrincipalName *s; Realm r; EncTicketPart adtkt; char opt_str[128]; int signedpath = 0; Key *tkey_check; Key *tkey_sign; int flags = HDB_F_FOR_TGS_REQ; memset(&sessionkey, 0, sizeof(sessionkey)); memset(&adtkt, 0, sizeof(adtkt)); krb5_data_zero(&rspac); memset(&enc_pa_data, 0, sizeof(enc_pa_data)); s = b->sname; r = b->realm; /* * The canonicalize KDC option is passed as a hint to the backend, but * can typically be ignored. Per RFC 6806, names are not canonicalized * in response to a TGS request (although we make an exception, see * force-canonicalize below). */ if (b->kdc_options.canonicalize) flags |= HDB_F_CANON; if(b->kdc_options.enc_tkt_in_skey){ Ticket *t; hdb_entry_ex *uu; krb5_principal p; Key *uukey; krb5uint32 second_kvno = 0; krb5uint32 *kvno_ptr = NULL; if(b->additional_tickets == NULL || b->additional_tickets->len == 0){ ret = KRB5KDC_ERR_BADOPTION; /* ? */ kdc_log(context, config, 4, "No second ticket present in user-to-user request"); _kdc_audit_addreason((kdc_request_t)priv, "No second ticket present in user-to-user request"); goto out; } t = &b->additional_tickets->val[0]; if(!get_krbtgt_realm(&t->sname)){ kdc_log(context, config, 4, "Additional ticket is not a ticket-granting ticket"); _kdc_audit_addreason((kdc_request_t)priv, "Additional ticket is not a ticket-granting ticket"); ret = KRB5KDC_ERR_POLICY; goto out; } _krb5_principalname2krb5_principal(context, &p, t->sname, t->realm); ret = krb5_unparse_name(context, p, &tpn); if (ret) goto out; if(t->enc_part.kvno){ second_kvno = *t->enc_part.kvno; kvno_ptr = &second_kvno; } ret = _kdc_db_fetch(context, config, p, HDB_F_GET_KRBTGT, kvno_ptr, NULL, &uu); krb5_free_principal(context, p); if(ret){ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; _kdc_audit_addreason((kdc_request_t)priv, "User-to-user service principal (TGS) unknown"); goto out; } ret = hdb_enctype2key(context, &uu->entry, NULL, t->enc_part.etype, &uukey); if(ret){ _kdc_free_ent(context, uu); ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ _kdc_audit_addreason((kdc_request_t)priv, "User-to-user enctype not supported"); goto out; } ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0); _kdc_free_ent(context, uu); if(ret) { _kdc_audit_addreason((kdc_request_t)priv, "User-to-user TGT decrypt failure"); goto out; } ret = verify_flags(context, config, &adtkt, tpn); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "User-to-user TGT expired or invalid"); goto out; } s = &adtkt.cname; r = adtkt.crealm; } _krb5_principalname2krb5_principal(context, &sp, *s, r); ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) goto out; spn = priv->sname; _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm); ret = krb5_unparse_name(context, cp, &priv->cname); if (ret) goto out; cpn = priv->cname; unparse_flags (KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(), opt_str, sizeof(opt_str)); if(*opt_str) kdc_log(context, config, 4, "TGS-REQ %s from %s for %s [%s]", cpn, from, spn, opt_str); else kdc_log(context, config, 4, "TGS-REQ %s from %s for %s", cpn, from, spn); /* * Fetch server */ server_lookup: ret = _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER | HDB_F_DELAY_NEW_KEYS | flags, NULL, NULL, &server); priv->server = server; if (ret == HDB_ERR_NOT_FOUND_HERE) { kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", spn); _kdc_audit_addreason((kdc_request_t)priv, "Target not found here"); goto out; } else if (ret == HDB_ERR_WRONG_REALM) { free(ref_realm); ref_realm = strdup(server->entry.principal->realm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } kdc_log(context, config, 4, "Returning a referral to realm %s for " "server %s.", ref_realm, spn); krb5_free_principal(context, sp); sp = NULL; ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); if (ret) goto out; free(priv->sname); priv->sname = NULL; ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) goto out; spn = priv->sname; goto server_lookup; } else if (ret) { const char *new_rlm, *msg; Realm req_rlm; krb5_realm *realms; if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) { if (capath == NULL) { /* With referalls, hierarchical capaths are always enabled */ ret2 = _krb5_find_capath(context, tgt->crealm, our_realm, req_rlm, TRUE, &capath, &num_capath); if (ret2) { ret = ret2; _kdc_audit_addreason((kdc_request_t)priv, "No trusted path from client realm to ours"); goto out; } } new_rlm = num_capath > 0 ? capath[--num_capath] : NULL; if (new_rlm) { kdc_log(context, config, 5, "krbtgt from %s via %s for " "realm %s not found, trying %s", tgt->crealm, our_realm, req_rlm, new_rlm); free(ref_realm); ref_realm = strdup(new_rlm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); free(priv->sname); priv->sname = NULL; ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) goto out; spn = priv->sname; goto server_lookup; } } else if (need_referral(context, config, &b->kdc_options, sp, &realms)) { if (strcmp(realms[0], sp->realm) != 0) { kdc_log(context, config, 4, "Returning a referral to realm %s for " "server %s that was not found", realms[0], spn); krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, realms[0], NULL); free(priv->sname); priv->sname = NULL; ret = krb5_unparse_name(context, sp, &priv->sname); if (ret) { krb5_free_host_realm(context, realms); goto out; } spn = priv->sname; free(ref_realm); ref_realm = strdup(realms[0]); krb5_free_host_realm(context, realms); goto server_lookup; } krb5_free_host_realm(context, realms); } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 3, "Server not found in database: %s: %s", spn, msg); krb5_free_error_message(context, msg); if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; _kdc_audit_addreason((kdc_request_t)priv, "Service principal unknown"); goto out; } /* * RFC 6806 notes that names MUST NOT be changed in the response to * a TGS request. Hence we ignore the setting of the canonicalize * KDC option. However, for legacy interoperability we do allow the * backend to override this by setting the force-canonicalize HDB * flag in the server entry. */ if (server->entry.flags.force_canonicalize) rsp = server->entry.principal; else rsp = sp; /* * Select enctype, return key and kvno. */ { krb5_enctype etype; if(b->kdc_options.enc_tkt_in_skey) { size_t i; ekey = &adtkt.key; for(i = 0; i < b->etype.len; i++) if (b->etype.val[i] == adtkt.key.keytype) break; if(i == b->etype.len) { kdc_log(context, config, 4, "Addition ticket have not matching etypes"); krb5_clear_error_message(context); ret = KRB5KDC_ERR_ETYPE_NOSUPP; _kdc_audit_addreason((kdc_request_t)priv, "No matching enctypes for 2nd ticket"); goto out; } etype = b->etype.val[i]; kvno = 0; } else { Key *skey; ret = _kdc_find_etype(priv, krb5_principal_is_krbtgt(context, sp) ? KFE_IS_TGS : 0, b->etype.val, b->etype.len, &etype, NULL, NULL); if(ret) { kdc_log(context, config, 4, "Server (%s) has no support for etypes", spn); _kdc_audit_addreason((kdc_request_t)priv, "Enctype not supported"); goto out; } ret = _kdc_get_preferred_key(context, config, server, spn, NULL, &skey); if(ret) { kdc_log(context, config, 4, "Server (%s) has no supported etypes", spn); _kdc_audit_addreason((kdc_request_t)priv, "Enctype not supported"); goto out; } ekey = &skey->key; kvno = server->entry.kvno; } ret = krb5_generate_random_keyblock(context, etype, &sessionkey); if (ret) goto out; } /* * Check that service is in the same realm as the krbtgt. If it's * not the same, it's someone that is using a uni-directional trust * backward. */ /* * Validate authorization data */ ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */ krbtgt_etype, &tkey_check); if(ret) { kdc_log(context, config, 4, "Failed to find key for krbtgt PAC check"); _kdc_audit_addreason((kdc_request_t)priv, "No key for krbtgt PAC check"); goto out; } /* * Now refetch the primary krbtgt, and get the current kvno (the * sign check may have been on an old kvno, and the server may * have been an incoming trust) */ ret = krb5_make_principal(context, &krbtgt_out_principal, our_realm, KRB5_TGS_NAME, our_realm, NULL); if (ret) { kdc_log(context, config, 4, "Failed to make krbtgt principal name object for " "authz-data signatures"); goto out; } ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n); if (ret) { kdc_log(context, config, 4, "Failed to make krbtgt principal name object for " "authz-data signatures"); goto out; } ret = _kdc_db_fetch(context, config, krbtgt_out_principal, HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out); if (ret) { char *ktpn = NULL; ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn); kdc_log(context, config, 4, "No such principal %s (needed for authz-data signature keys) " "while processing TGS-REQ for service %s with krbtg %s", krbtgt_out_n, spn, (ret == 0) ? ktpn : "<unknown>"); free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; goto out; } /* * The first realm is the realm of the service, the second is * krbtgt/<this>/@REALM component of the krbtgt DN the request was * encrypted to. The redirection via the krbtgt_out entry allows * the DB to possibly correct the case of the realm (Samba4 does * this) before the strcmp() */ if (strcmp(krb5_principal_get_realm(context, server->entry.principal), krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) { char *ktpn; ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn); kdc_log(context, config, 4, "Request with wrong krbtgt: %s", (ret == 0) ? ktpn : "<unknown>"); if(ret == 0) free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; _kdc_audit_addreason((kdc_request_t)priv, "Request with wrong TGT"); goto out; } ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n, NULL, &tkey_sign); if (ret) { kdc_log(context, config, 4, "Failed to find key for krbtgt PAC signature"); _kdc_audit_addreason((kdc_request_t)priv, "Failed to find key for krbtgt PAC signature"); goto out; } ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL, tkey_sign->key.keytype, &tkey_sign); if(ret) { kdc_log(context, config, 4, "Failed to find key for krbtgt PAC signature"); _kdc_audit_addreason((kdc_request_t)priv, "Failed to find key for krbtgt PAC signature"); goto out; } { krb5_data verified_cas; /* * If the client doesn't exist in the HDB but has a TGT and it's * obtained with PKINIT then we assume it's a synthetic client -- that * is, a client whose name was vouched for by a CA using a PKINIT SAN, * but which doesn't exist in the HDB proper. We'll allow such a * client to do TGT requests even though normally we'd reject all * clients that don't exist in the HDB. */ ret = krb5_ticket_get_authorization_data_type(context, ticket, KRB5_AUTHDATA_INITIAL_VERIFIED_CAS, &verified_cas); if (ret == 0) { krb5_data_free(&verified_cas); flags |= HDB_F_SYNTHETIC_OK; } } ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags, NULL, &clientdb, &client); flags &= ~HDB_F_SYNTHETIC_OK; priv->client = client; if(ret == HDB_ERR_NOT_FOUND_HERE) { /* This is OK, we are just trying to find out if they have * been disabled or deleted in the meantime, missing secrets * is OK */ } else if(ret){ const char *krbtgt_realm, *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal); if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) { if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; kdc_log(context, config, 4, "Client no longer in database: %s", cpn); _kdc_audit_addreason((kdc_request_t)priv, "Client no longer in HDB"); goto out; } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 4, "Client not found in database: %s", msg); _kdc_audit_addreason((kdc_request_t)priv, "Client does not exist"); krb5_free_error_message(context, msg); } else if (ret == 0 && (client->entry.flags.invalid || !client->entry.flags.client)) { _kdc_audit_addreason((kdc_request_t)priv, "Client has invalid bit set"); kdc_log(context, config, 4, "Client has invalid bit set"); ret = KRB5KDC_ERR_POLICY; goto out; } ret = check_PAC(context, config, cp, NULL, client, server, krbtgt, &tkey_check->key, ekey, &tkey_sign->key, tgt, &rspac, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "PAC check failed"); kdc_log(context, config, 4, "Verify PAC failed for %s (%s) from %s with %s", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* also check the krbtgt for signature */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, tgt, &spp, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath check failed"); kdc_log(context, config, 4, "KRB5SignedPath check failed for %s (%s) from %s with %s", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Process request */ /* by default the tgt principal matches the client principal */ tp = cp; tpn = cpn; if (client) { const PA_DATA *sdata; int i = 0; sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER); if (sdata) { struct astgs_request_desc imp_req; krb5_crypto crypto; krb5_data datack; PA_S4U2Self self; const char *str; ret = decode_PA_S4U2Self(sdata->padata_value.data, sdata->padata_value.length, &self, NULL); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Failed to decode PA-S4U2Self"); kdc_log(context, config, 4, "Failed to decode PA-S4U2Self"); goto out; } if (!krb5_checksum_is_keyed(context, self.cksum.cksumtype)) { free_PA_S4U2Self(&self); _kdc_audit_addreason((kdc_request_t)priv, "PA-S4U2Self with unkeyed checksum"); kdc_log(context, config, 4, "Reject PA-S4U2Self with unkeyed checksum"); ret = KRB5KRB_AP_ERR_INAPP_CKSUM; goto out; } ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack); if (ret) goto out; ret = krb5_crypto_init(context, &tgt->key, 0, &crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); krb5_data_free(&datack); kdc_log(context, config, 4, "krb5_crypto_init failed: %s", msg); krb5_free_error_message(context, msg); goto out; } /* Allow HMAC_MD5 checksum with any key type */ if (self.cksum.cksumtype == CKSUMTYPE_HMAC_MD5) { struct krb5_crypto_iov iov; unsigned char csdata[16]; Checksum cs; cs.checksum.length = sizeof(csdata); cs.checksum.data = &csdata; iov.data.data = datack.data; iov.data.length = datack.length; iov.flags = KRB5_CRYPTO_TYPE_DATA; ret = _krb5_HMAC_MD5_checksum(context, NULL, &crypto->key, KRB5_KU_OTHER_CKSUM, &iov, 1, &cs); if (ret == 0 && krb5_data_ct_cmp(&cs.checksum, &self.cksum.checksum) != 0) ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; } else { ret = krb5_verify_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, datack.data, datack.length, &self.cksum); } krb5_data_free(&datack); krb5_crypto_destroy(context, crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); _kdc_audit_addreason((kdc_request_t)priv, "S4U2Self checksum failed"); kdc_log(context, config, 4, "krb5_verify_checksum failed for S4U2Self: %s", msg); krb5_free_error_message(context, msg); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, self.name, self.realm); free_PA_S4U2Self(&self); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; /* * Note no HDB_F_SYNTHETIC_OK -- impersonating non-existent clients * is probably not desirable! */ ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags, NULL, &s4u2self_impersonated_clientdb, &s4u2self_impersonated_client); if (ret) { const char *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "S4U2Self principal to impersonate not found"); kdc_log(context, config, 2, "S4U2Self principal to impersonate %s not found in database: %s", tpn, msg); krb5_free_error_message(context, msg); goto out; } /* Ignore require_pwchange and pw_end attributes (as Windows does), * since S4U2Self is not password authentication. */ s4u2self_impersonated_client->entry.flags.require_pwchange = FALSE; free(s4u2self_impersonated_client->entry.pw_end); s4u2self_impersonated_client->entry.pw_end = NULL; imp_req = *priv; imp_req.client = s4u2self_impersonated_client; imp_req.client_princ = tp; ret = kdc_check_flags(&imp_req, FALSE); if (ret) goto out; /* kdc_check_flags() calls _kdc_audit_addreason() */ /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */ if(rspac.data) { krb5_pac p = NULL; krb5_data_free(&rspac); ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath missing"); kdc_log(context, config, 4, "PAC generation failed for -- %s", tpn); goto out; } if (p != NULL) { ret = _krb5_pac_sign(context, p, ticket->ticket.authtime, s4u2self_impersonated_client->entry.principal, ekey, &tkey_sign->key, &rspac); krb5_pac_free(context, p); if (ret) { kdc_log(context, config, 4, "PAC signing failed for -- %s", tpn); goto out; } } } /* * Check that service doing the impersonating is * requesting a ticket to it-self. */ ret = check_s4u2self(context, config, clientdb, client, sp); if (ret) { kdc_log(context, config, 4, "S4U2Self: %s is not allowed " "to impersonate to service " "(tried for user %s to service %s)", cpn, tpn, spn); goto out; } /* * If the service isn't trusted for authentication to * delegation or if the impersonate client is disallowed * forwardable, remove the forwardable flag. */ if (client->entry.flags.trusted_for_delegation && s4u2self_impersonated_client->entry.flags.forwardable) { str = "[forwardable]"; } else { b->kdc_options.forwardable = 0; str = ""; } kdc_log(context, config, 4, "s4u2self %s impersonating %s to " "service %s %s", cpn, tpn, spn, str); } } /* * Constrained delegation */ if (client != NULL && b->additional_tickets != NULL && b->additional_tickets->len != 0 && b->kdc_options.cname_in_addl_tkt && b->kdc_options.enc_tkt_in_skey == 0) { int ad_signedpath = 0; Key *clientkey; Ticket *t; /* * Require that the KDC have issued the service's krbtgt (not * self-issued ticket with kimpersonate(1). */ if (!signedpath) { ret = KRB5KDC_ERR_BADOPTION; _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath missing"); kdc_log(context, config, 4, "Constrained delegation done on service ticket %s/%s", cpn, spn); goto out; } t = &b->additional_tickets->val[0]; ret = hdb_enctype2key(context, &client->entry, hdb_kvno2keys(context, &client->entry, t->enc_part.kvno ? * t->enc_part.kvno : 0), t->enc_part.etype, &clientkey); if(ret){ ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ goto out; } ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Failed to decrypt constrained delegation ticket"); kdc_log(context, config, 4, "failed to decrypt ticket for " "constrained delegation from %s to %s ", cpn, spn); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, adtkt.cname, adtkt.crealm); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; _kdc_audit_addkv((kdc_request_t)priv, 0, "impersonatee", "%s", tpn); ret = _krb5_principalname2krb5_principal(context, &dp, t->sname, t->realm); if (ret) goto out; ret = krb5_unparse_name(context, dp, &dpn); if (ret) goto out; /* check that ticket is valid */ if (adtkt.flags.forwardable == 0) { _kdc_audit_addreason((kdc_request_t)priv, "Missing forwardable flag on ticket for constrained delegation"); kdc_log(context, config, 4, "Missing forwardable flag on ticket for " "constrained delegation from %s (%s) as %s to %s ", cpn, dpn, tpn, spn); ret = KRB5KDC_ERR_BADOPTION; goto out; } ret = check_constrained_delegation(context, config, clientdb, client, server, sp); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation not allowed"); kdc_log(context, config, 4, "constrained delegation from %s (%s) as %s to %s not allowed", cpn, dpn, tpn, spn); goto out; } ret = verify_flags(context, config, &adtkt, tpn); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation ticket expired or invalid"); goto out; } krb5_data_free(&rspac); /* * generate the PAC for the user. * * TODO: pass in t->sname and t->realm and build * a S4U_DELEGATION_INFO blob to the PAC. */ ret = check_PAC(context, config, tp, dp, client, server, krbtgt, &clientkey->key, ekey, &tkey_sign->key, &adtkt, &rspac, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation ticket PAC check failed"); kdc_log(context, config, 4, "Verify delegated PAC failed to %s for client" "%s (%s) as %s from %s with %s", spn, cpn, dpn, tpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Check that the KDC issued the user's ticket. */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, &adtkt, NULL, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 4, "KRB5SignedPath check from service %s failed " "for delegation to %s for client %s (%s)" "from %s failed with %s", spn, tpn, dpn, cpn, from, msg); krb5_free_error_message(context, msg); _kdc_audit_addreason((kdc_request_t)priv, "KRB5SignedPath check failed"); goto out; } if (!ad_signedpath) { ret = KRB5KDC_ERR_BADOPTION; kdc_log(context, config, 4, "Ticket not signed with PAC nor SignedPath service %s failed " "for delegation to %s for client %s (%s)" "from %s", spn, tpn, dpn, cpn, from); _kdc_audit_addreason((kdc_request_t)priv, "Constrained delegation ticket not signed"); goto out; } kdc_log(context, config, 4, "constrained delegation for %s " "from %s (%s) to %s", tpn, cpn, dpn, spn); } /* * Check flags */ ret = kdc_check_flags(priv, FALSE); if(ret) goto out; if((b->kdc_options.validate || b->kdc_options.renew) && !krb5_principal_compare(context, krbtgt->entry.principal, server->entry.principal)){ _kdc_audit_addreason((kdc_request_t)priv, "Inconsistent request"); kdc_log(context, config, 4, "Inconsistent request."); ret = KRB5KDC_ERR_SERVER_NOMATCH; goto out; } /* check for valid set of addresses */ if (!_kdc_check_addresses(priv, tgt->caddr, from_addr)) { if (config->check_ticket_addresses) { ret = KRB5KRB_AP_ERR_BADADDR; _kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes"); kdc_log(context, config, 4, "Request from wrong address"); _kdc_audit_addreason((kdc_request_t)priv, "Request from wrong address"); goto out; } else if (config->warn_ticket_addresses) { _kdc_audit_addkv((kdc_request_t)priv, 0, "wrongaddr", "yes"); } } /* check local and per-principal anonymous ticket issuance policy */ if (is_anon_tgs_request_p(b, tgt)) { ret = _kdc_check_anon_policy(priv); if (ret) goto out; } /* * If this is an referral, add server referral data to the * auth_data reply . */ if (ref_realm) { PA_DATA pa; krb5_crypto crypto; kdc_log(context, config, 3, "Adding server referral to %s", ref_realm); ret = krb5_crypto_init(context, &sessionkey, 0, &crypto); if (ret) goto out; ret = build_server_referral(context, config, crypto, ref_realm, NULL, s, &pa.padata_value); krb5_crypto_destroy(context, crypto); if (ret) { _kdc_audit_addreason((kdc_request_t)priv, "Referral build failed"); kdc_log(context, config, 4, "Failed building server referral"); goto out; } pa.padata_type = KRB5_PADATA_SERVER_REFERRAL; ret = add_METHOD_DATA(&enc_pa_data, &pa); krb5_data_free(&pa.padata_value); if (ret) { kdc_log(context, config, 4, "Add server referral METHOD-DATA failed"); goto out; } } /* * */ ret = tgs_make_reply(priv, tp, tgt, replykey, rk_is_subkey, ekey, &sessionkey, kvno, *auth_data, server, rsp, client, cp, tgt_realm, krbtgt_out, tkey_sign->key.keytype, spp, &rspac, &enc_pa_data); out: if (tpn != cpn) free(tpn); free(dpn); free(krbtgt_out_n); _krb5_free_capath(context, capath); krb5_data_free(&rspac); krb5_free_keyblock_contents(context, &sessionkey); if(krbtgt_out) _kdc_free_ent(context, krbtgt_out); if(server) _kdc_free_ent(context, server); if(client) _kdc_free_ent(context, client); if(s4u2self_impersonated_client) _kdc_free_ent(context, s4u2self_impersonated_client); if (tp && tp != cp) krb5_free_principal(context, tp); krb5_free_principal(context, cp); krb5_free_principal(context, dp); krb5_free_principal(context, sp); krb5_free_principal(context, krbtgt_out_principal); free(ref_realm); free_METHOD_DATA(&enc_pa_data); free_EncTicketPart(&adtkt); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'kdc: validate sname in TGS-REQ In tgs_build_reply(), validate the server name in the TGS-REQ is present before dereferencing.'</s>
<s>[INST] Given the following code containing errors, provide 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 k_ascii(struct vc_data *vc, unsigned char value, char up_flag) { int base; if (up_flag) return; if (value < 10) { /* decimal input of code, while Alt depressed */ base = 10; } else { /* hexadecimal input of code, while AltGr depressed */ value -= 10; base = 16; } if (npadch == -1) npadch = value; else npadch = npadch * base + value; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'vt: keyboard: avoid signed integer overflow in k_ascii When k_ascii is invoked several times in a row there is a potential for signed integer overflow: UBSAN: Undefined behaviour in drivers/tty/vt/keyboard.c:888:19 signed integer overflow: 10 * 1111111111 cannot be represented in type 'int' CPU: 0 PID: 0 Comm: swapper/0 Not tainted 5.6.11 #1 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 Call Trace: <IRQ> __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xce/0x128 lib/dump_stack.c:118 ubsan_epilogue+0xe/0x30 lib/ubsan.c:154 handle_overflow+0xdc/0xf0 lib/ubsan.c:184 __ubsan_handle_mul_overflow+0x2a/0x40 lib/ubsan.c:205 k_ascii+0xbf/0xd0 drivers/tty/vt/keyboard.c:888 kbd_keycode drivers/tty/vt/keyboard.c:1477 [inline] kbd_event+0x888/0x3be0 drivers/tty/vt/keyboard.c:1495 While it can be worked around by using check_mul_overflow()/ check_add_overflow(), it is better to introduce a separate flag to signal that number pad is being used to compose a symbol, and change type of the accumulator from signed to unsigned, thus avoiding undefined behavior when it overflows. Reported-by: Kyungtae Kim <kt0755@gmail.com> Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com> Cc: stable <stable@vger.kernel.org> Link: https://lore.kernel.org/r/20200525232740.GA262061@dtor-ws Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>