text
stringlengths
478
483k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int mainloop(CLIENT *client) { struct nbd_request request; struct nbd_reply reply; gboolean go_on=TRUE; #ifdef DODBG int i = 0; #endif negotiate(client); DEBUG("Entering request loop!\n"); reply.magic = htonl(NBD_REPLY_MAGIC); reply.error = 0; while (go_on) { char buf[BUFSIZE]; size_t len; #ifdef DODBG i++; printf("%d: ", i); #endif if (client->server->timeout) alarm(client->server->timeout); readit(client->net, &request, sizeof(request)); request.from = ntohll(request.from); request.type = ntohl(request.type); if (request.type==NBD_CMD_DISC) { msg2(LOG_INFO, "Disconnect request received."); if (client->difmap) g_free(client->difmap) ; if (client->difffile>=0) { close(client->difffile); unlink(client->difffilename); free(client->difffilename); } go_on=FALSE; continue; } len = ntohl(request.len); if (request.magic != htonl(NBD_REQUEST_MAGIC)) err("Not enough magic."); if (len > BUFSIZE) err("Request too big!"); #ifdef DODBG printf("%s from %Lu (%Lu) len %d, ", request.type ? "WRITE" : "READ", (unsigned long long)request.from, (unsigned long long)request.from / 512, len); #endif memcpy(reply.handle, request.handle, sizeof(reply.handle)); if ((request.from + len) > (OFFT_MAX)) { DEBUG("[Number too large!]"); ERROR(client, reply); continue; } if (((ssize_t)((off_t)request.from + len) > client->exportsize) || ((client->server->flags & F_READONLY) && request.type)) { DEBUG("[RANGE!]"); ERROR(client, reply); continue; } if (request.type==NBD_CMD_WRITE) { DEBUG("wr: net->buf, "); readit(client->net, buf, len); DEBUG("buf->exp, "); if ((client->server->flags & F_AUTOREADONLY) || expwrite(request.from, buf, len, client)) { DEBUG("Write failed: %m" ); ERROR(client, reply); continue; } SEND(client->net, reply); DEBUG("OK!\n"); continue; } /* READ */ DEBUG("exp->buf, "); if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { DEBUG("Read failed: %m"); ERROR(client, reply); continue; } DEBUG("buf->net, "); memcpy(buf, &reply, sizeof(struct nbd_reply)); writeit(client->net, buf, len + sizeof(struct nbd_reply)); DEBUG("OK!\n"); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'r134: CVE-2005-3534'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xfs_ioc_fsgeometry_v1( xfs_mount_t *mp, void __user *arg) { xfs_fsop_geom_v1_t fsgeo; int error; error = xfs_fs_geometry(mp, (xfs_fsop_geom_t *)&fsgeo, 3); if (error) return -error; if (copy_to_user(arg, &fsgeo, sizeof(fsgeo))) return -XFS_ERROR(EFAULT); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'xfs: zero proper structure size for geometry calls Commit 493f3358cb289ccf716c5a14fa5bb52ab75943e5 added this call to xfs_fs_geometry() in order to avoid passing kernel stack data back to user space: + memset(geo, 0, sizeof(*geo)); Unfortunately, one of the callers of that function passes the address of a smaller data type, cast to fit the type that xfs_fs_geometry() requires. As a result, this can happen: Kernel panic - not syncing: stack-protector: Kernel stack is corrupted in: f87aca93 Pid: 262, comm: xfs_fsr Not tainted 2.6.38-rc6-493f3358cb2+ #1 Call Trace: [<c12991ac>] ? panic+0x50/0x150 [<c102ed71>] ? __stack_chk_fail+0x10/0x18 [<f87aca93>] ? xfs_ioc_fsgeometry_v1+0x56/0x5d [xfs] Fix this by fixing that one caller to pass the right type and then copy out the subset it is interested in. Note: This patch is an alternative to one originally proposed by Eric Sandeen. Reported-by: Jeffrey Hundstad <[email protected]> Signed-off-by: Alex Elder <[email protected]> Reviewed-by: Eric Sandeen <[email protected]> Tested-by: Jeffrey Hundstad <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: vba_read_project_strings(int fd, int big_endian) { unsigned char *buf = NULL; uint16_t buflen = 0; int ret = 0; for(;;) { off_t offset; uint16_t length; char *name; if(!read_uint16(fd, &length, big_endian)) break; if (length < 6) { lseek(fd, -2, SEEK_CUR); break; } if(length > buflen) { unsigned char *newbuf = (unsigned char *)cli_realloc(buf, length); if(newbuf == NULL) { if(buf) free(buf); return 0; } buflen = length; buf = newbuf; } offset = lseek(fd, 0, SEEK_CUR); if(cli_readn(fd, buf, length) != (int)length) { cli_dbgmsg("read name failed - rewinding\n"); lseek(fd, offset, SEEK_SET); break; } name = get_unicode_name((const char *)buf, length, big_endian); cli_dbgmsg("length: %d, name: %s\n", length, (name) ? name : "[null]"); if((name == NULL) || (memcmp("*\\", name, 2) != 0) || (strchr("ghcd", name[2]) == NULL)) { /* Not a string */ lseek(fd, -(length+2), SEEK_CUR); if(name) free(name); break; } free(name); if(!read_uint16(fd, &length, big_endian)) { if(buf) free(buf); break; } ret++; if ((length != 0) && (length != 65535)) { lseek(fd, -2, SEEK_CUR); continue; } offset = lseek(fd, 10, SEEK_CUR); cli_dbgmsg("offset: %lu\n", (unsigned long)offset); vba56_test_middle(fd); } if(buf) free(buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'libclamav/vba_extract.c: fix error path double free (bb#2486)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlNodePtr cur = NULL; unsigned long val; xmlChar str[20]; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlXPathObjectPtr obj; xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } xmlXPathFreeObject(obj); } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ val = (unsigned long)((char *)cur - (char *)0); val /= sizeof(xmlNode); sprintf((char *)str, "id%ld", val); valuePush(ctxt, xmlXPathNewString(str)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Fix generate-id() to not expose object addresses As pointed out by Chris Evans <[email protected]> it's better security wise to not expose object addresses directly, use a diff w.r.t. the document root own address to avoid this * libxslt/functions.c: fix IDs generation 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: irc_server_gnutls_callback (void *data, gnutls_session_t tls_session, const gnutls_datum_t *req_ca, int nreq, const gnutls_pk_algorithm_t *pk_algos, int pk_algos_len, gnutls_retr_st *answer) { struct t_irc_server *server; gnutls_retr_st tls_struct; gnutls_x509_crt_t cert_temp; const gnutls_datum_t *cert_list; gnutls_datum_t filedatum; unsigned int cert_list_len, status; time_t cert_time; char *cert_path0, *cert_path1, *cert_path2, *cert_str, *hostname; const char *weechat_dir; int rc, ret, i, j, hostname_match; #if LIBGNUTLS_VERSION_NUMBER >= 0x010706 gnutls_datum_t cinfo; int rinfo; #endif /* make C compiler happy */ (void) req_ca; (void) nreq; (void) pk_algos; (void) pk_algos_len; rc = 0; if (!data) return -1; server = (struct t_irc_server *) data; hostname = server->current_address; hostname_match = 0; weechat_printf (server->buffer, _("gnutls: connected using %d-bit Diffie-Hellman shared " "secret exchange"), IRC_SERVER_OPTION_INTEGER (server, IRC_SERVER_OPTION_SSL_DHKEY_SIZE)); if (gnutls_certificate_verify_peers2 (tls_session, &status) < 0) { weechat_printf (server->buffer, _("%sgnutls: error while checking peer's certificate"), weechat_prefix ("error")); rc = -1; } else { /* some checks */ if (status & GNUTLS_CERT_INVALID) { weechat_printf (server->buffer, _("%sgnutls: peer's certificate is NOT trusted"), weechat_prefix ("error")); rc = -1; } else { weechat_printf (server->buffer, _("gnutls: peer's certificate is trusted")); } if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) { weechat_printf (server->buffer, _("%sgnutls: peer's certificate issuer is unknown"), weechat_prefix ("error")); rc = -1; } if (status & GNUTLS_CERT_REVOKED) { weechat_printf (server->buffer, _("%sgnutls: the certificate has been revoked"), weechat_prefix ("error")); rc = -1; } /* check certificates */ if (gnutls_x509_crt_init (&cert_temp) >= 0) { cert_list = gnutls_certificate_get_peers (tls_session, &cert_list_len); if (cert_list) { weechat_printf (server->buffer, NG_("gnutls: receiving %d certificate", "gnutls: receiving %d certificates", cert_list_len), cert_list_len); for (i = 0, j = (int) cert_list_len; i < j; i++) { if (gnutls_x509_crt_import (cert_temp, &cert_list[i], GNUTLS_X509_FMT_DER) >= 0) { /* checking if hostname matches in the first certificate */ if (i == 0 && gnutls_x509_crt_check_hostname (cert_temp, hostname) != 0) { hostname_match = 1; } #if LIBGNUTLS_VERSION_NUMBER >= 0x010706 /* displaying infos about certificate */ #if LIBGNUTLS_VERSION_NUMBER < 0x020400 rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_X509_CRT_ONELINE, &cinfo); #else rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_CRT_PRINT_ONELINE, &cinfo); #endif if (rinfo == 0) { weechat_printf (server->buffer, _(" - certificate[%d] info:"), i + 1); weechat_printf (server->buffer, " - %s", cinfo.data); gnutls_free (cinfo.data); } #endif /* check expiration date */ cert_time = gnutls_x509_crt_get_expiration_time (cert_temp); if (cert_time < time(NULL)) { weechat_printf (server->buffer, _("%sgnutls: certificate has expired"), weechat_prefix ("error")); rc = -1; } /* check expiration date */ cert_time = gnutls_x509_crt_get_activation_time (cert_temp); if (cert_time > time(NULL)) { weechat_printf (server->buffer, _("%sgnutls: certificate is not yet activated"), weechat_prefix ("error")); rc = -1; } } } if (hostname_match == 0) { weechat_printf (server->buffer, _("%sgnutls: the hostname in the " "certificate does NOT match \"%s\""), weechat_prefix ("error"), hostname); rc = -1; } } } } /* using client certificate if it exists */ cert_path0 = (char *) IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_SSL_CERT); if (cert_path0 && cert_path0[0]) { weechat_dir = weechat_info_get ("weechat_dir", ""); cert_path1 = weechat_string_replace (cert_path0, "%h", weechat_dir); cert_path2 = (cert_path1) ? weechat_string_expand_home (cert_path1) : NULL; if (cert_path2) { cert_str = weechat_file_get_content (cert_path2); if (cert_str) { weechat_printf (server->buffer, _("gnutls: sending one certificate")); filedatum.data = (unsigned char *) cert_str; filedatum.size = strlen (cert_str); /* certificate */ gnutls_x509_crt_init (&server->tls_cert); gnutls_x509_crt_import (server->tls_cert, &filedatum, GNUTLS_X509_FMT_PEM); /* key */ gnutls_x509_privkey_init (&server->tls_cert_key); ret = gnutls_x509_privkey_import (server->tls_cert_key, &filedatum, GNUTLS_X509_FMT_PEM); if (ret < 0) { ret = gnutls_x509_privkey_import_pkcs8 (server->tls_cert_key, &filedatum, GNUTLS_X509_FMT_PEM, NULL, GNUTLS_PKCS_PLAIN); } if (ret < 0) { weechat_printf (server->buffer, _("%sgnutls: invalid certificate \"%s\", " "error: %s"), weechat_prefix ("error"), cert_path2, gnutls_strerror (ret)); rc = -1; } else { tls_struct.type = GNUTLS_CRT_X509; tls_struct.ncerts = 1; tls_struct.deinit_all = 0; tls_struct.cert.x509 = &server->tls_cert; tls_struct.key.x509 = server->tls_cert_key; #if LIBGNUTLS_VERSION_NUMBER >= 0x010706 /* client certificate info */ #if LIBGNUTLS_VERSION_NUMBER < 0x020400 rinfo = gnutls_x509_crt_print (server->tls_cert, GNUTLS_X509_CRT_ONELINE, &cinfo); #else rinfo = gnutls_x509_crt_print (server->tls_cert, GNUTLS_CRT_PRINT_ONELINE, &cinfo); #endif if (rinfo == 0) { weechat_printf (server->buffer, _(" - client certificate info (%s):"), cert_path2); weechat_printf (server->buffer, " - %s", cinfo.data); gnutls_free (cinfo.data); } #endif memcpy (answer, &tls_struct, sizeof (gnutls_retr_st)); free (cert_str); } } else { weechat_printf (server->buffer, _("%sgnutls: unable to read certifcate \"%s\""), weechat_prefix ("error"), cert_path2); } } if (cert_path1) free (cert_path1); if (cert_path2) free (cert_path2); } /* an error should stop the handshake unless the user doesn't care */ if ((rc == -1) && (IRC_SERVER_OPTION_BOOLEAN(server, IRC_SERVER_OPTION_SSL_VERIFY) == 0)) { rc = 0; } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix verification of SSL certificates by calling gnutls verify callback (patch #7459)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret; struct arpt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct arpt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; /* choose the copy that is on our node/cpu */ loc_cpu_entry = newinfo->entries[raw_smp_processor_id()]; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_table(newinfo, loc_cpu_entry, &tmp); if (ret != 0) goto free_newinfo; duprintf("arp_tables: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, tmp.counters); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter); free_newinfo: xt_free_table_info(newinfo); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'netfilter: arp_tables: fix infoleak to userspace Structures ipt_replace, compat_ipt_replace, and xt_get_revision are copied from userspace. Fields of these structs that are zero-terminated strings are not checked. When they are used as argument to a format string containing "%s" in request_module(), some sensitive information is leaked to userspace via argument of spawned modprobe process. The first bug was introduced before the git epoch; the second is introduced by 6b7d31fc (v2.6.15-rc1); the third is introduced by 6b7d31fc (v2.6.15-rc1). To trigger the bug one should have CAP_NET_ADMIN. Signed-off-by: Vasiliy Kulikov <[email protected]> Signed-off-by: Patrick McHardy <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case ARPT_SO_GET_INFO: ret = get_info(sock_net(sk), user, len, 0); break; case ARPT_SO_GET_ENTRIES: ret = get_entries(sock_net(sk), user, len); break; case ARPT_SO_GET_REVISION_TARGET: { struct xt_get_revision rev; if (*len != sizeof(rev)) { ret = -EINVAL; break; } if (copy_from_user(&rev, user, sizeof(rev)) != 0) { ret = -EFAULT; break; } try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name, rev.revision, 1, &ret), "arpt_%s", rev.name); break; } default: duprintf("do_arpt_get_ctl: unknown request %i\n", cmd); ret = -EINVAL; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'netfilter: arp_tables: fix infoleak to userspace Structures ipt_replace, compat_ipt_replace, and xt_get_revision are copied from userspace. Fields of these structs that are zero-terminated strings are not checked. When they are used as argument to a format string containing "%s" in request_module(), some sensitive information is leaked to userspace via argument of spawned modprobe process. The first bug was introduced before the git epoch; the second is introduced by 6b7d31fc (v2.6.15-rc1); the third is introduced by 6b7d31fc (v2.6.15-rc1). To trigger the bug one should have CAP_NET_ADMIN. Signed-off-by: Vasiliy Kulikov <[email protected]> Signed-off-by: Patrick McHardy <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_ipt_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct ipt_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; /* choose the copy that is on our node/cpu */ loc_cpu_entry = newinfo->entries[raw_smp_processor_id()]; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(net, tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter, net); free_newinfo: xt_free_table_info(newinfo); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'netfilter: ip_tables: fix infoleak to userspace Structures ipt_replace, compat_ipt_replace, and xt_get_revision are copied from userspace. Fields of these structs that are zero-terminated strings are not checked. When they are used as argument to a format string containing "%s" in request_module(), some sensitive information is leaked to userspace via argument of spawned modprobe process. The first and the third bugs were introduced before the git epoch; the second was introduced in 2722971c (v2.6.17-rc1). To trigger the bug one should have CAP_NET_ADMIN. Signed-off-by: Vasiliy Kulikov <[email protected]> Signed-off-by: Patrick McHardy <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 clusterip_proc_write(struct file *file, const char __user *input, size_t size, loff_t *ofs) { struct clusterip_config *c = PDE(file->f_path.dentry->d_inode)->data; #define PROC_WRITELEN 10 char buffer[PROC_WRITELEN+1]; unsigned long nodenum; if (copy_from_user(buffer, input, PROC_WRITELEN)) return -EFAULT; if (*buffer == '+') { nodenum = simple_strtoul(buffer+1, NULL, 10); if (clusterip_add_node(c, nodenum)) return -ENOMEM; } else if (*buffer == '-') { nodenum = simple_strtoul(buffer+1, NULL,10); if (clusterip_del_node(c, nodenum)) return -ENOENT; } else return -EIO; return size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'netfilter: ipt_CLUSTERIP: fix buffer overflow 'buffer' string is copied from userspace. It is not checked whether it is zero terminated. This may lead to overflow inside of simple_strtoul(). Changli Gao suggested to copy not more than user supplied 'size' bytes. It was introduced before the git epoch. Files "ipt_CLUSTERIP/*" are root writable only by default, however, on some setups permissions might be relaxed to e.g. network admin user. Signed-off-by: Vasiliy Kulikov <[email protected]> Acked-by: Changli Gao <[email protected]> Signed-off-by: Patrick McHardy <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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_do_replace(struct net *net, void __user *user, unsigned int len) { int ret; struct compat_ip6t_replace tmp; struct xt_table_info *newinfo; void *loc_cpu_entry; struct ip6t_entry *iter; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; /* overflow check */ if (tmp.size >= INT_MAX / num_possible_cpus()) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters)) return -ENOMEM; newinfo = xt_alloc_table_info(tmp.size); if (!newinfo) return -ENOMEM; /* choose the copy that is on our node/cpu */ loc_cpu_entry = newinfo->entries[raw_smp_processor_id()]; if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) { ret = -EFAULT; goto free_newinfo; } ret = translate_compat_table(net, tmp.name, tmp.valid_hooks, &newinfo, &loc_cpu_entry, tmp.size, tmp.num_entries, tmp.hook_entry, tmp.underflow); if (ret != 0) goto free_newinfo; duprintf("compat_do_replace: Translated table\n"); ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo, tmp.num_counters, compat_ptr(tmp.counters)); if (ret) goto free_newinfo_untrans; return 0; free_newinfo_untrans: xt_entry_foreach(iter, loc_cpu_entry, newinfo->size) cleanup_entry(iter, net); free_newinfo: xt_free_table_info(newinfo); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'ipv6: netfilter: ip6_tables: fix infoleak to userspace Structures ip6t_replace, compat_ip6t_replace, and xt_get_revision are copied from userspace. Fields of these structs that are zero-terminated strings are not checked. When they are used as argument to a format string containing "%s" in request_module(), some sensitive information is leaked to userspace via argument of spawned modprobe process. The first bug was introduced before the git epoch; the second was introduced in 3bc3fe5e (v2.6.25-rc1); the third is introduced by 6b7d31fc (v2.6.15-rc1). To trigger the bug one should have CAP_NET_ADMIN. Signed-off-by: Vasiliy Kulikov <[email protected]> Signed-off-by: Patrick McHardy <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: load_image (const gchar *filename, GError **error) { FILE *fd; GimpDrawable *drawable; GimpPixelRgn pixel_rgn; guint16 offset_x, offset_y, bytesperline; gint32 width, height; gint32 image, layer; guchar *dest, cmap[768]; guint8 header_buf[128]; fd = g_fopen (filename, "rb"); if (! fd) { g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno), _("Could not open '%s' for reading: %s"), gimp_filename_to_utf8 (filename), g_strerror (errno)); return -1; } gimp_progress_init_printf (_("Opening '%s'"), gimp_filename_to_utf8 (filename)); if (fread (header_buf, 128, 1, fd) == 0) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("Could not read header from '%s'"), gimp_filename_to_utf8 (filename)); return -1; } pcx_header_from_buffer (header_buf); if (pcx_header.manufacturer != 10) { g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_FAILED, _("'%s' is not a PCX file"), gimp_filename_to_utf8 (filename)); return -1; } offset_x = GUINT16_FROM_LE (pcx_header.x1); offset_y = GUINT16_FROM_LE (pcx_header.y1); width = GUINT16_FROM_LE (pcx_header.x2) - offset_x + 1; height = GUINT16_FROM_LE (pcx_header.y2) - offset_y + 1; bytesperline = GUINT16_FROM_LE (pcx_header.bytesperline); if ((width < 0) || (width > GIMP_MAX_IMAGE_SIZE)) { g_message (_("Unsupported or invalid image width: %d"), width); return -1; } if ((height < 0) || (height > GIMP_MAX_IMAGE_SIZE)) { g_message (_("Unsupported or invalid image height: %d"), height); return -1; } if (bytesperline < (width * pcx_header.bpp) / 8) { g_message (_("Invalid number of bytes per line in PCX header")); return -1; } /* Shield against potential buffer overflows in load_*() functions. */ if (G_MAXSIZE / width / height < 3) { g_message (_("Image dimensions too large: width %d x height %d"), width, height); return -1; } if (pcx_header.planes == 3 && pcx_header.bpp == 8) { image= gimp_image_new (width, height, GIMP_RGB); layer= gimp_layer_new (image, _("Background"), width, height, GIMP_RGB_IMAGE, 100, GIMP_NORMAL_MODE); } else { image= gimp_image_new (width, height, GIMP_INDEXED); layer= gimp_layer_new (image, _("Background"), width, height, GIMP_INDEXED_IMAGE, 100, GIMP_NORMAL_MODE); } gimp_image_set_filename (image, filename); gimp_image_add_layer (image, layer, 0); gimp_layer_set_offsets (layer, offset_x, offset_y); drawable = gimp_drawable_get (layer); if (pcx_header.planes == 1 && pcx_header.bpp == 1) { dest = g_new (guchar, width * height); load_1 (fd, width, height, dest, bytesperline); gimp_image_set_colormap (image, mono, 2); } else if (pcx_header.planes == 4 && pcx_header.bpp == 1) { dest = g_new (guchar, width * height); load_4 (fd, width, height, dest, bytesperline); gimp_image_set_colormap (image, pcx_header.colormap, 16); } else if (pcx_header.planes == 1 && pcx_header.bpp == 8) { dest = g_new (guchar, width * height); load_8 (fd, width, height, dest, bytesperline); fseek (fd, -768L, SEEK_END); fread (cmap, 768, 1, fd); gimp_image_set_colormap (image, cmap, 256); } else if (pcx_header.planes == 3 && pcx_header.bpp == 8) { dest = g_new (guchar, width * height * 3); load_24 (fd, width, height, dest, bytesperline); } else { g_message (_("Unusual PCX flavour, giving up")); return -1; } gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, width, height, TRUE, FALSE); gimp_pixel_rgn_set_rect (&pixel_rgn, dest, 0, 0, width, height); g_free (dest); gimp_drawable_flush (drawable); gimp_drawable_detach (drawable); return image; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'PCX: Avoid allocation overflows. Multiplying gint values may overflow unless cast into a larger type.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: msg_t* MsgDup(msg_t* pOld) { msg_t* pNew; rsRetVal localRet; assert(pOld != NULL); BEGINfunc if(msgConstructWithTime(&pNew, &pOld->tTIMESTAMP, pOld->ttGenTime) != RS_RET_OK) { return NULL; } /* now copy the message properties */ pNew->iRefCount = 1; pNew->iSeverity = pOld->iSeverity; pNew->iFacility = pOld->iFacility; pNew->msgFlags = pOld->msgFlags; pNew->iProtocolVersion = pOld->iProtocolVersion; pNew->ttGenTime = pOld->ttGenTime; pNew->offMSG = pOld->offMSG; pNew->iLenRawMsg = pOld->iLenRawMsg; pNew->iLenMSG = pOld->iLenMSG; pNew->iLenTAG = pOld->iLenTAG; pNew->iLenHOSTNAME = pOld->iLenHOSTNAME; if((pOld->msgFlags & NEEDS_DNSRESOL) == 1) { localRet = msgSetFromSockinfo(pNew, pOld->rcvFrom.pfrominet); if(localRet != RS_RET_OK) { /* if something fails, we accept loss of this property, it is * better than losing the whole message. */ pNew->msgFlags &= ~NEEDS_DNSRESOL; } } else { if(pOld->rcvFrom.pRcvFrom != NULL) { pNew->rcvFrom.pRcvFrom = pOld->rcvFrom.pRcvFrom; prop.AddRef(pNew->rcvFrom.pRcvFrom); } } if(pOld->pRcvFromIP != NULL) { pNew->pRcvFromIP = pOld->pRcvFromIP; prop.AddRef(pNew->pRcvFromIP); } if(pOld->pInputName != NULL) { pNew->pInputName = pOld->pInputName; prop.AddRef(pNew->pInputName); } /* enable this, if someone actually uses UxTradMsg, delete after some time has * passed and nobody complained -- rgerhards, 2009-06-16 pNew->offAfterPRI = pOld->offAfterPRI; */ if(pOld->iLenTAG > 0) { if(pOld->iLenTAG < CONF_TAG_BUFSIZE) { memcpy(pNew->TAG.szBuf, pOld->TAG.szBuf, pOld->iLenTAG); } else { if((pNew->TAG.pszTAG = srUtilStrDup(pOld->TAG.pszTAG, pOld->iLenTAG)) == NULL) { msgDestruct(&pNew); return NULL; } pNew->iLenTAG = pOld->iLenTAG; } } if(pOld->iLenRawMsg < CONF_RAWMSG_BUFSIZE) { memcpy(pNew->szRawMsg, pOld->szRawMsg, pOld->iLenRawMsg + 1); pNew->pszRawMsg = pNew->szRawMsg; } else { tmpCOPYSZ(RawMsg); } if(pOld->iLenHOSTNAME < CONF_HOSTNAME_BUFSIZE) { memcpy(pNew->szHOSTNAME, pOld->szHOSTNAME, pOld->iLenHOSTNAME + 1); pNew->pszHOSTNAME = pNew->szHOSTNAME; } else { tmpCOPYSZ(HOSTNAME); } tmpCOPYCSTR(ProgName); tmpCOPYCSTR(StrucData); tmpCOPYCSTR(APPNAME); tmpCOPYCSTR(PROCID); tmpCOPYCSTR(MSGID); /* we do not copy all other cache properties, as we do not even know * if they are needed once again. So we let them re-create if needed. */ ENDfunc return pNew; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'backporting abort condition fix from 5.7.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: batchInit(batch_t *pBatch, int maxElem) { DEFiRet; pBatch->maxElem = maxElem; CHKmalloc(pBatch->pElem = calloc((size_t)maxElem, sizeof(batch_obj_t))); // TODO: replace calloc by inidividual writes? finalize_it: RETiRet; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772', 'CWE-401'], 'message': 'bugfix: fixed a memory leak and potential abort condition this could happen if multiple rulesets were used and some output batches contained messages belonging to more than one ruleset. fixes: http://bugzilla.adiscon.com/show_bug.cgi?id=226 fixes: http://bugzilla.adiscon.com/show_bug.cgi?id=218'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rfbSendFramebufferUpdate(rfbClientPtr cl, sraRegionPtr givenUpdateRegion) { sraRectangleIterator* i=NULL; sraRect rect; int nUpdateRegionRects; rfbFramebufferUpdateMsg *fu = (rfbFramebufferUpdateMsg *)cl->updateBuf; sraRegionPtr updateRegion, updateCopyRegion, tmpRegion, cursorRegion; sraRect cursorBounds = { 0, 0, 0, 0 }; int dx, dy; rfbBool sendCursorShape = FALSE; rfbBool sendCursorPos = FALSE; rfbBool cursorIsDrawn = FALSE; /* * If framebuffer size was changed and the client supports NewFBSize * encoding, just send NewFBSize marker and return. */ if (cl->useNewFBSize && cl->newFBSizePending) { LOCK(cl->updateMutex); cl->newFBSizePending = FALSE; UNLOCK(cl->updateMutex); cl->rfbFramebufferUpdateMessagesSent++; fu->type = rfbFramebufferUpdate; fu->nRects = Swap16IfLE(1); cl->ublen = sz_rfbFramebufferUpdateMsg; if (!rfbSendNewFBSize(cl, cl->screen->width, cl->screen->height)) { return FALSE; } return rfbSendUpdateBuf(cl); } LOCK(cl->updateMutex); /* * The modifiedRegion may overlap the destination copyRegion. We remove * any overlapping bits from the copyRegion (since they'd only be * overwritten anyway). */ sraRgnSubtract(cl->copyRegion,cl->modifiedRegion); updateRegion = sraRgnCreateRgn(givenUpdateRegion); sraRgnOr(updateRegion,cl->copyRegion); /* * If the client doesn't support cursor updates, we want to draw * the cursor locally, send the update and then undraw it. * We only want to do this if the cursor has moved/changed or * if it is contained in updateRegion * * We also want to send an update for the region where the cursor * was last drawn, again only if the cursor has moved/changed. */ LOCK(cl->screen->cursorMutex); cursorRegion = NULL; if (cl->enableCursorUpdates) { sendCursorShape = cl->cursorWasChanged; sendCursorPos = cl->cursorWasMoved; } else { sraRegionPtr lastDrawnCursorRegion; if (rfbGetCursorBounds(cl->screen, &cursorBounds)) { cursorRegion = sraRgnCreateRect(cursorBounds.x1, cursorBounds.y1, cursorBounds.x2, cursorBounds.y2); } lastDrawnCursorRegion = sraRgnCreateRect(cl->lastDrawnCursorBounds.x1, cl->lastDrawnCursorBounds.y1, cl->lastDrawnCursorBounds.x2, cl->lastDrawnCursorBounds.y2); if (cursorRegion) { sraRgnOr(cursorRegion, lastDrawnCursorRegion); sraRgnDestroy(lastDrawnCursorRegion); } else { cursorRegion = lastDrawnCursorRegion; } if (cl->cursorWasChanged || cl->cursorWasMoved) sraRgnOr(updateRegion, cursorRegion); } /* * The client is interested in the region requestedRegion. The region * which should be updated now is the intersection of requestedRegion * and the union of modifiedRegion and copyRegion. If it's empty then * no update is needed. */ if (!sraRgnAnd(updateRegion, cl->requestedRegion) && !sendCursorShape && !sendCursorPos) { sraRgnDestroy(updateRegion); if (cursorRegion) sraRgnDestroy(cursorRegion); UNLOCK(cl->updateMutex); UNLOCK(cl->cursorMutex); return TRUE; } /* * Put up the cursor if any part of it is in updateRegion. */ if (cursorRegion) { tmpRegion = sraRgnCreateRgn(cursorRegion); if (sraRgnAnd(tmpRegion, updateRegion)) { rfbDrawCursor(cl->screen, &cursorBounds); cursorIsDrawn = TRUE; cl->cursorWasMoved = FALSE; cl->cursorWasChanged = FALSE; cl->lastDrawnCursorBounds = cursorBounds; sraRgnOr(cl->modifiedRegion, cursorRegion); sraRgnOr(updateRegion, cursorRegion); sraRgnAnd(updateRegion, cl->requestedRegion); } sraRgnDestroy(tmpRegion); sraRgnDestroy(cursorRegion); } /* * We assume that the client doesn't have any pixel data outside the * requestedRegion. In other words, both the source and destination of a * copy must lie within requestedRegion. So the region we can send as a * copy is the intersection of the copyRegion with both the requestedRegion * and the requestedRegion translated by the amount of the copy. We set * updateCopyRegion to this. */ updateCopyRegion = sraRgnCreateRgn(cl->copyRegion); sraRgnAnd(updateCopyRegion,cl->requestedRegion); tmpRegion = sraRgnCreateRgn(cl->requestedRegion); sraRgnOffset(tmpRegion,cl->copyDX,cl->copyDY); sraRgnAnd(updateCopyRegion,tmpRegion); sraRgnDestroy(tmpRegion); dx = cl->copyDX; dy = cl->copyDY; /* * Next we remove updateCopyRegion from updateRegion so that updateRegion * is the part of this update which is sent as ordinary pixel data (i.e not * a copy). */ sraRgnSubtract(updateRegion,updateCopyRegion); /* * Finally we leave modifiedRegion to be the remainder (if any) of parts of * the screen which are modified but outside the requestedRegion. We also * empty both the requestedRegion and the copyRegion - note that we never * carry over a copyRegion for a future update. */ sraRgnOr(cl->modifiedRegion,cl->copyRegion); sraRgnSubtract(cl->modifiedRegion,updateRegion); sraRgnSubtract(cl->modifiedRegion,updateCopyRegion); sraRgnMakeEmpty(cl->requestedRegion); sraRgnMakeEmpty(cl->copyRegion); cl->copyDX = 0; cl->copyDY = 0; UNLOCK(cl->updateMutex); /* * Now send the update. */ cl->rfbFramebufferUpdateMessagesSent++; if (cl->preferredEncoding == rfbEncodingCoRRE) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; nUpdateRegionRects += (((w-1) / cl->correMaxWidth + 1) * ((h-1) / cl->correMaxHeight + 1)); } sraRgnReleaseIterator(i); #ifdef HAVE_LIBZ } else if (cl->preferredEncoding == rfbEncodingZlib) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; nUpdateRegionRects += (((h-1) / (ZLIB_MAX_SIZE( w ) / w)) + 1); } #ifdef HAVE_LIBJPEG } else if (cl->preferredEncoding == rfbEncodingTight) { nUpdateRegionRects = 0; for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; int n = rfbNumCodedRectsTight(cl, x, y, w, h); if (n == 0) { nUpdateRegionRects = 0xFFFF; break; } nUpdateRegionRects += n; } sraRgnReleaseIterator(i); #endif #endif } else { nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->type = rfbFramebufferUpdate; if (nUpdateRegionRects != 0xFFFF) { if(cl->screen->maxRectsPerUpdate>0 /* CoRRE splits the screen into smaller squares */ && cl->preferredEncoding != rfbEncodingCoRRE #ifdef HAVE_LIBZ /* Zlib encoding splits rectangles up into smaller chunks */ && cl->preferredEncoding != rfbEncodingZlib #ifdef HAVE_LIBJPEG /* Tight encoding counts the rectangles differently */ && cl->preferredEncoding != rfbEncodingTight #endif #endif /* HAVE_LIBZ */ && nUpdateRegionRects>cl->screen->maxRectsPerUpdate) { sraRegion* newUpdateRegion = sraRgnBBox(updateRegion); sraRgnDestroy(updateRegion); updateRegion = newUpdateRegion; nUpdateRegionRects = sraRgnCountRects(updateRegion); } fu->nRects = Swap16IfLE((uint16_t)(sraRgnCountRects(updateCopyRegion) + nUpdateRegionRects + !!sendCursorShape + !!sendCursorPos)); } else { fu->nRects = 0xFFFF; } cl->ublen = sz_rfbFramebufferUpdateMsg; UNLOCK(cl->cursorMutex); if (sendCursorShape) { cl->cursorWasChanged = FALSE; if (!rfbSendCursorShape(cl)) goto tx_error; } if (sendCursorPos) { cl->cursorWasMoved = FALSE; if (!rfbSendCursorPos(cl)) goto tx_error; } if (!sraRgnEmpty(updateCopyRegion)) { if (!rfbSendCopyRegion(cl,updateCopyRegion,dx,dy)) goto tx_error; } for(i = sraRgnGetIterator(updateRegion); sraRgnIteratorNext(i,&rect);){ int x = rect.x1; int y = rect.y1; int w = rect.x2 - x; int h = rect.y2 - y; cl->rfbRawBytesEquivalent += (sz_rfbFramebufferUpdateRectHeader + w * (cl->format.bitsPerPixel / 8) * h); switch (cl->preferredEncoding) { case rfbEncodingRaw: if (!rfbSendRectEncodingRaw(cl, x, y, w, h)) goto tx_error; break; case rfbEncodingRRE: if (!rfbSendRectEncodingRRE(cl, x, y, w, h)) goto tx_error; break; case rfbEncodingCoRRE: if (!rfbSendRectEncodingCoRRE(cl, x, y, w, h)) goto tx_error; break; case rfbEncodingHextile: if (!rfbSendRectEncodingHextile(cl, x, y, w, h)) goto tx_error; break; #ifdef HAVE_LIBZ case rfbEncodingZlib: if (!rfbSendRectEncodingZlib(cl, x, y, w, h)) goto tx_error; break; #ifdef HAVE_LIBJPEG case rfbEncodingTight: if (!rfbSendRectEncodingTight(cl, x, y, w, h)) goto tx_error; break; #endif #endif #ifdef HAVE_LIBZ case rfbEncodingZRLE: if (!rfbSendRectEncodingZRLE(cl, x, y, w, h)) goto tx_error; break; #endif } } if (cursorIsDrawn) rfbUndrawCursor(cl->screen, &cursorBounds); if ( nUpdateRegionRects == 0xFFFF && !rfbSendLastRectMarker(cl) ) goto tx_error; if (!rfbSendUpdateBuf(cl)) goto tx_error; sraRgnReleaseIterator(i); sraRgnDestroy(updateCopyRegion); sraRgnDestroy(updateRegion); return TRUE; tx_error: if (cursorIsDrawn) rfbUndrawCursor(cl->screen, &cursorBounds); if (i) sraRgnReleaseIterator(i); sraRgnDestroy(updateCopyRegion); sraRgnDestroy(updateRegion); return FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Avoid out-of-bounds memory accesses This fixes two critical security vulnerabilities that lead to an out-of-bounds memory access with a crafted client framebuffer update request packet. The dimensions of the update from the packet are checked to ensure that they are within the screen dimensions. Thanks to Kevin Chen from the Bitblaze group for the reports in bugs 641802 and 641803. The CVE identifiers for these vulnerabilities are CVE-2011-0904 and CVE-2011-0905.'</s>
<s>[INST] Given the following code containing errors, provide 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 ves_icall_System_Threading_InternalThread_Thread_free_internal (MonoInternalThread *this, HANDLE thread) { MONO_ARCH_SAVE_REGS; THREAD_DEBUG (g_message ("%s: Closing thread %p, handle %p", __func__, this, thread)); if (thread) CloseHandle (thread); if (this->synch_cs) { DeleteCriticalSection (this->synch_cs); g_free (this->synch_cs); this->synch_cs = NULL; } g_free (this->name); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-264'], 'message': 'Fix access to freed members of a dead thread * threads.c: Fix access to freed members of a dead thread. Found and fixed by Rodrigo Kumpera <[email protected]> Ref: CVE-2011-0992'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ves_icall_System_Array_FastCopy (MonoArray *source, int source_idx, MonoArray* dest, int dest_idx, int length) { int element_size; void * dest_addr; void * source_addr; MonoClass *src_class; MonoClass *dest_class; int i; MONO_ARCH_SAVE_REGS; if (source->obj.vtable->klass->rank != dest->obj.vtable->klass->rank) return FALSE; if (source->bounds || dest->bounds) return FALSE; /* there's no integer overflow since mono_array_length returns an unsigned integer */ if ((dest_idx + length > mono_array_length (dest)) || (source_idx + length > mono_array_length (source))) return FALSE; src_class = source->obj.vtable->klass->element_class; dest_class = dest->obj.vtable->klass->element_class; /* * Handle common cases. */ /* Case1: object[] -> valuetype[] (ArrayList::ToArray) */ if (src_class == mono_defaults.object_class && dest_class->valuetype) { int has_refs = dest_class->has_references; for (i = source_idx; i < source_idx + length; ++i) { MonoObject *elem = mono_array_get (source, MonoObject*, i); if (elem && !mono_object_isinst (elem, dest_class)) return FALSE; } element_size = mono_array_element_size (dest->obj.vtable->klass); memset (mono_array_addr_with_size (dest, element_size, dest_idx), 0, element_size * length); for (i = 0; i < length; ++i) { MonoObject *elem = mono_array_get (source, MonoObject*, source_idx + i); void *addr = mono_array_addr_with_size (dest, element_size, dest_idx + i); if (!elem) continue; if (has_refs) mono_value_copy (addr, (char *)elem + sizeof (MonoObject), dest_class); else memcpy (addr, (char *)elem + sizeof (MonoObject), element_size); } return TRUE; } /* Check if we're copying a char[] <==> (u)short[] */ if (src_class != dest_class) { if (dest_class->valuetype || dest_class->enumtype || src_class->valuetype || src_class->enumtype) return FALSE; if (mono_class_is_subclass_of (src_class, dest_class, FALSE)) ; /* Case2: object[] -> reftype[] (ArrayList::ToArray) */ else if (mono_class_is_subclass_of (dest_class, src_class, FALSE)) for (i = source_idx; i < source_idx + length; ++i) { MonoObject *elem = mono_array_get (source, MonoObject*, i); if (elem && !mono_object_isinst (elem, dest_class)) return FALSE; } else return FALSE; } if (dest_class->valuetype) { element_size = mono_array_element_size (source->obj.vtable->klass); source_addr = mono_array_addr_with_size (source, element_size, source_idx); if (dest_class->has_references) { mono_value_copy_array (dest, dest_idx, source_addr, length); } else { dest_addr = mono_array_addr_with_size (dest, element_size, dest_idx); memmove (dest_addr, source_addr, element_size * length); } } else { mono_array_memcpy_refs (dest, dest_idx, source, source_idx, length); } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-264'], 'message': 'Disable some of the FastCopy fast paths since they are racy.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb) { ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-264'], 'message': 'Don't use finalization to cleanup dynamic methods. * reflection.c: Use a reference queue to cleanup dynamic methods instead of finalization. * runtime.c: Shutdown the dynamic method queue before runtime cleanup begins. * DynamicMethod.cs: No longer finalizable. * icall-def.h: Remove unused dynamic method icall. Fixes #660422 Implement a reference queue API. * gc.c: A reference queue allows one to queue callbcks for when objects are collected. It allows for safe cleanup of objects that can only be done when it is effectively collected. The major difference with regular finalization is that the collector makes sure the object was collected - and can't be resurrected. * gc-internal.h: Export entrypoints for the new API.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mono_runtime_shutdown (void) { mono_domain_foreach (fire_process_exit_event, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-264'], 'message': 'Don't use finalization to cleanup dynamic methods. * reflection.c: Use a reference queue to cleanup dynamic methods instead of finalization. * runtime.c: Shutdown the dynamic method queue before runtime cleanup begins. * DynamicMethod.cs: No longer finalizable. * icall-def.h: Remove unused dynamic method icall. Fixes #660422'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void mono_gc_cleanup (void) { } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-264'], 'message': 'Implement a reference queue API. * gc.c: A reference queue allows one to queue callbcks for when objects are collected. It allows for safe cleanup of objects that can only be done when it is effectively collected. The major difference with regular finalization is that the collector makes sure the object was collected - and can't be resurrected. * gc-internal.h: Export entrypoints for the new API.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void mono_gc_init (void) { InitializeCriticalSection (&handle_section); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-264'], 'message': 'Implement a reference queue API. * gc.c: A reference queue allows one to queue callbcks for when objects are collected. It allows for safe cleanup of objects that can only be done when it is effectively collected. The major difference with regular finalization is that the collector makes sure the object was collected - and can't be resurrected. * gc-internal.h: Export entrypoints for the new API.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: add_mtab(char *devname, char *mountpoint, unsigned long flags, const char *fstype) { int rc = 0; uid_t uid; char *mount_user = NULL; struct mntent mountent; FILE *pmntfile; sigset_t mask, oldmask; uid = getuid(); if (uid != 0) mount_user = getusername(uid); /* * Set the real uid to the effective uid. This prevents unprivileged * users from sending signals to this process, though ^c on controlling * terminal should still work. */ rc = setreuid(geteuid(), -1); if (rc != 0) { fprintf(stderr, "Unable to set real uid to effective uid: %s\n", strerror(errno)); return EX_FILEIO; } rc = sigfillset(&mask); if (rc) { fprintf(stderr, "Unable to set filled signal mask\n"); return EX_FILEIO; } rc = sigprocmask(SIG_SETMASK, &mask, &oldmask); if (rc) { fprintf(stderr, "Unable to make process ignore signals\n"); return EX_FILEIO; } rc = toggle_dac_capability(1, 1); if (rc) return EX_FILEIO; atexit(unlock_mtab); rc = lock_mtab(); if (rc) { fprintf(stderr, "cannot lock mtab"); rc = EX_FILEIO; goto add_mtab_exit; } pmntfile = setmntent(MOUNTED, "a+"); if (!pmntfile) { fprintf(stderr, "could not update mount table\n"); unlock_mtab(); rc = EX_FILEIO; goto add_mtab_exit; } mountent.mnt_fsname = devname; mountent.mnt_dir = mountpoint; mountent.mnt_type = (char *)(void *)fstype; mountent.mnt_opts = (char *)calloc(MTAB_OPTIONS_LEN, 1); if (mountent.mnt_opts) { if (flags & MS_RDONLY) strlcat(mountent.mnt_opts, "ro", MTAB_OPTIONS_LEN); else strlcat(mountent.mnt_opts, "rw", MTAB_OPTIONS_LEN); if (flags & MS_MANDLOCK) strlcat(mountent.mnt_opts, ",mand", MTAB_OPTIONS_LEN); if (flags & MS_NOEXEC) strlcat(mountent.mnt_opts, ",noexec", MTAB_OPTIONS_LEN); if (flags & MS_NOSUID) strlcat(mountent.mnt_opts, ",nosuid", MTAB_OPTIONS_LEN); if (flags & MS_NODEV) strlcat(mountent.mnt_opts, ",nodev", MTAB_OPTIONS_LEN); if (flags & MS_SYNCHRONOUS) strlcat(mountent.mnt_opts, ",sync", MTAB_OPTIONS_LEN); if (mount_user) { strlcat(mountent.mnt_opts, ",user=", MTAB_OPTIONS_LEN); strlcat(mountent.mnt_opts, mount_user, MTAB_OPTIONS_LEN); } } mountent.mnt_freq = 0; mountent.mnt_passno = 0; rc = addmntent(pmntfile, &mountent); if (rc) { fprintf(stderr, "unable to add mount entry to mtab\n"); rc = EX_FILEIO; } endmntent(pmntfile); unlock_mtab(); SAFE_FREE(mountent.mnt_opts); add_mtab_exit: toggle_dac_capability(1, 0); sigprocmask(SIG_SETMASK, &oldmask, NULL); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'mtab: handle ENOSPC/EFBIG condition properly when altering mtab It's possible that when mount.cifs goes to append the mtab that there won't be enough space to do so, and the mntent won't be appended to the file in its entirety. Add a my_endmntent routine that will fflush and then fsync the FILE if that succeeds. If either fails then it will truncate the file back to its provided size. It will then call endmntent unconditionally. Have add_mtab call fstat on the opened mtab file in order to get the size of the file before it has been appended. Assuming that that succeeds, use my_endmntent to ensure that the file is not corrupted before closing it. It's possible that we'll have a small race window where the mtab is incorrect, but it should be quickly corrected. This was reported some time ago as CVE-2011-1678: http://openwall.com/lists/oss-security/2011/03/04/9 ...and it seems to fix the reproducer that I was able to come up with. Signed-off-by: Jeff Layton <[email protected]> Reviewed-by: Suresh Jayaraman <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void virtio_blk_handle_read(VirtIOBlockReq *req) { BlockDriverAIOCB *acb; uint64_t sector; sector = ldq_p(&req->out->sector); if (sector & req->dev->sector_mask) { virtio_blk_rw_complete(req, -EIO); return; } acb = bdrv_aio_readv(req->dev->bs, sector, &req->qiov, req->qiov.size / BDRV_SECTOR_SIZE, virtio_blk_rw_complete, req); if (!acb) { virtio_blk_rw_complete(req, -EIO); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'virtio-blk: fail unaligned requests Like all block drivers virtio-blk should not allow small than block size granularity access. But given that the protocol specifies a byte unit length field we currently accept such requests, which cause qemu to abort() in lower layers. Add checks to the main read and write handlers to catch them early. Reported-by: Conor Murphy <[email protected]> Tested-by: Conor Murphy <[email protected]> Signed-off-by: Christoph Hellwig <[email protected]> Reviewed-by: Stefan Hajnoczi <[email protected]> Signed-off-by: Kevin Wolf <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 agp_generic_insert_memory(struct agp_memory * mem, off_t pg_start, int type) { int num_entries; size_t i; off_t j; void *temp; struct agp_bridge_data *bridge; int mask_type; bridge = mem->bridge; if (!bridge) return -EINVAL; if (mem->page_count == 0) return 0; temp = bridge->current_size; switch (bridge->driver->size_type) { case U8_APER_SIZE: num_entries = A_SIZE_8(temp)->num_entries; break; case U16_APER_SIZE: num_entries = A_SIZE_16(temp)->num_entries; break; case U32_APER_SIZE: num_entries = A_SIZE_32(temp)->num_entries; break; case FIXED_APER_SIZE: num_entries = A_SIZE_FIX(temp)->num_entries; break; case LVL2_APER_SIZE: /* The generic routines can't deal with 2 level gatt's */ return -EINVAL; break; default: num_entries = 0; break; } num_entries -= agp_memory_reserved/PAGE_SIZE; if (num_entries < 0) num_entries = 0; if (type != mem->type) return -EINVAL; mask_type = bridge->driver->agp_type_to_mask_type(bridge, type); if (mask_type != 0) { /* The generic routines know nothing of memory types */ return -EINVAL; } /* AK: could wrap */ if ((pg_start + mem->page_count) > num_entries) return -EINVAL; j = pg_start; while (j < (pg_start + mem->page_count)) { if (!PGE_EMPTY(bridge, readl(bridge->gatt_table+j))) return -EBUSY; j++; } if (!mem->is_flushed) { bridge->driver->cache_flush(); mem->is_flushed = true; } for (i = 0, j = pg_start; i < mem->page_count; i++, j++) { writel(bridge->driver->mask_memory(bridge, page_to_phys(mem->pages[i]), mask_type), bridge->gatt_table+j); } readl(bridge->gatt_table+j-1); /* PCI Posting. */ bridge->driver->tlb_flush(mem); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'agp: fix arbitrary kernel memory writes pg_start is copied from userspace on AGPIOC_BIND and AGPIOC_UNBIND ioctl cmds of agp_ioctl() and passed to agpioc_bind_wrap(). As said in the comment, (pg_start + mem->page_count) may wrap in case of AGPIOC_BIND, and it is not checked at all in case of AGPIOC_UNBIND. As a result, user with sufficient privileges (usually "video" group) may generate either local DoS or privilege escalation. Signed-off-by: Vasiliy Kulikov <[email protected]> Signed-off-by: Dave Airlie <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 krb5_save_ccname_done(struct tevent_req *req) { struct krb5_auth_state *state = tevent_req_data(req, struct krb5_auth_state); struct krb5child_req *kr = state->kr; struct pam_data *pd = state->pd; int ret; char *password = NULL; if (kr->is_offline) { if (dp_opt_get_bool(kr->krb5_ctx->opts,KRB5_STORE_PASSWORD_IF_OFFLINE)) { krb5_pam_handler_cache_auth_step(req); return; } DEBUG(4, ("Backend is marked offline, retry later!\n")); state->pam_status = PAM_AUTHINFO_UNAVAIL; state->dp_err = DP_ERR_OFFLINE; ret = EOK; goto done; } if (state->be_ctx->domain->cache_credentials == TRUE) { /* password caching failures are not fatal errors */ state->pam_status = PAM_SUCCESS; state->dp_err = DP_ERR_OK; switch(pd->cmd) { case SSS_PAM_AUTHENTICATE: case SSS_CMD_RENEW: case SSS_PAM_CHAUTHTOK_PRELIM: password = talloc_size(state, pd->authtok_size + 1); if (password != NULL) { memcpy(password, pd->authtok, pd->authtok_size); password[pd->authtok_size] = '\0'; } break; case SSS_PAM_CHAUTHTOK: password = talloc_size(state, pd->newauthtok_size + 1); if (password != NULL) { memcpy(password, pd->newauthtok, pd->newauthtok_size); password[pd->newauthtok_size] = '\0'; } break; default: DEBUG(0, ("unsupported PAM command [%d].\n", pd->cmd)); } if (password == NULL) { DEBUG(0, ("password not available, offline auth may not work.\n")); ret = EOK; /* password caching failures are not fatal errors */ goto done; } talloc_set_destructor((TALLOC_CTX *)password, password_destructor); ret = sysdb_cache_password(state, state->be_ctx->sysdb, state->be_ctx->domain, pd->user, password); if (ret) { DEBUG(2, ("Failed to cache password, offline auth may not work." " (%d)[%s]!?\n", ret, strerror(ret))); } } state->pam_status = PAM_SUCCESS; state->dp_err = DP_ERR_OK; ret = EOK; done: if (ret == EOK) { tevent_req_done(req); } else { tevent_req_error(req, ret); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'Fix bad password caching when using automatic TGT renewal Fixes CVE-2011-1758, https://fedorahosted.org/sssd/ticket/856'</s>
<s>[INST] Given the following code containing errors, provide 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 dkim_exim_verify_finish(void) { pdkim_signature *sig = NULL; int dkim_signers_size = 0; int dkim_signers_ptr = 0; dkim_signers = NULL; /* Delete eventual previous signature chain */ dkim_signatures = NULL; /* If we have arrived here with dkim_collect_input == FALSE, it means there was a processing error somewhere along the way. Log the incident and disable futher verification. */ if (!dkim_collect_input) { log_write(0, LOG_MAIN, "DKIM: Error while running this message through validation, disabling signature verification."); dkim_disable_verify = TRUE; return; } dkim_collect_input = FALSE; /* Finish DKIM operation and fetch link to signatures chain */ if (pdkim_feed_finish(dkim_verify_ctx,&dkim_signatures) != PDKIM_OK) return; sig = dkim_signatures; while (sig != NULL) { int size = 0; int ptr = 0; /* Log a line for each signature */ uschar *logmsg = string_append(NULL, &size, &ptr, 5, string_sprintf( "DKIM: d=%s s=%s c=%s/%s a=%s ", sig->domain, sig->selector, (sig->canon_headers == PDKIM_CANON_SIMPLE)?"simple":"relaxed", (sig->canon_body == PDKIM_CANON_SIMPLE)?"simple":"relaxed", (sig->algo == PDKIM_ALGO_RSA_SHA256)?"rsa-sha256":"rsa-sha1" ), ((sig->identity != NULL)? string_sprintf("i=%s ", sig->identity) : US"" ), ((sig->created > 0)? string_sprintf("t=%lu ", sig->created) : US"" ), ((sig->expires > 0)? string_sprintf("x=%lu ", sig->expires) : US"" ), ((sig->bodylength > -1)? string_sprintf("l=%lu ", sig->bodylength) : US"" ) ); switch(sig->verify_status) { case PDKIM_VERIFY_NONE: logmsg = string_append(logmsg, &size, &ptr, 1, "[not verified]"); break; case PDKIM_VERIFY_INVALID: logmsg = string_append(logmsg, &size, &ptr, 1, "[invalid - "); switch (sig->verify_ext_status) { case PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE: logmsg = string_append(logmsg, &size, &ptr, 1, "public key record (currently?) unavailable]"); break; case PDKIM_VERIFY_INVALID_BUFFER_SIZE: logmsg = string_append(logmsg, &size, &ptr, 1, "overlong public key record]"); break; case PDKIM_VERIFY_INVALID_PUBKEY_PARSING: logmsg = string_append(logmsg, &size, &ptr, 1, "syntax error in public key record]"); break; default: logmsg = string_append(logmsg, &size, &ptr, 1, "unspecified problem]"); } break; case PDKIM_VERIFY_FAIL: logmsg = string_append(logmsg, &size, &ptr, 1, "[verification failed - "); switch (sig->verify_ext_status) { case PDKIM_VERIFY_FAIL_BODY: logmsg = string_append(logmsg, &size, &ptr, 1, "body hash mismatch (body probably modified in transit)]"); break; case PDKIM_VERIFY_FAIL_MESSAGE: logmsg = string_append(logmsg, &size, &ptr, 1, "signature did not verify (headers probably modified in transit)]"); break; default: logmsg = string_append(logmsg, &size, &ptr, 1, "unspecified reason]"); } break; case PDKIM_VERIFY_PASS: logmsg = string_append(logmsg, &size, &ptr, 1, "[verification succeeded]"); break; } logmsg[ptr] = '\0'; log_write(0, LOG_MAIN, (char *)logmsg); /* Build a colon-separated list of signing domains (and identities, if present) in dkim_signers */ dkim_signers = string_append(dkim_signers, &dkim_signers_size, &dkim_signers_ptr, 2, sig->domain, ":" ); if (sig->identity != NULL) { dkim_signers = string_append(dkim_signers, &dkim_signers_size, &dkim_signers_ptr, 2, sig->identity, ":" ); } /* Process next signature */ sig = sig->next; } /* NULL-terminate and chop the last colon from the domain list */ if (dkim_signers != NULL) { dkim_signers[dkim_signers_ptr] = '\0'; if (Ustrlen(dkim_signers) > 0) dkim_signers[Ustrlen(dkim_signers)-1] = '\0'; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-134'], 'message': 'Bugzilla #1106: Don't pass DKIM compound log line as format string'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: policy_summarize(smartlist_t *policy) { smartlist_t *summary = policy_summary_create(); smartlist_t *accepts, *rejects; int i, last, start_prt; size_t accepts_len, rejects_len, shorter_len, final_size; char *accepts_str = NULL, *rejects_str = NULL, *shorter_str, *result; const char *prefix; tor_assert(policy); /* Create the summary list */ SMARTLIST_FOREACH(policy, addr_policy_t *, p, { policy_summary_add_item(summary, p); }); /* Now create two lists of strings, one for accepted and one * for rejected ports. We take care to merge ranges so that * we avoid getting stuff like "1-4,5-9,10", instead we want * "1-10" */ i = 0; start_prt = 1; accepts = smartlist_create(); rejects = smartlist_create(); while (1) { last = i == smartlist_len(summary)-1; if (last || AT(i)->accepted != AT(i+1)->accepted) { char buf[POLICY_BUF_LEN]; if (start_prt == AT(i)->prt_max) tor_snprintf(buf, sizeof(buf), "%d", start_prt); else tor_snprintf(buf, sizeof(buf), "%d-%d", start_prt, AT(i)->prt_max); if (AT(i)->accepted) smartlist_add(accepts, tor_strdup(buf)); else smartlist_add(rejects, tor_strdup(buf)); if (last) break; start_prt = AT(i+1)->prt_min; }; i++; }; /* Figure out which of the two stringlists will be shorter and use * that to build the result */ if (smartlist_len(accepts) == 0) { /* no exits at all */ result = tor_strdup("reject 1-65535"); goto cleanup; } if (smartlist_len(rejects) == 0) { /* no rejects at all */ result = tor_strdup("accept 1-65535"); goto cleanup; } accepts_str = smartlist_join_strings(accepts, ",", 0, &accepts_len); rejects_str = smartlist_join_strings(rejects, ",", 0, &rejects_len); if (rejects_len > MAX_EXITPOLICY_SUMMARY_LEN && accepts_len > MAX_EXITPOLICY_SUMMARY_LEN) { char *c; shorter_str = accepts_str; prefix = "accept"; c = shorter_str + (MAX_EXITPOLICY_SUMMARY_LEN-strlen(prefix)-1); while (*c != ',' && c >= shorter_str) c--; tor_assert(c >= shorter_str); tor_assert(*c == ','); *c = '\0'; shorter_len = strlen(shorter_str); } else if (rejects_len < accepts_len) { shorter_str = rejects_str; shorter_len = rejects_len; prefix = "reject"; } else { shorter_str = accepts_str; shorter_len = accepts_len; prefix = "accept"; } final_size = strlen(prefix)+1+shorter_len+1; tor_assert(final_size <= MAX_EXITPOLICY_SUMMARY_LEN+1); result = tor_malloc(final_size); tor_snprintf(result, final_size, "%s %s", prefix, shorter_str); cleanup: /* cleanup */ SMARTLIST_FOREACH(summary, policy_summary_item_t *, s, tor_free(s)); smartlist_free(summary); tor_free(accepts_str); SMARTLIST_FOREACH(accepts, char *, s, tor_free(s)); smartlist_free(accepts); tor_free(rejects_str); SMARTLIST_FOREACH(rejects, char *, s, tor_free(s)); smartlist_free(rejects); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bounds-checking in policy_summarize Found by piebeer.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlXPathNodeSetMerge(xmlNodeSetPtr val1, xmlNodeSetPtr val2) { int i, j, initNr, skip; xmlNodePtr n1, n2; if (val2 == NULL) return(val1); if (val1 == NULL) { val1 = xmlXPathNodeSetCreate(NULL); if (val1 == NULL) return (NULL); #if 0 /* * TODO: The optimization won't work in every case, since * those nasty namespace nodes need to be added with * xmlXPathNodeSetDupNs() to the set; thus a pure * memcpy is not possible. * If there was a flag on the nodesetval, indicating that * some temporary nodes are in, that would be helpfull. */ /* * Optimization: Create an equally sized node-set * and memcpy the content. */ val1 = xmlXPathNodeSetCreateSize(val2->nodeNr); if (val1 == NULL) return(NULL); if (val2->nodeNr != 0) { if (val2->nodeNr == 1) *(val1->nodeTab) = *(val2->nodeTab); else { memcpy(val1->nodeTab, val2->nodeTab, val2->nodeNr * sizeof(xmlNodePtr)); } val1->nodeNr = val2->nodeNr; } return(val1); #endif } /* @@ with_ns to check whether namespace nodes should be looked at @@ */ initNr = val1->nodeNr; for (i = 0;i < val2->nodeNr;i++) { n2 = val2->nodeTab[i]; /* * check against duplicates */ skip = 0; for (j = 0; j < initNr; j++) { n1 = val1->nodeTab[j]; if (n1 == n2) { skip = 1; break; } else if ((n1->type == XML_NAMESPACE_DECL) && (n2->type == XML_NAMESPACE_DECL)) { if ((((xmlNsPtr) n1)->next == ((xmlNsPtr) n2)->next) && (xmlStrEqual(((xmlNsPtr) n1)->prefix, ((xmlNsPtr) n2)->prefix))) { skip = 1; break; } } } if (skip) continue; /* * grow the nodeTab if needed */ if (val1->nodeMax == 0) { val1->nodeTab = (xmlNodePtr *) xmlMalloc(XML_NODESET_DEFAULT * sizeof(xmlNodePtr)); if (val1->nodeTab == NULL) { xmlXPathErrMemory(NULL, "merging nodeset\n"); return(NULL); } memset(val1->nodeTab, 0 , XML_NODESET_DEFAULT * (size_t) sizeof(xmlNodePtr)); val1->nodeMax = XML_NODESET_DEFAULT; } else if (val1->nodeNr == val1->nodeMax) { xmlNodePtr *temp; val1->nodeMax *= 2; temp = (xmlNodePtr *) xmlRealloc(val1->nodeTab, val1->nodeMax * sizeof(xmlNodePtr)); if (temp == NULL) { xmlXPathErrMemory(NULL, "merging nodeset\n"); return(NULL); } val1->nodeTab = temp; } if (n2->type == XML_NAMESPACE_DECL) { xmlNsPtr ns = (xmlNsPtr) n2; val1->nodeTab[val1->nodeNr++] = xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns); } else val1->nodeTab[val1->nodeNr++] = n2; } return(val1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix some potential problems on reallocation failures The count was incremented before the allocation and not fixed in case of failure * xpath.c: corrects a few instances where the available count of some structure is updated before we know the allocation actually succeeds'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlXPathNodeSetMergeAndClearNoDupls(xmlNodeSetPtr set1, xmlNodeSetPtr set2, int hasNullEntries) { if (set2 == NULL) return(set1); if ((set1 == NULL) && (hasNullEntries == 0)) { /* * Note that doing a memcpy of the list, namespace nodes are * just assigned to set1, since set2 is cleared anyway. */ set1 = xmlXPathNodeSetCreateSize(set2->nodeNr); if (set1 == NULL) return(NULL); if (set2->nodeNr != 0) { memcpy(set1->nodeTab, set2->nodeTab, set2->nodeNr * sizeof(xmlNodePtr)); set1->nodeNr = set2->nodeNr; } } else { int i; xmlNodePtr n2; if (set1 == NULL) set1 = xmlXPathNodeSetCreate(NULL); if (set1 == NULL) return (NULL); for (i = 0;i < set2->nodeNr;i++) { n2 = set2->nodeTab[i]; /* * Skip NULLed entries. */ if (n2 == NULL) continue; if (set1->nodeMax == 0) { set1->nodeTab = (xmlNodePtr *) xmlMalloc( XML_NODESET_DEFAULT * sizeof(xmlNodePtr)); if (set1->nodeTab == NULL) { xmlXPathErrMemory(NULL, "merging nodeset\n"); return(NULL); } memset(set1->nodeTab, 0, XML_NODESET_DEFAULT * (size_t) sizeof(xmlNodePtr)); set1->nodeMax = XML_NODESET_DEFAULT; } else if (set1->nodeNr >= set1->nodeMax) { xmlNodePtr *temp; set1->nodeMax *= 2; temp = (xmlNodePtr *) xmlRealloc( set1->nodeTab, set1->nodeMax * sizeof(xmlNodePtr)); if (temp == NULL) { xmlXPathErrMemory(NULL, "merging nodeset\n"); return(NULL); } set1->nodeTab = temp; } set1->nodeTab[set1->nodeNr++] = n2; } } set2->nodeNr = 0; return(set1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix some potential problems on reallocation failures The count was incremented before the allocation and not fixed in case of failure * xpath.c: corrects a few instances where the available count of some structure is updated before we know the allocation actually succeeds'</s>
<s>[INST] Given the following code containing errors, provide 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 hfs_btree *hfs_btree_open(struct super_block *sb, u32 id, btree_keycmp keycmp) { struct hfs_btree *tree; struct hfs_btree_header_rec *head; struct address_space *mapping; struct page *page; unsigned int size; tree = kzalloc(sizeof(*tree), GFP_KERNEL); if (!tree) return NULL; mutex_init(&tree->tree_lock); spin_lock_init(&tree->hash_lock); /* Set the correct compare function */ tree->sb = sb; tree->cnid = id; tree->keycmp = keycmp; tree->inode = iget_locked(sb, id); if (!tree->inode) goto free_tree; BUG_ON(!(tree->inode->i_state & I_NEW)); { struct hfs_mdb *mdb = HFS_SB(sb)->mdb; HFS_I(tree->inode)->flags = 0; mutex_init(&HFS_I(tree->inode)->extents_lock); switch (id) { case HFS_EXT_CNID: hfs_inode_read_fork(tree->inode, mdb->drXTExtRec, mdb->drXTFlSize, mdb->drXTFlSize, be32_to_cpu(mdb->drXTClpSiz)); tree->inode->i_mapping->a_ops = &hfs_btree_aops; break; case HFS_CAT_CNID: hfs_inode_read_fork(tree->inode, mdb->drCTExtRec, mdb->drCTFlSize, mdb->drCTFlSize, be32_to_cpu(mdb->drCTClpSiz)); tree->inode->i_mapping->a_ops = &hfs_btree_aops; break; default: BUG(); } } unlock_new_inode(tree->inode); if (!HFS_I(tree->inode)->first_blocks) { printk(KERN_ERR "hfs: invalid btree extent records (0 size).\n"); goto free_inode; } mapping = tree->inode->i_mapping; page = read_mapping_page(mapping, 0, NULL); if (IS_ERR(page)) goto free_inode; /* Load the header */ head = (struct hfs_btree_header_rec *)(kmap(page) + sizeof(struct hfs_bnode_desc)); tree->root = be32_to_cpu(head->root); tree->leaf_count = be32_to_cpu(head->leaf_count); tree->leaf_head = be32_to_cpu(head->leaf_head); tree->leaf_tail = be32_to_cpu(head->leaf_tail); tree->node_count = be32_to_cpu(head->node_count); tree->free_nodes = be32_to_cpu(head->free_nodes); tree->attributes = be32_to_cpu(head->attributes); tree->node_size = be16_to_cpu(head->node_size); tree->max_key_len = be16_to_cpu(head->max_key_len); tree->depth = be16_to_cpu(head->depth); size = tree->node_size; if (!is_power_of_2(size)) goto fail_page; if (!tree->node_count) goto fail_page; switch (id) { case HFS_EXT_CNID: if (tree->max_key_len != HFS_MAX_EXT_KEYLEN) { printk(KERN_ERR "hfs: invalid extent max_key_len %d\n", tree->max_key_len); goto fail_page; } break; case HFS_CAT_CNID: if (tree->max_key_len != HFS_MAX_CAT_KEYLEN) { printk(KERN_ERR "hfs: invalid catalog max_key_len %d\n", tree->max_key_len); goto fail_page; } break; default: BUG(); } tree->node_size_shift = ffs(size) - 1; tree->pages_per_bnode = (tree->node_size + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT; kunmap(page); page_cache_release(page); return tree; fail_page: page_cache_release(page); free_inode: tree->inode->i_mapping->a_ops = &hfs_aops; iput(tree->inode); free_tree: kfree(tree); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'hfs: fix hfs_find_init() sb->ext_tree NULL ptr oops Clement Lecigne reports a filesystem which causes a kernel oops in hfs_find_init() trying to dereference sb->ext_tree which is NULL. This proves to be because the filesystem has a corrupted MDB extent record, where the extents file does not fit into the first three extents in the file record (the first blocks). In hfs_get_block() when looking up the blocks for the extent file (HFS_EXT_CNID), it fails the first blocks special case, and falls through to the extent code (which ultimately calls hfs_find_init()) which is in the process of being initialised. Hfs avoids this scenario by always having the extents b-tree fitting into the first blocks (the extents B-tree can't have overflow extents). The fix is to check at mount time that the B-tree fits into first blocks, i.e. fail if HFS_I(inode)->alloc_blocks >= HFS_I(inode)->first_blocks Note, the existing commit 47f365eb57573 ("hfs: fix oops on mount with corrupted btree extent records") becomes subsumed into this as a special case, but only for the extents B-tree (HFS_EXT_CNID), it is perfectly acceptable for the catalog B-Tree file to grow beyond three extents, with the remaining extent descriptors in the extents overfow. This fixes CVE-2011-2203 Reported-by: Clement LECIGNE <[email protected]> Signed-off-by: Phillip Lougher <[email protected]> Cc: Jeff Mahoney <[email protected]> Cc: Christoph Hellwig <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: const char *string_of_NPPVariable(int variable) { const char *str; switch (variable) { #define _(VAL) case VAL: str = #VAL; break; _(NPPVpluginNameString); _(NPPVpluginDescriptionString); _(NPPVpluginWindowBool); _(NPPVpluginTransparentBool); _(NPPVjavaClass); _(NPPVpluginWindowSize); _(NPPVpluginTimerInterval); _(NPPVpluginScriptableInstance); _(NPPVpluginScriptableIID); _(NPPVjavascriptPushCallerBool); _(NPPVpluginKeepLibraryInMemory); _(NPPVpluginNeedsXEmbed); _(NPPVpluginScriptableNPObject); _(NPPVformValue); #undef _ default: switch (variable & 0xff) { #define _(VAL, VAR) case VAL: str = #VAR; break _(10, NPPVpluginScriptableInstance); #undef _ default: str = "<unknown variable>"; break; } break; } return str; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Support all the new variables added'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: g_NPN_GetValue(NPP instance, NPNVariable variable, void *value) { D(bug("NPN_GetValue instance=%p, variable=%d [%s]\n", instance, variable, string_of_NPNVariable(variable))); if (!thread_check()) { npw_printf("WARNING: NPN_GetValue not called from the main thread\n"); return NPERR_INVALID_INSTANCE_ERROR; } PluginInstance *plugin = NULL; if (instance) plugin = PLUGIN_INSTANCE(instance); switch (variable) { case NPNVxDisplay: *(void **)value = x_display; break; case NPNVxtAppContext: *(void **)value = XtDisplayToApplicationContext(x_display); break; case NPNVToolkit: *(NPNToolkitType *)value = NPW_TOOLKIT; break; #if USE_XPCOM case NPNVserviceManager: { nsIServiceManager *sm; int ret = NS_GetServiceManager(&sm); if (NS_FAILED(ret)) { npw_printf("WARNING: NS_GetServiceManager failed\n"); return NPERR_GENERIC_ERROR; } *(nsIServiceManager **)value = sm; break; } case NPNVDOMWindow: case NPNVDOMElement: npw_printf("WARNING: %s is not supported by NPN_GetValue()\n", string_of_NPNVariable(variable)); return NPERR_INVALID_PARAM; #endif case NPNVnetscapeWindow: if (plugin == NULL) { npw_printf("ERROR: NPNVnetscapeWindow requires a non NULL instance\n"); return NPERR_INVALID_INSTANCE_ERROR; } if (plugin->browser_toplevel == NULL) { GdkNativeWindow netscape_xid = None; NPError error = g_NPN_GetValue_real(instance, variable, &netscape_xid); if (error != NPERR_NO_ERROR) return error; if (netscape_xid == None) return NPERR_GENERIC_ERROR; plugin->browser_toplevel = gdk_window_foreign_new(netscape_xid); if (plugin->browser_toplevel == NULL) return NPERR_GENERIC_ERROR; } *((GdkNativeWindow *)value) = GDK_WINDOW_XWINDOW(plugin->browser_toplevel); break; #if ALLOW_WINDOWLESS_PLUGINS case NPNVSupportsWindowless: #endif case NPNVSupportsXEmbedBool: case NPNVWindowNPObject: case NPNVPluginElementNPObject: return g_NPN_GetValue_real(instance, variable, value); default: switch (variable & 0xff) { case 13: /* NPNVToolkit */ if (NPW_TOOLKIT == NPNVGtk2) { // Gtk2 does not need to depend on a specific C++ ABI *(NPNToolkitType *)value = NPW_TOOLKIT; return NPERR_NO_ERROR; } break; } D(bug("WARNING: unhandled variable %d (%s) in NPN_GetValue()\n", variable, string_of_NPNVariable(variable))); return NPERR_INVALID_PARAM; } return NPERR_NO_ERROR; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Support all the new variables added'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int rpc_type_of_NPNVariable(int variable) { int type; switch (variable) { case NPNVjavascriptEnabledBool: case NPNVasdEnabledBool: case NPNVisOfflineBool: case NPNVSupportsXEmbedBool: case NPNVSupportsWindowless: type = RPC_TYPE_BOOLEAN; break; case NPNVToolkit: case NPNVnetscapeWindow: type = RPC_TYPE_UINT32; break; case NPNVWindowNPObject: case NPNVPluginElementNPObject: type = RPC_TYPE_NP_OBJECT; break; default: type = RPC_ERROR_GENERIC; break; } return type; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Support all the new variables added'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlCharEncInFunc(xmlCharEncodingHandler * handler, xmlBufferPtr out, xmlBufferPtr in) { int ret = -2; int written; int toconv; if (handler == NULL) return (-1); if (out == NULL) return (-1); if (in == NULL) return (-1); toconv = in->use; if (toconv == 0) return (0); written = out->size - out->use; if (toconv * 2 >= written) { xmlBufferGrow(out, out->size + toconv * 2); written = out->size - out->use - 1; } if (handler->input != NULL) { ret = handler->input(&out->content[out->use], &written, in->content, &toconv); xmlBufferShrink(in, toconv); out->use += written; out->content[out->use] = 0; } #ifdef LIBXML_ICONV_ENABLED else if (handler->iconv_in != NULL) { ret = xmlIconvWrapper(handler->iconv_in, &out->content[out->use], &written, in->content, &toconv); xmlBufferShrink(in, toconv); out->use += written; out->content[out->use] = 0; if (ret == -1) ret = -3; } #endif /* LIBXML_ICONV_ENABLED */ #ifdef LIBXML_ICU_ENABLED else if (handler->uconv_in != NULL) { ret = xmlUconvWrapper(handler->uconv_in, 1, &out->content[out->use], &written, in->content, &toconv); xmlBufferShrink(in, toconv); out->use += written; out->content[out->use] = 0; if (ret == -1) ret = -3; } #endif /* LIBXML_ICU_ENABLED */ switch (ret) { case 0: #ifdef DEBUG_ENCODING xmlGenericError(xmlGenericErrorContext, "converted %d bytes to %d bytes of input\n", toconv, written); #endif break; case -1: #ifdef DEBUG_ENCODING xmlGenericError(xmlGenericErrorContext, "converted %d bytes to %d bytes of input, %d left\n", toconv, written, in->use); #endif break; case -3: #ifdef DEBUG_ENCODING xmlGenericError(xmlGenericErrorContext, "converted %d bytes to %d bytes of input, %d left\n", toconv, written, in->use); #endif break; case -2: { char buf[50]; snprintf(&buf[0], 49, "0x%02X 0x%02X 0x%02X 0x%02X", in->content[0], in->content[1], in->content[2], in->content[3]); buf[49] = 0; xmlEncodingErr(XML_I18N_CONV_FAILED, "input conversion failed due to input error, bytes %s\n", buf); } } /* * Ignore when input buffer is not on a boundary */ if (ret == -3) ret = 0; return (written? written : ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix an off by one error in encoding this off by one error doesn't seems to reproduce on linux but the error is real.'</s>
<s>[INST] Given the following code containing errors, provide 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 NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name) { unsigned upper_length; int len, type, optlen; char *dest, *ret; /* option points to OPT_DATA, need to go back to get OPT_LEN */ len = option[-OPT_DATA + OPT_LEN]; type = optflag->flags & OPTION_TYPE_MASK; optlen = dhcp_option_lengths[type]; upper_length = len_of_option_as_string[type] * ((unsigned)(len + optlen - 1) / (unsigned)optlen); dest = ret = xmalloc(upper_length + strlen(opt_name) + 2); dest += sprintf(ret, "%s=", opt_name); while (len >= optlen) { switch (type) { case OPTION_IP: case OPTION_IP_PAIR: dest += sprint_nip(dest, "", option); if (type == OPTION_IP) break; dest += sprint_nip(dest, "/", option + 4); break; // case OPTION_BOOLEAN: // dest += sprintf(dest, *option ? "yes" : "no"); // break; case OPTION_U8: dest += sprintf(dest, "%u", *option); break; // case OPTION_S16: case OPTION_U16: { uint16_t val_u16; move_from_unaligned16(val_u16, option); dest += sprintf(dest, "%u", ntohs(val_u16)); break; } case OPTION_S32: case OPTION_U32: { uint32_t val_u32; move_from_unaligned32(val_u32, option); dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32)); break; } /* Note: options which use 'return' instead of 'break' * (for example, OPTION_STRING) skip the code which handles * the case of list of options. */ case OPTION_STRING: memcpy(dest, option, len); dest[len] = '\0'; return ret; case OPTION_STATIC_ROUTES: { /* Option binary format: * mask [one byte, 0..32] * ip [big endian, 0..4 bytes depending on mask] * router [big endian, 4 bytes] * may be repeated * * We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2" */ const char *pfx = ""; while (len >= 1 + 4) { /* mask + 0-byte ip + router */ uint32_t nip; uint8_t *p; unsigned mask; int bytes; mask = *option++; if (mask > 32) break; len--; nip = 0; p = (void*) &nip; bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */ while (--bytes >= 0) { *p++ = *option++; len--; } if (len < 4) break; /* print ip/mask */ dest += sprint_nip(dest, pfx, (void*) &nip); pfx = " "; dest += sprintf(dest, "/%u ", mask); /* print router */ dest += sprint_nip(dest, "", option); option += 4; len -= 4; } return ret; } case OPTION_6RD: /* Option binary format (see RFC 5969): * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 6rdPrefix | * ... (16 octets) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ... 6rdBRIPv4Address(es) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * We convert it to a string * "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..." * * Sanity check: ensure that our length is at least 22 bytes, that * IPv4MaskLen <= 32, * 6rdPrefixLen <= 128, * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128 * (2nd condition need no check - it follows from 1st and 3rd). * Else, return envvar with empty value ("optname=") */ if (len >= (1 + 1 + 16 + 4) && option[0] <= 32 && (option[1] + 32 - option[0]) <= 128 ) { /* IPv4MaskLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefixLen */ dest += sprintf(dest, "%u ", *option++); /* 6rdPrefix */ dest += sprint_nip6(dest, /* "", */ option); option += 16; len -= 1 + 1 + 16 + 4; /* "+ 4" above corresponds to the length of IPv4 addr * we consume in the loop below */ while (1) { /* 6rdBRIPv4Address(es) */ dest += sprint_nip(dest, " ", option); option += 4; len -= 4; /* do we have yet another 4+ bytes? */ if (len < 0) break; /* no */ } } return ret; #if ENABLE_FEATURE_UDHCP_RFC3397 case OPTION_DNS_STRING: /* unpack option into dest; use ret for prefix (i.e., "optname=") */ dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } /* error. return "optname=" string */ return ret; case OPTION_SIP_SERVERS: /* Option binary format: * type: byte * type=0: domain names, dns-compressed * type=1: IP addrs */ option++; len--; if (option[-1] == 0) { dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } } else if (option[-1] == 1) { const char *pfx = ""; while (1) { len -= 4; if (len < 0) break; dest += sprint_nip(dest, pfx, option); pfx = " "; option += 4; } } return ret; #endif } /* switch */ /* If we are here, try to format any remaining data * in the option as another, similarly-formatted option */ option += optlen; len -= optlen; // TODO: it can be a list only if (optflag->flags & OPTION_LIST). // Should we bail out/warn if we see multi-ip option which is // not allowed to be such (for example, DHCP_BROADCAST)? - if (len < optlen /* || !(optflag->flags & OPTION_LIST) */) break; *dest++ = ' '; *dest = '\0'; } /* while */ return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'udhcpc: sanitize hostnames in incoming packets. Closes 3979. The following options are replaced with string "bad" if they contain malformed hostname: HOST_NAME, DOMAIN_NAME, NIS_DOMAIN, TFTP_SERVER_NAME function old new delta xmalloc_optname_optval 850 888 +38 attach_option 440 443 +3 len_of_option_as_string 13 14 +1 dhcp_option_lengths 13 14 +1 ------------------------------------------------------------------------------ (add/remove: 0/0 grow/shrink: 4/0 up/down: 43/0) Total: 43 bytes Signed-off-by: Denys Vlasenko <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 NOINLINE void attach_option( struct option_set **opt_list, const struct dhcp_optflag *optflag, char *buffer, int length) { struct option_set *existing, *new, **curr; char *allocated = NULL; existing = udhcp_find_option(*opt_list, optflag->code); if (!existing) { log2("Attaching option %02x to list", optflag->code); allocated = allocate_tempopt_if_needed(optflag, buffer, &length); #if ENABLE_FEATURE_UDHCP_RFC3397 if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_DNS_STRING) { /* reuse buffer and length for RFC1035-formatted string */ allocated = buffer = (char *)dname_enc(NULL, 0, buffer, &length); } #endif /* make a new option */ new = xmalloc(sizeof(*new)); new->data = xmalloc(length + OPT_DATA); new->data[OPT_CODE] = optflag->code; new->data[OPT_LEN] = length; memcpy(new->data + OPT_DATA, (allocated ? allocated : buffer), length); curr = opt_list; while (*curr && (*curr)->data[OPT_CODE] < optflag->code) curr = &(*curr)->next; new->next = *curr; *curr = new; goto ret; } if (optflag->flags & OPTION_LIST) { unsigned old_len; /* add it to an existing option */ log2("Attaching option %02x to existing member of list", optflag->code); allocated = allocate_tempopt_if_needed(optflag, buffer, &length); old_len = existing->data[OPT_LEN]; #if ENABLE_FEATURE_UDHCP_RFC3397 if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_DNS_STRING) { /* reuse buffer and length for RFC1035-formatted string */ allocated = buffer = (char *)dname_enc(existing->data + OPT_DATA, old_len, buffer, &length); } #endif if (old_len + length < 255) { /* actually 255 is ok too, but adding a space can overlow it */ existing->data = xrealloc(existing->data, OPT_DATA + 1 + old_len + length); if ((optflag->flags & OPTION_TYPE_MASK) == OPTION_STRING) { /* add space separator between STRING options in a list */ existing->data[OPT_DATA + old_len] = ' '; old_len++; } memcpy(existing->data + OPT_DATA + old_len, buffer, length); existing->data[OPT_LEN] = old_len + length; } /* else, ignore the data, we could put this in a second option in the future */ } /* else, ignore the new data */ ret: free(allocated); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'udhcpc: sanitize hostnames in incoming packets. Closes 3979. The following options are replaced with string "bad" if they contain malformed hostname: HOST_NAME, DOMAIN_NAME, NIS_DOMAIN, TFTP_SERVER_NAME function old new delta xmalloc_optname_optval 850 888 +38 attach_option 440 443 +3 len_of_option_as_string 13 14 +1 dhcp_option_lengths 13 14 +1 ------------------------------------------------------------------------------ (add/remove: 0/0 grow/shrink: 4/0 up/down: 43/0) Total: 43 bytes Signed-off-by: Denys Vlasenko <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 check_mtab(const char *progname, const char *devname, const char *dir) { if (check_newline(progname, devname) == -1 || check_newline(progname, dir) == -1) return EX_USAGE; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'mount.cifs: check_newline returns EX_USAGE on error, not -1 Reported-by: Jan Lieskovsky <[email protected]> Signed-off-by: Jeff Layton <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdk_pixbuf__png_image_stop_load (gpointer context, GError **error) { LoadContext* lc = context; g_return_val_if_fail(lc != NULL, TRUE); /* FIXME this thing needs to report errors if * we have unused image data */ gdk_pixbuf_unref(lc->pixbuf); png_destroy_read_struct(&lc->png_read_ptr, NULL, NULL); g_free(lc); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <[email protected]> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lzw_read_byte (GifContext *context) { int code, incode; gint retval; gint my_retval; register int i; if (context->lzw_code_pending != -1) { retval = context->lzw_code_pending; context->lzw_code_pending = -1; return retval; } if (context->lzw_fresh) { context->lzw_fresh = FALSE; do { retval = get_code (context, context->lzw_code_size); if (retval < 0) { return retval; } context->lzw_firstcode = context->lzw_oldcode = retval; } while (context->lzw_firstcode == context->lzw_clear_code); return context->lzw_firstcode; } if (context->lzw_sp > context->lzw_stack) { my_retval = *--(context->lzw_sp); return my_retval; } while ((code = get_code (context, context->lzw_code_size)) >= 0) { if (code == context->lzw_clear_code) { for (i = 0; i < context->lzw_clear_code; ++i) { context->lzw_table[0][i] = 0; context->lzw_table[1][i] = i; } for (; i < (1 << MAX_LZW_BITS); ++i) context->lzw_table[0][i] = context->lzw_table[1][i] = 0; context->lzw_code_size = context->lzw_set_code_size + 1; context->lzw_max_code_size = 2 * context->lzw_clear_code; context->lzw_max_code = context->lzw_clear_code + 2; context->lzw_sp = context->lzw_stack; set_gif_lzw_clear_code (context); return -3; } else if (code == context->lzw_end_code) { int count; unsigned char buf[260]; /*g_error (" DID WE EVER EVER GET HERE\n");*/ g_warning ("Unhandled Case. If you have an image that causes this, let me <[email protected]> know.\n"); if (ZeroDataBlock) { return -2; } while ((count = GetDataBlock (context, buf)) > 0) ; if (count != 0) { /*g_print (_("GIF: missing EOD in data stream (common occurence)"));*/ return -2; } } incode = code; if (code >= context->lzw_max_code) { *(context->lzw_sp)++ = context->lzw_firstcode; code = context->lzw_oldcode; } while (code >= context->lzw_clear_code) { *(context->lzw_sp)++ = context->lzw_table[1][code]; if (code == context->lzw_table[0][code]) { g_set_error (context->error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE, _("Circular table entry in GIF file")); return -2; } code = context->lzw_table[0][code]; } *(context->lzw_sp)++ = context->lzw_firstcode = context->lzw_table[1][code]; if ((code = context->lzw_max_code) < (1 << MAX_LZW_BITS)) { context->lzw_table[0][code] = context->lzw_oldcode; context->lzw_table[1][code] = context->lzw_firstcode; ++context->lzw_max_code; if ((context->lzw_max_code >= context->lzw_max_code_size) && (context->lzw_max_code_size < (1 << MAX_LZW_BITS))) { context->lzw_max_code_size *= 2; ++context->lzw_code_size; } } context->lzw_oldcode = incode; if (context->lzw_sp > context->lzw_stack) { my_retval = *--(context->lzw_sp); return my_retval; } } return code; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <[email protected]> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdk_pixbuf_loader_close (GdkPixbufLoader *loader, GError **error) { GdkPixbufLoaderPrivate *priv; gboolean retval = TRUE; g_return_val_if_fail (loader != NULL, TRUE); g_return_val_if_fail (GDK_IS_PIXBUF_LOADER (loader), TRUE); priv = loader->priv; /* we expect it's not closed */ g_return_val_if_fail (priv->closed == FALSE, TRUE); /* We have less the 128 bytes in the image. Flush it, and keep going. */ if (priv->image_module == NULL) gdk_pixbuf_loader_load_module (loader, NULL, NULL); if (priv->image_module && priv->image_module->stop_load) retval = priv->image_module->stop_load (priv->context, error); priv->closed = TRUE; g_signal_emit (G_OBJECT (loader), pixbuf_loader_signals[CLOSED], 0); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <[email protected]> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gif_read (GifContext *context, guchar *buffer, size_t len) { gint retval; #ifdef IO_GIFDEBUG gint i; #endif if (context->file) { #ifdef IO_GIFDEBUG count += len; g_print ("Fsize :%d\tcount :%d\t", len, count); #endif retval = (fread(buffer, len, 1, context->file) != 0); if (!retval && ferror (context->file)) g_set_error (context->error, G_FILE_ERROR, g_file_error_from_errno (errno), _("Failure reading GIF: %s"), strerror (errno)); #ifdef IO_GIFDEBUG if (len < 100) { for (i = 0; i < len; i++) g_print ("%d ", buffer[i]); } g_print ("\n"); #endif return retval; } else { #ifdef IO_GIFDEBUG /* g_print ("\tlooking for %d bytes. size == %d, ptr == %d\n", len, context->size, context->ptr); */ #endif if ((context->size - context->ptr) >= len) { #ifdef IO_GIFDEBUG count += len; #endif memcpy (buffer, context->buf + context->ptr, len); context->ptr += len; context->amount_needed = 0; #ifdef IO_GIFDEBUG g_print ("Psize :%d\tcount :%d\t", len, count); if (len < 100) { for (i = 0; i < len; i++) g_print ("%d ", buffer[i]); } g_print ("\n"); #endif return TRUE; } context->amount_needed = len - (context->size - context->ptr); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <[email protected]> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdk_pixbuf__tiff_fill_vtable (GdkPixbufModule *module) { module->load = gdk_pixbuf__tiff_image_load; module->begin_load = gdk_pixbuf__tiff_image_begin_load; module->stop_load = gdk_pixbuf__tiff_image_stop_load; module->load_increment = gdk_pixbuf__tiff_image_load_increment; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <[email protected]> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdk_pixbuf__tiff_image_load_increment (gpointer data, const guchar *buf, guint size, GError **error) { TiffData *context = (TiffData *) data; g_return_val_if_fail (data != NULL, FALSE); if (fwrite (buf, sizeof (guchar), size, context->file) != size) { context->all_okay = FALSE; g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (errno), _("Failed to write to temporary file when loading TIFF image")); return FALSE; } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <[email protected]> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdk_pixbuf__gif_image_begin_load (ModulePreparedNotifyFunc prepare_func, ModuleUpdatedNotifyFunc update_func, gpointer user_data, GError **error) { GifContext *context; #ifdef IO_GIFDEBUG count = 0; #endif context = new_context (); context->error = error; context->prepare_func = prepare_func; context->update_func = update_func; context->user_data = user_data; return (gpointer) context; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <[email protected]> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdk_pixbuf__png_image_save (FILE *f, GdkPixbuf *pixbuf, gchar **keys, gchar **values, GError **error) { png_structp png_ptr; png_infop info_ptr; guchar *ptr; guchar *pixels; int x, y, j; png_bytep row_ptr, data = NULL; png_color_8 sig_bit; int w, h, rowstride; int has_alpha; int bpc; if (keys && *keys) { g_warning ("Bad option name '%s' passed to PNG saver", *keys); return FALSE; #if 0 gchar **kiter = keys; gchar **viter = values; while (*kiter) { ++kiter; ++viter; } #endif } bpc = gdk_pixbuf_get_bits_per_sample (pixbuf); w = gdk_pixbuf_get_width (pixbuf); h = gdk_pixbuf_get_height (pixbuf); rowstride = gdk_pixbuf_get_rowstride (pixbuf); has_alpha = gdk_pixbuf_get_has_alpha (pixbuf); pixels = gdk_pixbuf_get_pixels (pixbuf); png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, error, png_simple_error_callback, png_simple_warning_callback); g_return_val_if_fail (png_ptr != NULL, FALSE); info_ptr = png_create_info_struct (png_ptr); if (info_ptr == NULL) { png_destroy_write_struct (&png_ptr, (png_infopp) NULL); return FALSE; } if (setjmp (png_ptr->jmpbuf)) { png_destroy_write_struct (&png_ptr, (png_infopp) NULL); return FALSE; } png_init_io (png_ptr, f); if (has_alpha) { png_set_IHDR (png_ptr, info_ptr, w, h, bpc, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); #ifdef WORDS_BIGENDIAN png_set_swap_alpha (png_ptr); #else png_set_bgr (png_ptr); #endif } else { png_set_IHDR (png_ptr, info_ptr, w, h, bpc, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); data = g_try_malloc (w * 3 * sizeof (char)); if (data == NULL) { /* Check error NULL, normally this would be broken, * but libpng makes me want to code defensively. */ if (error && *error == NULL) { g_set_error (error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_INSUFFICIENT_MEMORY, _("Insufficient memory to save PNG file")); } png_destroy_write_struct (&png_ptr, (png_infopp) NULL); return FALSE; } } sig_bit.red = bpc; sig_bit.green = bpc; sig_bit.blue = bpc; sig_bit.alpha = bpc; png_set_sBIT (png_ptr, info_ptr, &sig_bit); png_write_info (png_ptr, info_ptr); png_set_shift (png_ptr, &sig_bit); png_set_packing (png_ptr); ptr = pixels; for (y = 0; y < h; y++) { if (has_alpha) row_ptr = (png_bytep)ptr; else { for (j = 0, x = 0; x < w; x++) memcpy (&(data[x*3]), &(ptr[x*3]), 3); row_ptr = (png_bytep)data; } png_write_rows (png_ptr, &row_ptr, 1); ptr += rowstride; } if (data) g_free (data); png_write_end (png_ptr, info_ptr); png_destroy_write_struct (&png_ptr, (png_infopp) NULL); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <[email protected]> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gdk_pixbuf__gif_image_load_increment (gpointer data, const guchar *buf, guint size, GError **error) { gint retval; GifContext *context = (GifContext *) data; context->error = error; if (context->amount_needed == 0) { /* we aren't looking for some bytes. */ /* we can use buf now, but we don't want to keep it around at all. * it will be gone by the end of the call. */ context->buf = (guchar*) buf; /* very dubious const cast */ context->ptr = 0; context->size = size; } else { /* we need some bytes */ if (size < context->amount_needed) { context->amount_needed -= size; /* copy it over and return */ memcpy (context->buf + context->size, buf, size); context->size += size; return TRUE; } else if (size == context->amount_needed) { memcpy (context->buf + context->size, buf, size); context->size += size; } else { context->buf = g_realloc (context->buf, context->size + size); memcpy (context->buf + context->size, buf, size); context->size += size; } } retval = gif_main_loop (context); if (retval == -2) return FALSE; if (retval == -1) { /* we didn't have enough memory */ /* prepare for the next image_load_increment */ if (context->buf == buf) { g_assert (context->size == size); context->buf = (guchar *)g_new (guchar, context->amount_needed + (context->size - context->ptr)); memcpy (context->buf, buf + context->ptr, context->size - context->ptr); } else { /* copy the left overs to the begining of the buffer */ /* and realloc the memory */ memmove (context->buf, context->buf + context->ptr, context->size - context->ptr); context->buf = g_realloc (context->buf, context->amount_needed + (context->size - context->ptr)); } context->size = context->size - context->ptr; context->ptr = 0; } else { /* we are prolly all done */ if (context->buf == buf) context->buf = NULL; } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <[email protected]> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gif_prepare_lzw (GifContext *context) { gint i; if (!gif_read (context, &(context->lzw_set_code_size), 1)) { /*g_message (_("GIF: EOF / read error on image data\n"));*/ return -1; } context->lzw_code_size = context->lzw_set_code_size + 1; context->lzw_clear_code = 1 << context->lzw_set_code_size; context->lzw_end_code = context->lzw_clear_code + 1; context->lzw_max_code_size = 2 * context->lzw_clear_code; context->lzw_max_code = context->lzw_clear_code + 2; context->lzw_fresh = TRUE; context->code_curbit = 0; context->code_lastbit = 0; context->code_last_byte = 0; context->code_done = FALSE; for (i = 0; i < context->lzw_clear_code; ++i) { context->lzw_table[0][i] = 0; context->lzw_table[1][i] = i; } for (; i < (1 << MAX_LZW_BITS); ++i) context->lzw_table[0][i] = context->lzw_table[1][0] = 0; context->lzw_sp = context->lzw_stack; gif_set_get_lzw (context); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Initial stab at getting the focus code to work. Fri Jun 1 18:54:47 2001 Jonathan Blandford <[email protected]> * gtk/gtktreeview.c: (gtk_tree_view_focus): Initial stab at getting the focus code to work. (gtk_tree_view_class_init): Add a bunch of keybindings. * gtk/gtktreeviewcolumn.c (gtk_tree_view_column_set_cell_data_func): s/GtkCellDataFunc/GtkTreeCellDataFunc. (_gtk_tree_view_column_set_tree_view): Use "notify::model" instead of "properties_changed" to help justify the death of the latter signal. (-: * tests/testtreefocus.c (main): Let some columns be focussable to test focus better.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: LZWReadByte (FILE *fd, int flag, int input_code_size) { static int fresh = FALSE; int code, incode; static int code_size, set_code_size; static int max_code, max_code_size; static int firstcode, oldcode; static int clear_code, end_code; static int table[2][(1 << MAX_LZW_BITS)]; static int stack[(1 << (MAX_LZW_BITS)) * 2], *sp; register int i; if (flag) { set_code_size = input_code_size; code_size = set_code_size + 1; clear_code = 1 << set_code_size; end_code = clear_code + 1; max_code_size = 2 * clear_code; max_code = clear_code + 2; GetCode (fd, 0, TRUE); fresh = TRUE; for (i = 0; i < clear_code; ++i) { table[0][i] = 0; table[1][i] = i; } for (; i < (1 << MAX_LZW_BITS); ++i) table[0][i] = table[1][0] = 0; sp = stack; return 0; } else if (fresh) { fresh = FALSE; do { firstcode = oldcode = GetCode (fd, code_size, FALSE); } while (firstcode == clear_code); return firstcode; } if (sp > stack) return *--sp; while ((code = GetCode (fd, code_size, FALSE)) >= 0) { if (code == clear_code) { for (i = 0; i < clear_code; ++i) { table[0][i] = 0; table[1][i] = i; } for (; i < (1 << MAX_LZW_BITS); ++i) table[0][i] = table[1][i] = 0; code_size = set_code_size + 1; max_code_size = 2 * clear_code; max_code = clear_code + 2; sp = stack; firstcode = oldcode = GetCode (fd, code_size, FALSE); return firstcode; } else if (code == end_code) { int count; unsigned char buf[260]; if (ZeroDataBlock) return -2; while ((count = GetDataBlock (fd, buf)) > 0) ; if (count != 0) g_print ("GIF: missing EOD in data stream (common occurence)"); return -2; } incode = code; if (code >= max_code) { *sp++ = firstcode; code = oldcode; } while (code >= clear_code) { *sp++ = table[1][code]; if (code == table[0][code]) { g_message ("GIF: circular table entry BIG ERROR\n"); gimp_quit (); } code = table[0][code]; } *sp++ = firstcode = table[1][code]; if ((code = max_code) < (1 << MAX_LZW_BITS)) { table[0][code] = oldcode; table[1][code] = firstcode; ++max_code; if ((max_code >= max_code_size) && (max_code_size < (1 << MAX_LZW_BITS))) { max_code_size *= 2; ++code_size; } } oldcode = incode; if (sp > stack) return *--sp; } return code; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'When initializing the LZW state, watch out for a completely bogus * plug-ins/common/gifload.c: When initializing the LZW state, watch out for a completely bogus input_code_size [based on fix by Raphael Quinet] Also, fix a stupid old bug when clearing the code table between subimages. (Enables us to deal better with errors when the stream is corrupted pretty early in a subimage.) [me]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: LZWReadByte (FILE *fd, gint just_reset_LZW, gint input_code_size) { static gint fresh = FALSE; gint code, incode; static gint code_size, set_code_size; static gint max_code, max_code_size; static gint firstcode, oldcode; static gint clear_code, end_code; static gint table[2][(1 << MAX_LZW_BITS)]; static gint stack[(1 << (MAX_LZW_BITS)) * 2], *sp; gint i; if (just_reset_LZW) { if (input_code_size > MAX_LZW_BITS) { g_message ("Value out of range for code size (corrupted file?)"); return -1; } set_code_size = input_code_size; code_size = set_code_size + 1; clear_code = 1 << set_code_size; end_code = clear_code + 1; max_code_size = 2 * clear_code; max_code = clear_code + 2; GetCode (fd, 0, TRUE); fresh = TRUE; sp = stack; for (i = 0; i < clear_code; ++i) { table[0][i] = 0; table[1][i] = i; } for (; i < (1 << MAX_LZW_BITS); ++i) { table[0][i] = 0; table[1][i] = 0; } return 0; } else if (fresh) { fresh = FALSE; do { firstcode = oldcode = GetCode (fd, code_size, FALSE); } while (firstcode == clear_code); return firstcode & 255; } if (sp > stack) return (*--sp) & 255; while ((code = GetCode (fd, code_size, FALSE)) >= 0) { if (code == clear_code) { for (i = 0; i < clear_code; ++i) { table[0][i] = 0; table[1][i] = i; } for (; i < (1 << MAX_LZW_BITS); ++i) { table[0][i] = 0; table[1][i] = 0; } code_size = set_code_size + 1; max_code_size = 2 * clear_code; max_code = clear_code + 2; sp = stack; firstcode = oldcode = GetCode (fd, code_size, FALSE); return firstcode & 255; } else if (code == end_code) { gint count; guchar buf[260]; if (ZeroDataBlock) return -2; while ((count = GetDataBlock (fd, buf)) > 0) ; if (count != 0) g_print ("GIF: missing EOD in data stream (common occurence)"); return -2; } incode = code; if (code >= max_code) { *sp++ = firstcode; code = oldcode; } while (code >= clear_code) { *sp++ = table[1][code]; if (code == table[0][code]) { g_message ("Circular table entry. Corrupt file."); gimp_quit (); } code = table[0][code]; } *sp++ = firstcode = table[1][code]; if ((code = max_code) < (1 << MAX_LZW_BITS)) { table[0][code] = oldcode; table[1][code] = firstcode; ++max_code; if ((max_code >= max_code_size) && (max_code_size < (1 << MAX_LZW_BITS))) { max_code_size *= 2; ++code_size; } } oldcode = incode; if (sp > stack) return (*--sp) & 255; } return code & 255; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'file-gif-load: fix heap corruption and buffer overflow (CVE-2011-2896)'</s>
<s>[INST] Given the following code containing errors, provide 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 tpm_transmit(struct tpm_chip *chip, const char *buf, size_t bufsiz) { ssize_t rc; u32 count, ordinal; unsigned long stop; count = be32_to_cpu(*((__be32 *) (buf + 2))); ordinal = be32_to_cpu(*((__be32 *) (buf + 6))); if (count == 0) return -ENODATA; if (count > bufsiz) { dev_err(chip->dev, "invalid count value %x %zx \n", count, bufsiz); return -E2BIG; } mutex_lock(&chip->tpm_mutex); if ((rc = chip->vendor.send(chip, (u8 *) buf, count)) < 0) { dev_err(chip->dev, "tpm_transmit: tpm_send: error %zd\n", rc); goto out; } if (chip->vendor.irq) goto out_recv; stop = jiffies + tpm_calc_ordinal_duration(chip, ordinal); do { u8 status = chip->vendor.status(chip); if ((status & chip->vendor.req_complete_mask) == chip->vendor.req_complete_val) goto out_recv; if ((status == chip->vendor.req_canceled)) { dev_err(chip->dev, "Operation Canceled\n"); rc = -ECANCELED; goto out; } msleep(TPM_TIMEOUT); /* CHECK */ rmb(); } while (time_before(jiffies, stop)); chip->vendor.cancel(chip); dev_err(chip->dev, "Operation Timed out\n"); rc = -ETIME; goto out; out_recv: rc = chip->vendor.recv(chip, (u8 *) buf, bufsiz); if (rc < 0) dev_err(chip->dev, "tpm_transmit: tpm_recv: error %zd\n", rc); out: mutex_unlock(&chip->tpm_mutex); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'TPM: Call tpm_transmit with correct size This patch changes the call of tpm_transmit by supplying the size of the userspace buffer instead of TPM_BUFSIZE. This got assigned CVE-2011-1161. [The first hunk didn't make much sense given one could expect way less data than TPM_BUFSIZE, so added tpm_transmit boundary check over bufsiz instead] Signed-off-by: Rajiv Andrade <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jiffies_to_timespec(const unsigned long jiffies, struct timespec *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &value->tv_nsec); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline unsigned long do_div_llr(const long long dividend, const long divisor, long *remainder) { u64 result = dividend; *(remainder) = do_div(result, divisor); return (unsigned long) result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 sgi_clock_get(clockid_t clockid, struct timespec *tp) { u64 nsec; nsec = rtc_time() * sgi_clock_period + sgi_clock_offset.tv_nsec; tp->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &tp->tv_nsec) + sgi_clock_offset.tv_sec; return 0; }; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 sgi_clock_set(clockid_t clockid, struct timespec *tp) { u64 nsec; u64 rem; nsec = rtc_time() * sgi_clock_period; sgi_clock_offset.tv_sec = tp->tv_sec - div_long_long_rem(nsec, NSEC_PER_SEC, &rem); if (rem <= tp->tv_nsec) sgi_clock_offset.tv_nsec = tp->tv_sec - rem; else { sgi_clock_offset.tv_nsec = tp->tv_sec + NSEC_PER_SEC - rem; sgi_clock_offset.tv_sec--; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline long div_ll_X_l_rem(long long divs, long div, long *rem) { long dum2; asm("divl %2":"=a"(dum2), "=d"(*rem) : "rm"(div), "A"(divs)); return dum2; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 sgi_timer_set(struct k_itimer *timr, int flags, struct itimerspec * new_setting, struct itimerspec * old_setting) { unsigned long when, period, irqflags; int err = 0; cnodeid_t nodeid; struct mmtimer *base; struct rb_node *n; if (old_setting) sgi_timer_get(timr, old_setting); sgi_timer_del(timr); when = timespec_to_ns(new_setting->it_value); period = timespec_to_ns(new_setting->it_interval); if (when == 0) /* Clear timer */ return 0; base = kmalloc(sizeof(struct mmtimer), GFP_KERNEL); if (base == NULL) return -ENOMEM; if (flags & TIMER_ABSTIME) { struct timespec n; unsigned long now; getnstimeofday(&n); now = timespec_to_ns(n); if (when > now) when -= now; else /* Fire the timer immediately */ when = 0; } /* * Convert to sgi clock period. Need to keep rtc_time() as near as possible * to getnstimeofday() in order to be as faithful as possible to the time * specified. */ when = (when + sgi_clock_period - 1) / sgi_clock_period + rtc_time(); period = (period + sgi_clock_period - 1) / sgi_clock_period; /* * We are allocating a local SHub comparator. If we would be moved to another * cpu then another SHub may be local to us. Prohibit that by switching off * preemption. */ preempt_disable(); nodeid = cpu_to_node(smp_processor_id()); /* Lock the node timer structure */ spin_lock_irqsave(&timers[nodeid].lock, irqflags); base->timer = timr; base->cpu = smp_processor_id(); timr->it.mmtimer.clock = TIMER_SET; timr->it.mmtimer.node = nodeid; timr->it.mmtimer.incr = period; timr->it.mmtimer.expires = when; n = timers[nodeid].next; /* Add the new struct mmtimer to node's timer list */ mmtimer_add_list(base); if (timers[nodeid].next == n) { /* No need to reprogram comparator for now */ spin_unlock_irqrestore(&timers[nodeid].lock, irqflags); preempt_enable(); return err; } /* We need to reprogram the comparator */ if (n) mmtimer_disable_int(cnodeid_to_nasid(nodeid), COMPARATOR); mmtimer_set_next_timer(nodeid); /* Unlock the node timer structure */ spin_unlock_irqrestore(&timers[nodeid].lock, irqflags); preempt_enable(); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 list_locations(struct kmem_cache *s, char *buf, enum track_item alloc) { int len = 0; unsigned long i; struct loc_track t = { 0, 0, NULL }; int node; if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location), GFP_TEMPORARY)) return sprintf(buf, "Out of memory\n"); /* Push back cpu slabs */ flush_all(s); for_each_node_state(node, N_NORMAL_MEMORY) { struct kmem_cache_node *n = get_node(s, node); unsigned long flags; struct page *page; if (!atomic_long_read(&n->nr_slabs)) continue; spin_lock_irqsave(&n->list_lock, flags); list_for_each_entry(page, &n->partial, lru) process_slab(&t, s, page, alloc); list_for_each_entry(page, &n->full, lru) process_slab(&t, s, page, alloc); spin_unlock_irqrestore(&n->list_lock, flags); } for (i = 0; i < t.count; i++) { struct location *l = &t.loc[i]; if (len > PAGE_SIZE - 100) break; len += sprintf(buf + len, "%7ld ", l->count); if (l->addr) len += sprint_symbol(buf + len, (unsigned long)l->addr); else len += sprintf(buf + len, "<not-available>"); if (l->sum_time != l->min_time) { unsigned long remainder; len += sprintf(buf + len, " age=%ld/%ld/%ld", l->min_time, div_long_long_rem(l->sum_time, l->count, &remainder), l->max_time); } else len += sprintf(buf + len, " age=%ld", l->min_time); if (l->min_pid != l->max_pid) len += sprintf(buf + len, " pid=%ld-%ld", l->min_pid, l->max_pid); else len += sprintf(buf + len, " pid=%ld", l->min_pid); if (num_online_cpus() > 1 && !cpus_empty(l->cpus) && len < PAGE_SIZE - 60) { len += sprintf(buf + len, " cpus="); len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50, l->cpus); } if (num_online_nodes() > 1 && !nodes_empty(l->nodes) && len < PAGE_SIZE - 60) { len += sprintf(buf + len, " nodes="); len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50, l->nodes); } len += sprintf(buf + len, "\n"); } free_loc_track(&t); if (!t.count) len += sprintf(buf, "No data\n"); return len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pam_sm_authenticate (pam_handle_t * pamh, int flags, int argc, const char **argv) { int retval, rc; const char *user = NULL; const char *password = NULL; char otp[MAX_TOKEN_ID_LEN + TOKEN_OTP_LEN + 1] = { 0 }; char otp_id[MAX_TOKEN_ID_LEN + 1] = { 0 }; int password_len = 0; int skip_bytes = 0; int valid_token = 0; struct pam_conv *conv; struct pam_message *pmsg[1], msg[1]; struct pam_response *resp; int nargs = 1; ykclient_t *ykc = NULL; struct cfg cfg_st; struct cfg *cfg = &cfg_st; /* for DBG macro */ parse_cfg (flags, argc, argv, cfg); retval = pam_get_user (pamh, &user, NULL); if (retval != PAM_SUCCESS) { DBG (("get user returned error: %s", pam_strerror (pamh, retval))); goto done; } DBG (("get user returned: %s", user)); if (cfg->mode == CHRESP) { #if HAVE_LIBYKPERS_1 return do_challenge_response(pamh, cfg, user); #else DBG (("no support for challenge/response")); retval = PAM_AUTH_ERR; goto done; #endif } if (cfg->try_first_pass || cfg->use_first_pass) { retval = pam_get_item (pamh, PAM_AUTHTOK, (const void **) &password); if (retval != PAM_SUCCESS) { DBG (("get password returned error: %s", pam_strerror (pamh, retval))); goto done; } DBG (("get password returned: %s", password)); } if (cfg->use_first_pass && password == NULL) { DBG (("use_first_pass set and no password, giving up")); retval = PAM_AUTH_ERR; goto done; } rc = ykclient_init (&ykc); if (rc != YKCLIENT_OK) { DBG (("ykclient_init() failed (%d): %s", rc, ykclient_strerror (rc))); retval = PAM_AUTHINFO_UNAVAIL; goto done; } rc = ykclient_set_client_b64 (ykc, cfg->client_id, cfg->client_key); if (rc != YKCLIENT_OK) { DBG (("ykclient_set_client_b64() failed (%d): %s", rc, ykclient_strerror (rc))); retval = PAM_AUTHINFO_UNAVAIL; goto done; } if (cfg->capath) ykclient_set_ca_path (ykc, cfg->capath); if (cfg->url) ykclient_set_url_template (ykc, cfg->url); if (password == NULL) { retval = pam_get_item (pamh, PAM_CONV, (const void **) &conv); if (retval != PAM_SUCCESS) { DBG (("get conv returned error: %s", pam_strerror (pamh, retval))); goto done; } pmsg[0] = &msg[0]; { const char *query_template = "Yubikey for `%s': "; size_t len = strlen (query_template) + strlen (user); size_t wrote; msg[0].msg = malloc (len); if (!msg[0].msg) { retval = PAM_BUF_ERR; goto done; } wrote = snprintf ((char *) msg[0].msg, len, query_template, user); if (wrote < 0 || wrote >= len) { retval = PAM_BUF_ERR; goto done; } } msg[0].msg_style = cfg->verbose_otp ? PAM_PROMPT_ECHO_ON : PAM_PROMPT_ECHO_OFF; resp = NULL; retval = conv->conv (nargs, (const struct pam_message **) pmsg, &resp, conv->appdata_ptr); free ((char *) msg[0].msg); if (retval != PAM_SUCCESS) { DBG (("conv returned error: %s", pam_strerror (pamh, retval))); goto done; } if (resp->resp == NULL) { DBG (("conv returned NULL passwd?")); goto done; } DBG (("conv returned %i bytes", strlen(resp->resp))); password = resp->resp; } password_len = strlen (password); if (password_len < (cfg->token_id_length + TOKEN_OTP_LEN)) { DBG (("OTP too short to be considered : %i < %i", password_len, (cfg->token_id_length + TOKEN_OTP_LEN))); retval = PAM_AUTH_ERR; goto done; } /* In case the input was systempassword+YubiKeyOTP, we want to skip over "systempassword" when copying the token_id and OTP to separate buffers */ skip_bytes = password_len - (cfg->token_id_length + TOKEN_OTP_LEN); DBG (("Skipping first %i bytes. Length is %i, token_id set to %i and token OTP always %i.", skip_bytes, password_len, cfg->token_id_length, TOKEN_OTP_LEN)); /* Copy full YubiKey output (public ID + OTP) into otp */ strncpy (otp, password + skip_bytes, sizeof (otp) - 1); /* Copy only public ID into otp_id. Destination buffer is zeroed. */ strncpy (otp_id, password + skip_bytes, cfg->token_id_length); DBG (("OTP: %s ID: %s ", otp, otp_id)); /* user entered their system password followed by generated OTP? */ if (password_len > TOKEN_OTP_LEN + cfg->token_id_length) { char *onlypasswd = strdup (password); onlypasswd[password_len - (TOKEN_OTP_LEN + cfg->token_id_length)] = '\0'; DBG (("Extracted a probable system password entered before the OTP - " "setting item PAM_AUTHTOK")); retval = pam_set_item (pamh, PAM_AUTHTOK, onlypasswd); free (onlypasswd); if (retval != PAM_SUCCESS) { DBG (("set_item returned error: %s", pam_strerror (pamh, retval))); goto done; } } else password = NULL; rc = ykclient_request (ykc, otp); DBG (("ykclient return value (%d): %s", rc, ykclient_strerror (rc))); switch (rc) { case YKCLIENT_OK: break; case YKCLIENT_BAD_OTP: case YKCLIENT_REPLAYED_OTP: retval = PAM_AUTH_ERR; goto done; default: retval = PAM_AUTHINFO_UNAVAIL; goto done; } /* authorize the user with supplied token id */ if (cfg->ldapserver != NULL || cfg->ldap_uri != NULL) valid_token = authorize_user_token_ldap (cfg, user, otp_id); else valid_token = authorize_user_token (cfg, user, otp_id); if (valid_token == 0) { DBG (("Yubikey not authorized to login as user")); retval = PAM_AUTHINFO_UNAVAIL; goto done; } retval = PAM_SUCCESS; done: if (ykc) ykclient_done (&ykc); if (cfg->alwaysok && retval != PAM_SUCCESS) { DBG (("alwaysok needed (otherwise return with %d)", retval)); retval = PAM_SUCCESS; } DBG (("done. [%s]", pam_strerror (pamh, retval))); pam_set_data (pamh, "yubico_setcred_return", (void*) (intptr_t) retval, NULL); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix big security hole: Authentication succeeded when no password was given, unless use_first_pass was being used. This is fatal if pam_yubico is considered 'sufficient' in the PAM configuration. Signed-off-by: Nanakos Chrysostomos <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlXPtrEvalXPointer(xmlXPathParserContextPtr ctxt) { if (ctxt->valueTab == NULL) { /* Allocate the value stack */ ctxt->valueTab = (xmlXPathObjectPtr *) xmlMalloc(10 * sizeof(xmlXPathObjectPtr)); if (ctxt->valueTab == NULL) { xmlXPtrErrMemory("allocating evaluation context"); return; } ctxt->valueNr = 0; ctxt->valueMax = 10; ctxt->value = NULL; } SKIP_BLANKS; if (CUR == '/') { xmlXPathRoot(ctxt); xmlXPtrEvalChildSeq(ctxt, NULL); } else { xmlChar *name; name = xmlXPathParseName(ctxt); if (name == NULL) XP_ERROR(XPATH_EXPR_ERROR); if (CUR == '(') { xmlXPtrEvalFullXPtr(ctxt, name); /* Short evaluation */ return; } else { /* this handle both Bare Names and Child Sequences */ xmlXPtrEvalChildSeq(ctxt, name); } } SKIP_BLANKS; if (CUR != 0) XP_ERROR(XPATH_EXPR_ERROR); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Hardening of XPath evaluation Add a mechanism of frame for XPath evaluation when entering a function or a scoped evaluation, also fix a potential problem in predicate evaluation.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op, xmlNodeSetPtr set, int contextSize, int minPos, int maxPos, int hasNsNodes) { if (op->ch1 != -1) { xmlXPathCompExprPtr comp = ctxt->comp; if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) { /* * TODO: raise an internal error. */ } contextSize = xmlXPathCompOpEvalPredicate(ctxt, &comp->steps[op->ch1], set, contextSize, hasNsNodes); CHECK_ERROR0; if (contextSize <= 0) return(0); } /* * Check if the node set contains a sufficient number of nodes for * the requested range. */ if (contextSize < minPos) { xmlXPathNodeSetClear(set, hasNsNodes); return(0); } if (op->ch2 == -1) { /* * TODO: Can this ever happen? */ return (contextSize); } else { xmlDocPtr oldContextDoc; int i, pos = 0, newContextSize = 0, contextPos = 0, res; xmlXPathStepOpPtr exprOp; xmlXPathObjectPtr contextObj = NULL, exprRes = NULL; xmlNodePtr oldContextNode, contextNode = NULL; xmlXPathContextPtr xpctxt = ctxt->context; #ifdef LIBXML_XPTR_ENABLED /* * URGENT TODO: Check the following: * We don't expect location sets if evaluating prediates, right? * Only filters should expect location sets, right? */ #endif /* LIBXML_XPTR_ENABLED */ /* * Save old context. */ oldContextNode = xpctxt->node; oldContextDoc = xpctxt->doc; /* * Get the expression of this predicate. */ exprOp = &ctxt->comp->steps[op->ch2]; for (i = 0; i < set->nodeNr; i++) { if (set->nodeTab[i] == NULL) continue; contextNode = set->nodeTab[i]; xpctxt->node = contextNode; xpctxt->contextSize = contextSize; xpctxt->proximityPosition = ++contextPos; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ if ((contextNode->type != XML_NAMESPACE_DECL) && (contextNode->doc != NULL)) xpctxt->doc = contextNode->doc; /* * Evaluate the predicate expression with 1 context node * at a time; this node is packaged into a node set; this * node set is handed over to the evaluation mechanism. */ if (contextObj == NULL) contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode); else xmlXPathNodeSetAddUnique(contextObj->nodesetval, contextNode); valuePush(ctxt, contextObj); res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1); if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) { xmlXPathObjectPtr tmp; /* pop the result if any */ tmp = valuePop(ctxt); if (tmp != contextObj) { /* * Free up the result * then pop off contextObj, which will be freed later */ xmlXPathReleaseObject(xpctxt, tmp); valuePop(ctxt); } goto evaluation_error; } if (res) pos++; if (res && (pos >= minPos) && (pos <= maxPos)) { /* * Fits in the requested range. */ newContextSize++; if (minPos == maxPos) { /* * Only 1 node was requested. */ if (contextNode->type == XML_NAMESPACE_DECL) { /* * As always: take care of those nasty * namespace nodes. */ set->nodeTab[i] = NULL; } xmlXPathNodeSetClear(set, hasNsNodes); set->nodeNr = 1; set->nodeTab[0] = contextNode; goto evaluation_exit; } if (pos == maxPos) { /* * We are done. */ xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes); goto evaluation_exit; } } else { /* * Remove the entry from the initial node set. */ set->nodeTab[i] = NULL; if (contextNode->type == XML_NAMESPACE_DECL) xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode); } if (exprRes != NULL) { xmlXPathReleaseObject(ctxt->context, exprRes); exprRes = NULL; } if (ctxt->value == contextObj) { /* * Don't free the temporary XPath object holding the * context node, in order to avoid massive recreation * inside this loop. */ valuePop(ctxt); xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes); } else { /* * The object was lost in the evaluation machinery. * Can this happen? Maybe in case of internal-errors. */ contextObj = NULL; } } goto evaluation_exit; evaluation_error: xmlXPathNodeSetClear(set, hasNsNodes); newContextSize = 0; evaluation_exit: if (contextObj != NULL) { if (ctxt->value == contextObj) valuePop(ctxt); xmlXPathReleaseObject(xpctxt, contextObj); } if (exprRes != NULL) xmlXPathReleaseObject(ctxt->context, exprRes); /* * Reset/invalidate the context. */ xpctxt->node = oldContextNode; xpctxt->doc = oldContextDoc; xpctxt->contextSize = -1; xpctxt->proximityPosition = -1; return(newContextSize); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Hardening of XPath evaluation Add a mechanism of frame for XPath evaluation when entering a function or a scoped evaluation, also fix a potential problem in predicate evaluation.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: */ static int xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op) { int total = 0; int equal, ret; xmlXPathCompExprPtr comp; xmlXPathObjectPtr arg1, arg2; xmlNodePtr bak; xmlDocPtr bakd; int pp; int cs; CHECK_ERROR0; comp = ctxt->comp; switch (op->op) { case XPATH_OP_END: return (0); case XPATH_OP_AND: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 0)) return (total); arg2 = valuePop(ctxt); ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); arg1 = valuePop(ctxt); arg1->boolval &= arg2->boolval; valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_OR: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; xmlXPathBooleanFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->boolval == 1)) return (total); arg2 = valuePop(ctxt); ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error) { xmlXPathFreeObject(arg2); return(0); } xmlXPathBooleanFunction(ctxt, 1); arg1 = valuePop(ctxt); arg1->boolval |= arg2->boolval; valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_EQUAL: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value) equal = xmlXPathEqualValues(ctxt); else equal = xmlXPathNotEqualValues(ctxt); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal)); return (total); case XPATH_OP_CMP: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; ret = xmlXPathCompareValues(ctxt, op->value, op->value2); valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, ret)); return (total); case XPATH_OP_PLUS: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) { ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); } CHECK_ERROR0; if (op->value == 0) xmlXPathSubValues(ctxt); else if (op->value == 1) xmlXPathAddValues(ctxt); else if (op->value == 2) xmlXPathValueFlipSign(ctxt); else if (op->value == 3) { CAST_TO_NUMBER; CHECK_TYPE0(XPATH_NUMBER); } return (total); case XPATH_OP_MULT: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; if (op->value == 0) xmlXPathMultValues(ctxt); else if (op->value == 1) xmlXPathDivValues(ctxt); else if (op->value == 2) xmlXPathModValues(ctxt); return (total); case XPATH_OP_UNION: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; ctxt->context->doc = bakd; ctxt->context->node = bak; ctxt->context->proximityPosition = pp; ctxt->context->contextSize = cs; total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; CHECK_TYPE0(XPATH_NODESET); arg2 = valuePop(ctxt); CHECK_TYPE0(XPATH_NODESET); arg1 = valuePop(ctxt); if ((arg1->nodesetval == NULL) || ((arg2->nodesetval != NULL) && (arg2->nodesetval->nodeNr != 0))) { arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval, arg2->nodesetval); } valuePush(ctxt, arg1); xmlXPathReleaseObject(ctxt->context, arg2); return (total); case XPATH_OP_ROOT: xmlXPathRoot(ctxt); return (total); case XPATH_OP_NODE: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node)); return (total); case XPATH_OP_RESET: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; ctxt->context->node = NULL; return (total); case XPATH_OP_COLLECT:{ if (op->ch1 == -1) return (total); total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 0); return (total); } case XPATH_OP_VALUE: valuePush(ctxt, xmlXPathCacheObjectCopy(ctxt->context, (xmlXPathObjectPtr) op->value4)); return (total); case XPATH_OP_VARIABLE:{ xmlXPathObjectPtr val; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (op->value5 == NULL) { val = xmlXPathVariableLookup(ctxt->context, op->value4); if (val == NULL) { ctxt->error = XPATH_UNDEF_VARIABLE_ERROR; return(0); } valuePush(ctxt, val); } else { const xmlChar *URI; URI = xmlXPathNsLookup(ctxt->context, op->value5); if (URI == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: variable %s bound to undefined prefix %s\n", (char *) op->value4, (char *)op->value5); return (total); } val = xmlXPathVariableLookupNS(ctxt->context, op->value4, URI); if (val == NULL) { ctxt->error = XPATH_UNDEF_VARIABLE_ERROR; return(0); } valuePush(ctxt, val); } return (total); } case XPATH_OP_FUNCTION:{ xmlXPathFunction func; const xmlChar *oldFunc, *oldFuncURI; int i; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (ctxt->valueNr < op->value) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: parameter error\n"); ctxt->error = XPATH_INVALID_OPERAND; return (total); } for (i = 0; i < op->value; i++) if (ctxt->valueTab[(ctxt->valueNr - 1) - i] == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: parameter error\n"); ctxt->error = XPATH_INVALID_OPERAND; return (total); } if (op->cache != NULL) XML_CAST_FPTR(func) = op->cache; else { const xmlChar *URI = NULL; if (op->value5 == NULL) func = xmlXPathFunctionLookup(ctxt->context, op->value4); else { URI = xmlXPathNsLookup(ctxt->context, op->value5); if (URI == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: function %s bound to undefined prefix %s\n", (char *)op->value4, (char *)op->value5); return (total); } func = xmlXPathFunctionLookupNS(ctxt->context, op->value4, URI); } if (func == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlXPathCompOpEval: function %s not found\n", (char *)op->value4); XP_ERROR0(XPATH_UNKNOWN_FUNC_ERROR); } op->cache = XML_CAST_FPTR(func); op->cacheURI = (void *) URI; } oldFunc = ctxt->context->function; oldFuncURI = ctxt->context->functionURI; ctxt->context->function = op->value4; ctxt->context->functionURI = op->cacheURI; func(ctxt, op->value); ctxt->context->function = oldFunc; ctxt->context->functionURI = oldFuncURI; return (total); } case XPATH_OP_ARG: bakd = ctxt->context->doc; bak = ctxt->context->node; pp = ctxt->context->proximityPosition; cs = ctxt->context->contextSize; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); ctxt->context->contextSize = cs; ctxt->context->proximityPosition = pp; ctxt->context->node = bak; ctxt->context->doc = bakd; CHECK_ERROR0; if (op->ch2 != -1) { total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); ctxt->context->doc = bakd; ctxt->context->node = bak; CHECK_ERROR0; } return (total); case XPATH_OP_PREDICATE: case XPATH_OP_FILTER:{ xmlXPathObjectPtr res; xmlXPathObjectPtr obj, tmp; xmlNodeSetPtr newset = NULL; xmlNodeSetPtr oldset; xmlNodePtr oldnode; xmlDocPtr oldDoc; int i; /* * Optimization for ()[1] selection i.e. the first elem */ if ((op->ch1 != -1) && (op->ch2 != -1) && #ifdef XP_OPTIMIZED_FILTER_FIRST /* * FILTER TODO: Can we assume that the inner processing * will result in an ordered list if we have an * XPATH_OP_FILTER? * What about an additional field or flag on * xmlXPathObject like @sorted ? This way we wouln'd need * to assume anything, so it would be more robust and * easier to optimize. */ ((comp->steps[op->ch1].op == XPATH_OP_SORT) || /* 18 */ (comp->steps[op->ch1].op == XPATH_OP_FILTER)) && /* 17 */ #else (comp->steps[op->ch1].op == XPATH_OP_SORT) && #endif (comp->steps[op->ch2].op == XPATH_OP_VALUE)) { /* 12 */ xmlXPathObjectPtr val; val = comp->steps[op->ch2].value4; if ((val != NULL) && (val->type == XPATH_NUMBER) && (val->floatval == 1.0)) { xmlNodePtr first = NULL; total += xmlXPathCompOpEvalFirst(ctxt, &comp->steps[op->ch1], &first); CHECK_ERROR0; /* * The nodeset should be in document order, * Keep only the first value */ if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) ctxt->value->nodesetval->nodeNr = 1; return (total); } } /* * Optimization for ()[last()] selection i.e. the last elem */ if ((op->ch1 != -1) && (op->ch2 != -1) && (comp->steps[op->ch1].op == XPATH_OP_SORT) && (comp->steps[op->ch2].op == XPATH_OP_SORT)) { int f = comp->steps[op->ch2].ch1; if ((f != -1) && (comp->steps[f].op == XPATH_OP_FUNCTION) && (comp->steps[f].value5 == NULL) && (comp->steps[f].value == 0) && (comp->steps[f].value4 != NULL) && (xmlStrEqual (comp->steps[f].value4, BAD_CAST "last"))) { xmlNodePtr last = NULL; total += xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch1], &last); CHECK_ERROR0; /* * The nodeset should be in document order, * Keep only the last value */ if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeTab != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) { ctxt->value->nodesetval->nodeTab[0] = ctxt->value->nodesetval->nodeTab[ctxt-> value-> nodesetval-> nodeNr - 1]; ctxt->value->nodesetval->nodeNr = 1; } return (total); } } /* * Process inner predicates first. * Example "index[parent::book][1]": * ... * PREDICATE <-- we are here "[1]" * PREDICATE <-- process "[parent::book]" first * SORT * COLLECT 'parent' 'name' 'node' book * NODE * ELEM Object is a number : 1 */ if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if (op->ch2 == -1) return (total); if (ctxt->value == NULL) return (total); oldnode = ctxt->context->node; #ifdef LIBXML_XPTR_ENABLED /* * Hum are we filtering the result of an XPointer expression */ if (ctxt->value->type == XPATH_LOCATIONSET) { xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; /* * Extract the old locset, and then evaluate the result of the * expression for all the element in the locset. use it to grow * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); obj = valuePop(ctxt); oldlocset = obj->user; ctxt->context->node = NULL; if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); res = valuePop(ctxt); if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } valuePush(ctxt, obj); CHECK_ERROR0; return (total); } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { /* * Run the evaluation with a node list made of a * single item in the nodelocset. */ ctxt->context->node = oldlocset->locTab[i]->user; ctxt->context->contextSize = oldlocset->locNr; ctxt->context->proximityPosition = i + 1; tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } /* * The result of the evaluation need to be tested to * decided whether the filter succeeded or not */ res = valuePop(ctxt); if (xmlXPathEvaluatePredicateResult(ctxt, res)) { xmlXPtrLocationSetAdd(newlocset, xmlXPathObjectCopy (oldlocset->locTab[i])); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } /* * The result is used as the new evaluation locset. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); ctxt->context->node = oldnode; return (total); } #endif /* LIBXML_XPTR_ENABLED */ /* * Extract the old set, and then evaluate the result of the * expression for all the element in the set. use it to grow * up a new set. */ CHECK_TYPE0(XPATH_NODESET); obj = valuePop(ctxt); oldset = obj->nodesetval; oldnode = ctxt->context->node; oldDoc = ctxt->context->doc; ctxt->context->node = NULL; if ((oldset == NULL) || (oldset->nodeNr == 0)) { ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; /* if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); CHECK_ERROR0; res = valuePop(ctxt); if (res != NULL) xmlXPathFreeObject(res); */ valuePush(ctxt, obj); ctxt->context->node = oldnode; CHECK_ERROR0; } else { tmp = NULL; /* * Initialize the new set. * Also set the xpath document in case things like * key() evaluation are attempted on the predicate */ newset = xmlXPathNodeSetCreate(NULL); /* * SPEC XPath 1.0: * "For each node in the node-set to be filtered, the * PredicateExpr is evaluated with that node as the * context node, with the number of nodes in the * node-set as the context size, and with the proximity * position of the node in the node-set with respect to * the axis as the context position;" * @oldset is the node-set" to be filtered. * * SPEC XPath 1.0: * "only predicates change the context position and * context size (see [2.4 Predicates])." * Example: * node-set context pos * nA 1 * nB 2 * nC 3 * After applying predicate [position() > 1] : * node-set context pos * nB 1 * nC 2 * * removed the first node in the node-set, then * the context position of the */ for (i = 0; i < oldset->nodeNr; i++) { /* * Run the evaluation with a node list made of * a single item in the nodeset. */ ctxt->context->node = oldset->nodeTab[i]; if ((oldset->nodeTab[i]->type != XML_NAMESPACE_DECL) && (oldset->nodeTab[i]->doc != NULL)) ctxt->context->doc = oldset->nodeTab[i]->doc; if (tmp == NULL) { tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); } else { xmlXPathNodeSetAddUnique(tmp->nodesetval, ctxt->context->node); } valuePush(ctxt, tmp); ctxt->context->contextSize = oldset->nodeNr; ctxt->context->proximityPosition = i + 1; /* * Evaluate the predicate against the context node. * Can/should we optimize position() predicates * here (e.g. "[1]")? */ if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeNodeSet(newset); xmlXPathFreeObject(obj); return(0); } /* * The result of the evaluation needs to be tested to * decide whether the filter succeeded or not */ /* * OPTIMIZE TODO: Can we use * xmlXPathNodeSetAdd*Unique()* instead? */ res = valuePop(ctxt); if (xmlXPathEvaluatePredicateResult(ctxt, res)) { xmlXPathNodeSetAdd(newset, oldset->nodeTab[i]); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { valuePop(ctxt); xmlXPathNodeSetClear(tmp->nodesetval, 1); /* * Don't free the temporary nodeset * in order to avoid massive recreation inside this * loop. */ } else tmp = NULL; ctxt->context->node = NULL; } if (tmp != NULL) xmlXPathReleaseObject(ctxt->context, tmp); /* * The result is used as the new evaluation set. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; /* may want to move this past the '}' later */ ctxt->context->doc = oldDoc; valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, newset)); } ctxt->context->node = oldnode; return (total); } case XPATH_OP_SORT: if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); CHECK_ERROR0; if ((ctxt->value != NULL) && (ctxt->value->type == XPATH_NODESET) && (ctxt->value->nodesetval != NULL) && (ctxt->value->nodesetval->nodeNr > 1)) { xmlXPathNodeSetSort(ctxt->value->nodesetval); } return (total); #ifdef LIBXML_XPTR_ENABLED case XPATH_OP_RANGETO:{ xmlXPathObjectPtr range; xmlXPathObjectPtr res, obj; xmlXPathObjectPtr tmp; xmlLocationSetPtr newlocset = NULL; xmlLocationSetPtr oldlocset; xmlNodeSetPtr oldset; int i, j; if (op->ch1 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]); if (op->ch2 == -1) return (total); if (ctxt->value->type == XPATH_LOCATIONSET) { /* * Extract the old locset, and then evaluate the result of the * expression for all the element in the locset. use it to grow * up a new locset. */ CHECK_TYPE0(XPATH_LOCATIONSET); obj = valuePop(ctxt); oldlocset = obj->user; if ((oldlocset == NULL) || (oldlocset->locNr == 0)) { ctxt->context->node = NULL; ctxt->context->contextSize = 0; ctxt->context->proximityPosition = 0; total += xmlXPathCompOpEval(ctxt,&comp->steps[op->ch2]); res = valuePop(ctxt); if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } valuePush(ctxt, obj); CHECK_ERROR0; return (total); } newlocset = xmlXPtrLocationSetCreate(NULL); for (i = 0; i < oldlocset->locNr; i++) { /* * Run the evaluation with a node list made of a * single item in the nodelocset. */ ctxt->context->node = oldlocset->locTab[i]->user; ctxt->context->contextSize = oldlocset->locNr; ctxt->context->proximityPosition = i + 1; tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } res = valuePop(ctxt); if (res->type == XPATH_LOCATIONSET) { xmlLocationSetPtr rloc = (xmlLocationSetPtr)res->user; for (j=0; j<rloc->locNr; j++) { range = xmlXPtrNewRange( oldlocset->locTab[i]->user, oldlocset->locTab[i]->index, rloc->locTab[j]->user2, rloc->locTab[j]->index2); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset, range); } } } else { range = xmlXPtrNewRangeNodeObject( (xmlNodePtr)oldlocset->locTab[i]->user, res); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset,range); } } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } } else { /* Not a location set */ CHECK_TYPE0(XPATH_NODESET); obj = valuePop(ctxt); oldset = obj->nodesetval; ctxt->context->node = NULL; newlocset = xmlXPtrLocationSetCreate(NULL); if (oldset != NULL) { for (i = 0; i < oldset->nodeNr; i++) { /* * Run the evaluation with a node list made of a single item * in the nodeset. */ ctxt->context->node = oldset->nodeTab[i]; /* * OPTIMIZE TODO: Avoid recreation for every iteration. */ tmp = xmlXPathCacheNewNodeSet(ctxt->context, ctxt->context->node); valuePush(ctxt, tmp); if (op->ch2 != -1) total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]); if (ctxt->error != XPATH_EXPRESSION_OK) { xmlXPathFreeObject(obj); return(0); } res = valuePop(ctxt); range = xmlXPtrNewRangeNodeObject(oldset->nodeTab[i], res); if (range != NULL) { xmlXPtrLocationSetAdd(newlocset, range); } /* * Cleanup */ if (res != NULL) { xmlXPathReleaseObject(ctxt->context, res); } if (ctxt->value == tmp) { res = valuePop(ctxt); xmlXPathReleaseObject(ctxt->context, res); } ctxt->context->node = NULL; } } } /* * The result is used as the new evaluation set. */ xmlXPathReleaseObject(ctxt->context, obj); ctxt->context->node = NULL; ctxt->context->contextSize = -1; ctxt->context->proximityPosition = -1; valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset)); return (total); } #endif /* LIBXML_XPTR_ENABLED */ } xmlGenericError(xmlGenericErrorContext, "XPath: unknown precompiled operation %d\n", op->op); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Hardening of XPath evaluation Add a mechanism of frame for XPath evaluation when entering a function or a scoped evaluation, also fix a potential problem in predicate evaluation.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void scsi_read_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->sector_count == (uint32_t)-1) { DPRINTF("Read buf_len=%zd\n", r->iov.iov_len); r->sector_count = 0; scsi_req_data(&r->req, r->iov.iov_len); return; } DPRINTF("Read sector_count=%d\n", r->sector_count); if (r->sector_count == 0) { /* This also clears the sense buffer for REQUEST SENSE. */ scsi_req_complete(&r->req, GOOD); return; } /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); if (r->req.cmd.mode == SCSI_XFER_TO_DEV) { DPRINTF("Data transfer direction invalid\n"); scsi_read_complete(r, -EINVAL); return; } n = r->sector_count; if (n > SCSI_DMA_BUF_SIZE / 512) n = SCSI_DMA_BUF_SIZE / 512; if (s->tray_open) { scsi_read_complete(r, -ENOMEDIUM); } r->iov.iov_len = n * 512; qemu_iovec_init_external(&r->qiov, &r->iov, 1); bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n, scsi_read_complete, r); if (r->req.aiocb == NULL) { scsi_read_complete(r, -EIO); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 scsi_read_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); int n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->bs, &r->acct); } if (ret) { if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) { return; } } DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->iov.iov_len); n = r->iov.iov_len / 512; r->sector += n; r->sector_count -= n; scsi_req_data(&r->req, r->iov.iov_len); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 scsi_free_request(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); qemu_vfree(r->iov.iov_base); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 uint32_t scsi_init_iovec(SCSIDiskReq *r) { r->iov.iov_len = MIN(r->sector_count * 512, SCSI_DMA_BUF_SIZE); qemu_iovec_init_external(&r->qiov, &r->iov, 1); return r->qiov.size / 512; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun, void *hba_private) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d); SCSIRequest *req; SCSIDiskReq *r; req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private); r = DO_UPCAST(SCSIDiskReq, req, req); r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE); return req; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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_notify_inval_entry(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_inval_entry_out outarg; int err = -ENOMEM; char *buf; struct qstr name; buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL); if (!buf) goto err; err = -EINVAL; if (size < sizeof(outarg)) goto err; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto err; err = -ENAMETOOLONG; if (outarg.namelen > FUSE_NAME_MAX) goto err; name.name = buf; name.len = outarg.namelen; err = fuse_copy_one(cs, buf, outarg.namelen + 1); if (err) goto err; fuse_copy_finish(cs); buf[outarg.namelen] = 0; name.hash = full_name_hash(name.name, name.len); down_read(&fc->killsb); err = -ENOENT; if (fc->sb) err = fuse_reverse_inval_entry(fc->sb, outarg.parent, &name); up_read(&fc->killsb); kfree(buf); return err; err: kfree(buf); fuse_copy_finish(cs); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-119', 'CWE-787'], 'message': 'fuse: check size of FUSE_NOTIFY_INVAL_ENTRY message FUSE_NOTIFY_INVAL_ENTRY didn't check the length of the write so the message processing could overrun and result in a "kernel BUG at fs/fuse/dev.c:629!" Reported-by: Han-Wen Nienhuys <[email protected]> Signed-off-by: Miklos Szeredi <[email protected]> CC: [email protected]'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cifs_mount(struct super_block *sb, struct cifs_sb_info *cifs_sb, char *mount_data_global, const char *devname) { int rc; int xid; struct smb_vol *volume_info; struct cifsSesInfo *pSesInfo; struct cifsTconInfo *tcon; struct TCP_Server_Info *srvTcp; char *full_path; char *mount_data = mount_data_global; struct tcon_link *tlink; #ifdef CONFIG_CIFS_DFS_UPCALL struct dfs_info3_param *referrals = NULL; unsigned int num_referrals = 0; int referral_walks_count = 0; try_mount_again: #endif rc = 0; tcon = NULL; pSesInfo = NULL; srvTcp = NULL; full_path = NULL; tlink = NULL; xid = GetXid(); volume_info = kzalloc(sizeof(struct smb_vol), GFP_KERNEL); if (!volume_info) { rc = -ENOMEM; goto out; } if (cifs_parse_mount_options(mount_data, devname, volume_info)) { rc = -EINVAL; goto out; } if (volume_info->nullauth) { cFYI(1, "null user"); volume_info->username = ""; } else if (volume_info->username) { /* BB fixme parse for domain name here */ cFYI(1, "Username: %s", volume_info->username); } else { cifserror("No username specified"); /* In userspace mount helper we can get user name from alternate locations such as env variables and files on disk */ rc = -EINVAL; goto out; } /* this is needed for ASCII cp to Unicode converts */ if (volume_info->iocharset == NULL) { /* load_nls_default cannot return null */ volume_info->local_nls = load_nls_default(); } else { volume_info->local_nls = load_nls(volume_info->iocharset); if (volume_info->local_nls == NULL) { cERROR(1, "CIFS mount error: iocharset %s not found", volume_info->iocharset); rc = -ELIBACC; goto out; } } cifs_sb->local_nls = volume_info->local_nls; /* get a reference to a tcp session */ srvTcp = cifs_get_tcp_session(volume_info); if (IS_ERR(srvTcp)) { rc = PTR_ERR(srvTcp); goto out; } /* get a reference to a SMB session */ pSesInfo = cifs_get_smb_ses(srvTcp, volume_info); if (IS_ERR(pSesInfo)) { rc = PTR_ERR(pSesInfo); pSesInfo = NULL; goto mount_fail_check; } setup_cifs_sb(volume_info, cifs_sb); if (pSesInfo->capabilities & CAP_LARGE_FILES) sb->s_maxbytes = MAX_LFS_FILESIZE; else sb->s_maxbytes = MAX_NON_LFS; /* BB FIXME fix time_gran to be larger for LANMAN sessions */ sb->s_time_gran = 100; /* search for existing tcon to this server share */ tcon = cifs_get_tcon(pSesInfo, volume_info); if (IS_ERR(tcon)) { rc = PTR_ERR(tcon); tcon = NULL; goto remote_path_check; } /* do not care if following two calls succeed - informational */ if (!tcon->ipc) { CIFSSMBQFSDeviceInfo(xid, tcon); CIFSSMBQFSAttributeInfo(xid, tcon); } /* tell server which Unix caps we support */ if (tcon->ses->capabilities & CAP_UNIX) /* reset of caps checks mount to see if unix extensions disabled for just this mount */ reset_cifs_unix_caps(xid, tcon, sb, volume_info); else tcon->unix_ext = 0; /* server does not support them */ /* convert forward to back slashes in prepath here if needed */ if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) == 0) convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb)); if ((tcon->unix_ext == 0) && (cifs_sb->rsize > (1024 * 127))) { cifs_sb->rsize = 1024 * 127; cFYI(DBG2, "no very large read support, rsize now 127K"); } if (!(tcon->ses->capabilities & CAP_LARGE_WRITE_X)) cifs_sb->wsize = min(cifs_sb->wsize, (tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE)); if (!(tcon->ses->capabilities & CAP_LARGE_READ_X)) cifs_sb->rsize = min(cifs_sb->rsize, (tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE)); remote_path_check: /* check if a whole path (including prepath) is not remote */ if (!rc && cifs_sb->prepathlen && tcon) { /* build_path_to_root works only when we have a valid tcon */ full_path = cifs_build_path_to_root(cifs_sb, tcon); if (full_path == NULL) { rc = -ENOMEM; goto mount_fail_check; } rc = is_path_accessible(xid, tcon, cifs_sb, full_path); if (rc != 0 && rc != -EREMOTE) { kfree(full_path); goto mount_fail_check; } kfree(full_path); } /* get referral if needed */ if (rc == -EREMOTE) { #ifdef CONFIG_CIFS_DFS_UPCALL if (referral_walks_count > MAX_NESTED_LINKS) { /* * BB: when we implement proper loop detection, * we will remove this check. But now we need it * to prevent an indefinite loop if 'DFS tree' is * misconfigured (i.e. has loops). */ rc = -ELOOP; goto mount_fail_check; } /* convert forward to back slashes in prepath here if needed */ if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS) == 0) convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb)); full_path = build_unc_path_to_root(volume_info, cifs_sb); if (IS_ERR(full_path)) { rc = PTR_ERR(full_path); goto mount_fail_check; } cFYI(1, "Getting referral for: %s", full_path); rc = get_dfs_path(xid, pSesInfo , full_path + 1, cifs_sb->local_nls, &num_referrals, &referrals, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (!rc && num_referrals > 0) { char *fake_devname = NULL; if (mount_data != mount_data_global) kfree(mount_data); mount_data = cifs_compose_mount_options( cifs_sb->mountdata, full_path + 1, referrals, &fake_devname); free_dfs_info_array(referrals, num_referrals); kfree(fake_devname); kfree(full_path); if (IS_ERR(mount_data)) { rc = PTR_ERR(mount_data); mount_data = NULL; goto mount_fail_check; } if (tcon) cifs_put_tcon(tcon); else if (pSesInfo) cifs_put_smb_ses(pSesInfo); cleanup_volume_info(&volume_info); referral_walks_count++; FreeXid(xid); goto try_mount_again; } #else /* No DFS support, return error on mount */ rc = -EOPNOTSUPP; #endif } if (rc) goto mount_fail_check; /* now, hang the tcon off of the superblock */ tlink = kzalloc(sizeof *tlink, GFP_KERNEL); if (tlink == NULL) { rc = -ENOMEM; goto mount_fail_check; } tlink->tl_uid = pSesInfo->linux_uid; tlink->tl_tcon = tcon; tlink->tl_time = jiffies; set_bit(TCON_LINK_MASTER, &tlink->tl_flags); set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags); cifs_sb->master_tlink = tlink; spin_lock(&cifs_sb->tlink_tree_lock); tlink_rb_insert(&cifs_sb->tlink_tree, tlink); spin_unlock(&cifs_sb->tlink_tree_lock); queue_delayed_work(system_nrt_wq, &cifs_sb->prune_tlinks, TLINK_IDLE_EXPIRE); mount_fail_check: /* on error free sesinfo and tcon struct if needed */ if (rc) { if (mount_data != mount_data_global) kfree(mount_data); /* If find_unc succeeded then rc == 0 so we can not end */ /* up accidentally freeing someone elses tcon struct */ if (tcon) cifs_put_tcon(tcon); else if (pSesInfo) cifs_put_smb_ses(pSesInfo); else cifs_put_tcp_session(srvTcp); goto out; } /* volume_info->password is freed above when existing session found (in which case it is not needed anymore) but when new sesion is created the password ptr is put in the new session structure (in which case the password will be freed at unmount time) */ out: /* zero out password before freeing */ cleanup_volume_info(&volume_info); FreeXid(xid); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'cifs: always do is_path_accessible check in cifs_mount Currently, we skip doing the is_path_accessible check in cifs_mount if there is no prefixpath. I have a report of at least one server however that allows a TREE_CONNECT to a share that has a DFS referral at its root. The reporter in this case was using a UNC that had no prefixpath, so the is_path_accessible check was not triggered and the box later hit a BUG() because we were chasing a DFS referral on the root dentry for the mount. This patch fixes this by removing the check for a zero-length prefixpath. That should make the is_path_accessible check be done in this situation and should allow the client to chase the DFS referral at mount time instead. Cc: [email protected] Reported-and-Tested-by: Yogesh Sharma <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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 deliver(message_data_t *msg) { int n, r = 0, myrights; char *rcpt = NULL, *local_rcpt = NULL, *server, *acl; unsigned long uid; struct body *body = NULL; struct dest *dlist = NULL; duplicate_key_t dkey = {msg->id, NULL, msg->date}; /* check ACLs of all mailboxes */ for (n = 0; n < msg->rcpt_num; n++) { rcpt = msg->rcpt[n]; /* look it up */ r = mlookup(rcpt, &server, &acl, NULL); dkey.to = rcpt; if (r) return IMAP_MAILBOX_NONEXISTENT; if (!(acl && (myrights = cyrus_acl_myrights(nntp_authstate, acl)) && (myrights & ACL_POST))) return IMAP_PERMISSION_DENIED; if (server) { /* remote group */ proxy_adddest(&dlist, NULL, 0, server, ""); } else { /* local group */ struct appendstate as; if (msg->id && duplicate_check(&dkey)) { /* duplicate message */ duplicate_log(&dkey, "nntp delivery"); continue; } r = append_setup(&as, rcpt, nntp_userid, nntp_authstate, ACL_POST, 0); if (!r) { prot_rewind(msg->data); if (stage) { r = append_fromstage(&as, &body, stage, 0, (const char **) NULL, 0, !singleinstance); } else { /* XXX should never get here */ r = append_fromstream(&as, &body, msg->data, msg->size, 0, (const char **) NULL, 0); } if (r || ( msg->id && duplicate_check(&dkey) ) ) { append_abort(&as); if (!r) { /* duplicate message */ duplicate_log(&dkey, "nntp delivery"); continue; } } else { r = append_commit(&as, 0, NULL, &uid, NULL, NULL); } } if (!r && msg->id) duplicate_mark(&dkey, time(NULL), uid); if (r) return r; local_rcpt = rcpt; } } if (body) { message_free_body(body); free(body); } if (dlist) { struct dest *d; /* run the txns */ r = deliver_remote(msg, dlist); /* free the destination list */ d = dlist; while (d) { struct dest *nextd = d->next; free(d); d = nextd; } } return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'Secunia SA46093 - make sure nntp authentication completes Discovered by Stefan Cornelius, Secunia Research The vulnerability is caused due to the access restriction for certain commands only checking whether or not variable "nntp_userid" is non-NULL, without performing additional checks to verify that a complete, successful authentication actually took place. The variable "nntp_userid" can be set to point to a string holding the username (changing it to a non-NULL, thus allowing attackers to bypass the checks) by sending an "AUTHINFO USER" command. The variable is not reset to NULL until e.g. a wrong "AUTHINFO PASS" command is received. This can be exploited to bypass the authentication mechanism and allows access to e.g. the "NEWNEWS" or the "LIST NEWSGROUPS" commands by sending an "AUTHINFO USER" command without a following "AUTHINFO PASS" command.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void cmd_capabilities(char *keyword __attribute__((unused))) { const char *mechlist; int mechcount = 0; prot_printf(nntp_out, "101 Capability list follows:\r\n"); prot_printf(nntp_out, "VERSION 2\r\n"); if (nntp_authstate || (config_serverinfo == IMAP_ENUM_SERVERINFO_ON)) { prot_printf(nntp_out, "IMPLEMENTATION Cyrus NNTP%s %s\r\n", config_mupdate_server ? " Murder" : "", cyrus_version()); } /* add STARTTLS */ if (tls_enabled() && !nntp_starttls_done && !nntp_authstate) prot_printf(nntp_out, "STARTTLS\r\n"); /* check for SASL mechs */ sasl_listmech(nntp_saslconn, NULL, "SASL ", " ", "\r\n", &mechlist, NULL, &mechcount); /* add the AUTHINFO variants */ if (!nntp_authstate) { prot_printf(nntp_out, "AUTHINFO%s%s\r\n", (nntp_starttls_done || (extprops_ssf > 1) || config_getswitch(IMAPOPT_ALLOWPLAINTEXT)) ? " USER" : "", mechcount ? " SASL" : ""); } /* add the SASL mechs */ if (mechcount) prot_printf(nntp_out, "%s", mechlist); /* add the reader capabilities/extensions */ if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) { prot_printf(nntp_out, "READER\r\n"); prot_printf(nntp_out, "POST\r\n"); if (config_getswitch(IMAPOPT_ALLOWNEWNEWS)) prot_printf(nntp_out, "NEWNEWS\r\n"); prot_printf(nntp_out, "HDR\r\n"); prot_printf(nntp_out, "OVER\r\n"); prot_printf(nntp_out, "XPAT\r\n"); } /* add the feeder capabilities/extensions */ if (nntp_capa & MODE_FEED) { prot_printf(nntp_out, "IHAVE\r\n"); prot_printf(nntp_out, "STREAMING\r\n"); } /* add the LIST variants */ prot_printf(nntp_out, "LIST ACTIVE%s\r\n", ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) ? " HEADERS NEWSGROUPS OVERVIEW.FMT" : ""); prot_printf(nntp_out, ".\r\n"); did_capabilities = 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'Secunia SA46093 - make sure nntp authentication completes Discovered by Stefan Cornelius, Secunia Research The vulnerability is caused due to the access restriction for certain commands only checking whether or not variable "nntp_userid" is non-NULL, without performing additional checks to verify that a complete, successful authentication actually took place. The variable "nntp_userid" can be set to point to a string holding the username (changing it to a non-NULL, thus allowing attackers to bypass the checks) by sending an "AUTHINFO USER" command. The variable is not reset to NULL until e.g. a wrong "AUTHINFO PASS" command is received. This can be exploited to bypass the authentication mechanism and allows access to e.g. the "NEWNEWS" or the "LIST NEWSGROUPS" commands by sending an "AUTHINFO USER" command without a following "AUTHINFO PASS" command.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void cmd_help(void) { prot_printf(nntp_out, "100 Supported commands:\r\n"); if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) { prot_printf(nntp_out, "\tARTICLE [ message-id | number ]\r\n" "\t\tRetrieve entirety of the specified article.\r\n"); } if (!nntp_authstate) { if (!nntp_userid) { prot_printf(nntp_out, "\tAUTHINFO SASL mechanism [initial-response]\r\n" "\t\tPerform an authentication exchange using the specified\r\n" "\t\tSASL mechanism.\r\n"); prot_printf(nntp_out, "\tAUTHINFO USER username\r\n" "\t\tPresent username for authentication.\r\n"); } prot_printf(nntp_out, "\tAUTHINFO PASS password\r\n" "\t\tPresent clear-text password for authentication.\r\n"); } if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) { prot_printf(nntp_out, "\tBODY [ message-id | number ]\r\n" "\t\tRetrieve body of the specified article.\r\n"); } prot_printf(nntp_out, "\tCAPABILITIES\r\n" "\t\tList the current server capabilities.\r\n"); if (nntp_capa & MODE_FEED) { prot_printf(nntp_out, "\tCHECK message-id\r\n" "\t\tCheck if the server wants the specified article.\r\n"); } if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) { prot_printf(nntp_out, "\tDATE\r\n" "\t\tRequest the current server UTC date and time.\r\n"); prot_printf(nntp_out, "\tGROUP group\r\n" "\t\tSelect a newsgroup for article retrieval.\r\n"); prot_printf(nntp_out, "\tHDR header [ message-id | range ]\r\n" "\t\tRetrieve the specified header/metadata from the\r\n" "\t\tspecified article(s).\r\n"); } prot_printf(nntp_out, "\tHEAD [ message-id | number ]\r\n" "\t\tRetrieve the headers of the specified article.\r\n"); prot_printf(nntp_out, "\tHELP\r\n" "\t\tRequest command summary (this text).\r\n"); if (nntp_capa & MODE_FEED) { prot_printf(nntp_out, "\tIHAVE message-id\r\n" "\t\tPresent/transfer the specified article to the server.\r\n"); } if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) { prot_printf(nntp_out, "\tLAST\r\n" "\t\tSelect the previous article.\r\n"); } prot_printf(nntp_out, "\tLIST [ ACTIVE wildmat ]\r\n" "\t\tList the (subset of) valid newsgroups.\r\n"); if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) { prot_printf(nntp_out, "\tLIST HEADERS [ MSGID | RANGE ]\r\n" "\t\tList the headers and metadata items available via HDR.\r\n"); prot_printf(nntp_out, "\tLIST NEWSGROUPS [wildmat]\r\n" "\t\tList the descriptions of the specified newsgroups.\r\n"); prot_printf(nntp_out, "\tLIST OVERVIEW.FMT\r\n" "\t\tList the headers and metadata items available via OVER.\r\n"); prot_printf(nntp_out, "\tLISTGROUP [group [range]]\r\n" "\t\tList the article numbers in the specified newsgroup.\r\n"); if (config_getswitch(IMAPOPT_ALLOWNEWNEWS)) prot_printf(nntp_out, "\tNEWNEWS wildmat date time [GMT]\r\n" "\t\tList the newly arrived articles in the specified newsgroup(s)\r\n" "\t\tsince the specified date and time.\r\n"); prot_printf(nntp_out, "\tNEXT\r\n" "\t\tSelect the next article.\r\n"); prot_printf(nntp_out, "\tOVER [ message-id | range ]\r\n" "\t\tRetrieve the overview information for the specified article(s).\r\n"); prot_printf(nntp_out, "\tPOST\r\n" "\t\tPost an article to the server.\r\n"); } prot_printf(nntp_out, "\tQUIT\r\n" "\t\tTerminate the session.\r\n"); if (tls_enabled() && !nntp_starttls_done && !nntp_authstate) { prot_printf(nntp_out, "\tSTARTTLS\r\n" "\t\tStart a TLS negotiation.\r\n"); } prot_printf(nntp_out, "\tSTAT [ message-id | number ]\r\n" "\t\tCheck if the specified article exists.\r\n"); if (nntp_capa & MODE_FEED) { prot_printf(nntp_out, "\tTAKETHIS message-id\r\n" "\t\tTransfer the specified article to the server.\r\n"); } if ((nntp_capa & MODE_READ) && (nntp_userid || allowanonymous)) { prot_printf(nntp_out, "\tXPAT header message-id|range wildmat\r\n" "\t\tList the specified article(s) in which the contents\r\n" "\t\tof the specified header/metadata matches the wildmat.\r\n"); } prot_printf(nntp_out, ".\r\n"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'Secunia SA46093 - make sure nntp authentication completes Discovered by Stefan Cornelius, Secunia Research The vulnerability is caused due to the access restriction for certain commands only checking whether or not variable "nntp_userid" is non-NULL, without performing additional checks to verify that a complete, successful authentication actually took place. The variable "nntp_userid" can be set to point to a string holding the username (changing it to a non-NULL, thus allowing attackers to bypass the checks) by sending an "AUTHINFO USER" command. The variable is not reset to NULL until e.g. a wrong "AUTHINFO PASS" command is received. This can be exploited to bypass the authentication mechanism and allows access to e.g. the "NEWNEWS" or the "LIST NEWSGROUPS" commands by sending an "AUTHINFO USER" command without a following "AUTHINFO PASS" command.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int deliver_remote(message_data_t *msg, struct dest *dlist) { struct dest *d; /* run the txns */ for (d = dlist; d; d = d->next) { struct backend *be; char buf[4096]; be = proxy_findserver(d->server, &nntp_protocol, nntp_userid ? nntp_userid : "anonymous", &backend_cached, &backend_current, NULL, nntp_in); if (!be) return IMAP_SERVER_UNAVAILABLE; /* tell the backend about our new article */ prot_printf(be->out, "IHAVE %s\r\n", msg->id); prot_flush(be->out); if (!prot_fgets(buf, sizeof(buf), be->in) || strncmp("335", buf, 3)) { syslog(LOG_NOTICE, "backend doesn't want article %s", msg->id); continue; } /* send the article */ rewind(msg->f); while (fgets(buf, sizeof(buf), msg->f)) { if (buf[0] == '.') prot_putc('.', be->out); do { prot_printf(be->out, "%s", buf); } while (buf[strlen(buf)-1] != '\n' && fgets(buf, sizeof(buf), msg->f)); } /* Protect against messages not ending in CRLF */ if (buf[strlen(buf)-1] != '\n') prot_printf(be->out, "\r\n"); prot_printf(be->out, ".\r\n"); if (!prot_fgets(buf, sizeof(buf), be->in) || strncmp("235", buf, 3)) { syslog(LOG_WARNING, "article %s transfer to backend failed", msg->id); return NNTP_FAIL_TRANSFER; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'Secunia SA46093 - make sure nntp authentication completes Discovered by Stefan Cornelius, Secunia Research The vulnerability is caused due to the access restriction for certain commands only checking whether or not variable "nntp_userid" is non-NULL, without performing additional checks to verify that a complete, successful authentication actually took place. The variable "nntp_userid" can be set to point to a string holding the username (changing it to a non-NULL, thus allowing attackers to bypass the checks) by sending an "AUTHINFO USER" command. The variable is not reset to NULL until e.g. a wrong "AUTHINFO PASS" command is received. This can be exploited to bypass the authentication mechanism and allows access to e.g. the "NEWNEWS" or the "LIST NEWSGROUPS" commands by sending an "AUTHINFO USER" command without a following "AUTHINFO PASS" command.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: httpSpecialClientSideHandler(int status, FdEventHandlerPtr event, StreamRequestPtr srequest) { HTTPConnectionPtr connection = srequest->data; HTTPRequestPtr request = connection->request; int push; if((request->object->flags & OBJECT_ABORTED) || !(request->object->flags & OBJECT_INPROGRESS)) { httpClientDiscardBody(connection); httpClientError(request, 503, internAtom("Post aborted")); return 1; } if(status < 0) { do_log_error(L_ERROR, -status, "Reading from client"); if(status == -EDOGRACEFUL) httpClientFinish(connection, 1); else httpClientFinish(connection, 2); return 1; } push = MIN(srequest->offset - connection->reqlen, connection->bodylen - connection->reqoffset); if(push > 0) { connection->reqlen += push; httpSpecialDoSide(request); } do_log(L_ERROR, "Incomplete client request.\n"); connection->flags &= ~CONN_READER; httpClientRawError(connection, 502, internAtom("Incomplete client request"), 1); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'Try to read POST requests to local configuration interface correctly.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: httpLocalRequest(ObjectPtr object, int method, int from, int to, HTTPRequestPtr requestor, void *closure) { if(object->requestor == NULL) object->requestor = requestor; if(!disableLocalInterface && urlIsSpecial(object->key, object->key_size)) return httpSpecialRequest(object, method, from, to, requestor, closure); if(method >= METHOD_POST) { httpClientError(requestor, 405, internAtom("Method not allowed")); requestor->connection->flags &= ~CONN_READER; return 1; } /* objectFillFromDisk already did the real work but we have to make sure we don't get into an infinite loop. */ if(object->flags & OBJECT_INITIAL) { abortObject(object, 404, internAtom("Not found")); } object->age = current_time.tv_sec; object->date = current_time.tv_sec; object->flags &= ~OBJECT_VALIDATING; notifyObject(object); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'Try to read POST requests to local configuration interface correctly.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: httpSpecialDoSideFinish(AtomPtr data, HTTPRequestPtr requestor) { ObjectPtr object = requestor->object; if(matchUrl("/polipo/config", object)) { AtomListPtr list = NULL; int i, rc; if(disableConfiguration) { abortObject(object, 403, internAtom("Action not allowed")); goto out; } list = urlDecode(data->string, data->length); if(list == NULL) { abortObject(object, 400, internAtom("Couldn't parse variable to set")); goto out; } for(i = 0; i < list->length; i++) { rc = parseConfigLine(list->list[i]->string, NULL, 0, 1); if(rc < 0) { abortObject(object, 400, rc == -1 ? internAtom("Couldn't parse variable to set") : internAtom("Variable is not settable")); destroyAtomList(list); goto out; } } destroyAtomList(list); object->date = current_time.tv_sec; object->age = current_time.tv_sec; object->headers = internAtom("\r\nLocation: /polipo/config?"); object->code = 303; object->message = internAtom("Done"); object->flags &= ~OBJECT_INITIAL; object->length = 0; } else if(matchUrl("/polipo/status", object)) { AtomListPtr list = NULL; int i; if(disableConfiguration) { abortObject(object, 403, internAtom("Action not allowed")); goto out; } list = urlDecode(data->string, data->length); if(list == NULL) { abortObject(object, 400, internAtom("Couldn't parse action")); goto out; } for(i = 0; i < list->length; i++) { char *equals = memchr(list->list[i]->string, '=', list->list[i]->length); AtomPtr name = equals ? internAtomN(list->list[i]->string, equals - list->list[i]->string) : retainAtom(list->list[i]); if(name == atomInitForbidden) initForbidden(); else if(name == atomReopenLog) reopenLog(); else if(name == atomDiscardObjects) discardObjects(1, 0); else if(name == atomWriteoutObjects) writeoutObjects(1); else if(name == atomFreeChunkArenas) free_chunk_arenas(); else { abortObject(object, 400, internAtomF("Unknown action %s", name->string)); releaseAtom(name); destroyAtomList(list); goto out; } releaseAtom(name); } destroyAtomList(list); object->date = current_time.tv_sec; object->age = current_time.tv_sec; object->headers = internAtom("\r\nLocation: /polipo/status?"); object->code = 303; object->message = internAtom("Done"); object->flags &= ~OBJECT_INITIAL; object->length = 0; } else { abortObject(object, 405, internAtom("Method not allowed")); } out: releaseAtom(data); notifyObject(object); requestor->connection->flags &= ~CONN_READER; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'Try to read POST requests to local configuration interface correctly.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: assemble_mountinfo(struct parsed_mount_info *parsed_info, const char *thisprogram, const char *mountpoint, const char *orig_dev, char *orgoptions) { int rc; rc = drop_child_privs(); if (rc) goto assemble_exit; if (getuid()) { rc = check_fstab(thisprogram, mountpoint, orig_dev, &orgoptions); if (rc) goto assemble_exit; /* enable any default user mount flags */ parsed_info->flags |= CIFS_SETUID_FLAGS; } rc = get_pw_from_env(parsed_info); if (rc) goto assemble_exit; if (orgoptions) { rc = parse_options(orgoptions, parsed_info); if (rc) goto assemble_exit; } if (getuid()) { if (!(parsed_info->flags & (MS_USERS | MS_USER))) { fprintf(stderr, "%s: permission denied\n", thisprogram); rc = EX_USAGE; goto assemble_exit; } } parsed_info->flags &= ~(MS_USERS | MS_USER); rc = parse_unc(orig_dev, parsed_info); if (rc) goto assemble_exit; rc = resolve_host(parsed_info); if (rc) goto assemble_exit; if (!parsed_info->got_user) { /* * Note that the password will not be retrieved from the * USER env variable (ie user%password form) as there is * already a PASSWD environment varaible */ if (getenv("USER")) strlcpy(parsed_info->username, getenv("USER"), sizeof(parsed_info->username)); else strlcpy(parsed_info->username, getusername(), sizeof(parsed_info->username)); parsed_info->got_user = 1; } if (!parsed_info->got_password) { /* getpass is obsolete, but there's apparently nothing that replaces it */ char *tmp_pass = getpass("Password: "); if (!tmp_pass) { fprintf(stderr, "Error reading password, exiting\n"); rc = EX_SYSERR; goto assemble_exit; } rc = set_password(parsed_info, tmp_pass); if (rc) goto assemble_exit; } /* copy in ver= string. It's not really needed, but what the hell */ strlcat(parsed_info->options, ",ver=", sizeof(parsed_info->options)); strlcat(parsed_info->options, OPTIONS_VERSION, sizeof(parsed_info->options)); /* copy in user= string */ if (parsed_info->got_user) { strlcat(parsed_info->options, ",user=", sizeof(parsed_info->options)); strlcat(parsed_info->options, parsed_info->username, sizeof(parsed_info->options)); } if (*parsed_info->domain) { strlcat(parsed_info->options, ",domain=", sizeof(parsed_info->options)); strlcat(parsed_info->options, parsed_info->domain, sizeof(parsed_info->options)); } assemble_exit: return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'mount.cifs: guard against signals by unprivileged users If mount.cifs is setuid root, then the unprivileged user who runs the program can send the mount.cifs process a signal and kill it. This is not a huge problem unless we happen to be updating the mtab at the time, in which case the mtab lockfiles might not get cleaned up. To remedy this, have the privileged mount.cifs process set its real uid to the effective uid (usually, root). This prevents unprivileged users from being able to signal the process. While we're at it, also mask off signals while we're updating the mtab. This leaves a SIGKILL by root as the only way to interrupt the mtab update, but there's really nothing we can do about that. Signed-off-by: Jeff Layton <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide 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_ra(struct Interface *iface, unsigned char *msg, int len, struct sockaddr_in6 *addr) { struct nd_router_advert *radvert; char addr_str[INET6_ADDRSTRLEN]; uint8_t *opt_str; print_addr(&addr->sin6_addr, addr_str); radvert = (struct nd_router_advert *) msg; if ((radvert->nd_ra_curhoplimit && iface->AdvCurHopLimit) && (radvert->nd_ra_curhoplimit != iface->AdvCurHopLimit)) { flog(LOG_WARNING, "our AdvCurHopLimit on %s doesn't agree with %s", iface->Name, addr_str); } if ((radvert->nd_ra_flags_reserved & ND_RA_FLAG_MANAGED) && !iface->AdvManagedFlag) { flog(LOG_WARNING, "our AdvManagedFlag on %s doesn't agree with %s", iface->Name, addr_str); } if ((radvert->nd_ra_flags_reserved & ND_RA_FLAG_OTHER) && !iface->AdvOtherConfigFlag) { flog(LOG_WARNING, "our AdvOtherConfigFlag on %s doesn't agree with %s", iface->Name, addr_str); } /* note: we don't check the default router preference here, because they're likely different */ if ((radvert->nd_ra_reachable && iface->AdvReachableTime) && (ntohl(radvert->nd_ra_reachable) != iface->AdvReachableTime)) { flog(LOG_WARNING, "our AdvReachableTime on %s doesn't agree with %s", iface->Name, addr_str); } if ((radvert->nd_ra_retransmit && iface->AdvRetransTimer) && (ntohl(radvert->nd_ra_retransmit) != iface->AdvRetransTimer)) { flog(LOG_WARNING, "our AdvRetransTimer on %s doesn't agree with %s", iface->Name, addr_str); } len -= sizeof(struct nd_router_advert); if (len == 0) return; opt_str = (uint8_t *)(msg + sizeof(struct nd_router_advert)); while (len > 0) { int optlen; struct nd_opt_prefix_info *pinfo; struct nd_opt_rdnss_info_local *rdnssinfo; struct nd_opt_dnssl_info_local *dnsslinfo; struct nd_opt_mtu *mtu; struct AdvPrefix *prefix; struct AdvRDNSS *rdnss; char prefix_str[INET6_ADDRSTRLEN]; char rdnss_str[INET6_ADDRSTRLEN]; char suffix[256]; int offset, label_len; uint32_t preferred, valid, count; if (len < 2) { flog(LOG_ERR, "trailing garbage in RA on %s from %s", iface->Name, addr_str); break; } optlen = (opt_str[1] << 3); if (optlen == 0) { flog(LOG_ERR, "zero length option in RA on %s from %s", iface->Name, addr_str); break; } else if (optlen > len) { flog(LOG_ERR, "option length greater than total" " length in RA on %s from %s", iface->Name, addr_str); break; } switch (*opt_str) { case ND_OPT_MTU: mtu = (struct nd_opt_mtu *)opt_str; if (iface->AdvLinkMTU && (ntohl(mtu->nd_opt_mtu_mtu) != iface->AdvLinkMTU)) { flog(LOG_WARNING, "our AdvLinkMTU on %s doesn't agree with %s", iface->Name, addr_str); } break; case ND_OPT_PREFIX_INFORMATION: pinfo = (struct nd_opt_prefix_info *) opt_str; preferred = ntohl(pinfo->nd_opt_pi_preferred_time); valid = ntohl(pinfo->nd_opt_pi_valid_time); prefix = iface->AdvPrefixList; while (prefix) { if (prefix->enabled && (prefix->PrefixLen == pinfo->nd_opt_pi_prefix_len) && addr_match(&prefix->Prefix, &pinfo->nd_opt_pi_prefix, prefix->PrefixLen)) { print_addr(&prefix->Prefix, prefix_str); if (!prefix->DecrementLifetimesFlag && valid != prefix->AdvValidLifetime) { flog(LOG_WARNING, "our AdvValidLifetime on" " %s for %s doesn't agree with %s", iface->Name, prefix_str, addr_str ); } if (!prefix->DecrementLifetimesFlag && preferred != prefix->AdvPreferredLifetime) { flog(LOG_WARNING, "our AdvPreferredLifetime on" " %s for %s doesn't agree with %s", iface->Name, prefix_str, addr_str ); } } prefix = prefix->next; } break; case ND_OPT_ROUTE_INFORMATION: /* not checked: these will very likely vary a lot */ break; case ND_OPT_SOURCE_LINKADDR: /* not checked */ break; case ND_OPT_TARGET_LINKADDR: case ND_OPT_REDIRECTED_HEADER: flog(LOG_ERR, "invalid option %d in RA on %s from %s", (int)*opt_str, iface->Name, addr_str); break; /* Mobile IPv6 extensions */ case ND_OPT_RTR_ADV_INTERVAL: case ND_OPT_HOME_AGENT_INFO: /* not checked */ break; case ND_OPT_RDNSS_INFORMATION: rdnssinfo = (struct nd_opt_rdnss_info_local *) opt_str; count = rdnssinfo->nd_opt_rdnssi_len; /* Check the RNDSS addresses received */ switch (count) { case 7: rdnss = iface->AdvRDNSSList; if (!check_rdnss_presence(rdnss, &rdnssinfo->nd_opt_rdnssi_addr3 )) { /* no match found in iface->AdvRDNSSList */ print_addr(&rdnssinfo->nd_opt_rdnssi_addr3, rdnss_str); flog(LOG_WARNING, "RDNSS address %s received on %s from %s is not advertised by us", rdnss_str, iface->Name, addr_str); } /* FALLTHROUGH */ case 5: rdnss = iface->AdvRDNSSList; if (!check_rdnss_presence(rdnss, &rdnssinfo->nd_opt_rdnssi_addr2 )) { /* no match found in iface->AdvRDNSSList */ print_addr(&rdnssinfo->nd_opt_rdnssi_addr2, rdnss_str); flog(LOG_WARNING, "RDNSS address %s received on %s from %s is not advertised by us", rdnss_str, iface->Name, addr_str); } /* FALLTHROUGH */ case 3: rdnss = iface->AdvRDNSSList; if (!check_rdnss_presence(rdnss, &rdnssinfo->nd_opt_rdnssi_addr1 )) { /* no match found in iface->AdvRDNSSList */ print_addr(&rdnssinfo->nd_opt_rdnssi_addr1, rdnss_str); flog(LOG_WARNING, "RDNSS address %s received on %s from %s is not advertised by us", rdnss_str, iface->Name, addr_str); } break; default: flog(LOG_ERR, "invalid len %i in RDNSS option on %s from %s", count, iface->Name, addr_str); } break; case ND_OPT_DNSSL_INFORMATION: dnsslinfo = (struct nd_opt_dnssl_info_local *) opt_str; suffix[0] = '\0'; for (offset = 0; offset < (dnsslinfo->nd_opt_dnssli_len-1)*8;) { label_len = dnsslinfo->nd_opt_dnssli_suffixes[offset++]; if (label_len == 0) { /* * Ignore empty suffixes. They're * probably just padding... */ if (suffix[0] == '\0') continue; if (!check_dnssl_presence(iface->AdvDNSSLList, suffix)) { flog(LOG_WARNING, "DNSSL suffix %s received on %s from %s is not advertised by us", suffix, iface->Name, addr_str); } suffix[0] = '\0'; continue; } if ((sizeof(suffix) - strlen(suffix)) < (label_len + 2)) { flog(LOG_ERR, "oversized suffix in DNSSL option on %s from %s", iface->Name, addr_str); break; } if (suffix[0] != '\0') strcat(suffix, "."); strncat(suffix, &dnsslinfo->nd_opt_dnssli_suffixes[offset], label_len); offset += label_len; } break; default: dlog(LOG_DEBUG, 1, "unknown option %d in RA on %s from %s", (int)*opt_str, iface->Name, addr_str); break; } len -= optlen; opt_str += optlen; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'In process_ra() ND_OPT_DNSSL_INFORMATION option parsing "label_len" is not checked for negativeness; it leads to "suffix" buffer overflow, which leads to privilege escalation (at least with -fno-stack-protector, I didn't discover whether it's possible with -fstack-protector).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: main(int argc, char *argv[]) { char pidstr[16]; ssize_t ret; int c, log_method; char *logfile, *pidfile; int facility, fd; char *username = NULL; char *chrootdir = NULL; int configtest = 0; int singleprocess = 0; #ifdef HAVE_GETOPT_LONG int opt_idx; #endif pname = ((pname=strrchr(argv[0],'/')) != NULL)?pname+1:argv[0]; srand((unsigned int)time(NULL)); log_method = L_STDERR_SYSLOG; logfile = PATH_RADVD_LOG; conf_file = PATH_RADVD_CONF; facility = LOG_FACILITY; pidfile = PATH_RADVD_PID; /* parse args */ #define OPTIONS_STR "d:C:l:m:p:t:u:vhcs" #ifdef HAVE_GETOPT_LONG while ((c = getopt_long(argc, argv, OPTIONS_STR, prog_opt, &opt_idx)) > 0) #else while ((c = getopt(argc, argv, OPTIONS_STR)) > 0) #endif { switch (c) { case 'C': conf_file = optarg; break; case 'd': set_debuglevel(atoi(optarg)); break; case 'f': facility = atoi(optarg); break; case 'l': logfile = optarg; break; case 'p': pidfile = optarg; break; case 'm': if (!strcmp(optarg, "syslog")) { log_method = L_SYSLOG; } else if (!strcmp(optarg, "stderr_syslog")) { log_method = L_STDERR_SYSLOG; } else if (!strcmp(optarg, "stderr")) { log_method = L_STDERR; } else if (!strcmp(optarg, "logfile")) { log_method = L_LOGFILE; } else if (!strcmp(optarg, "none")) { log_method = L_NONE; } else { fprintf(stderr, "%s: unknown log method: %s\n", pname, optarg); exit(1); } break; case 't': chrootdir = strdup(optarg); break; case 'u': username = strdup(optarg); break; case 'v': version(); break; case 'c': configtest = 1; break; case 's': singleprocess = 1; break; case 'h': usage(); #ifdef HAVE_GETOPT_LONG case ':': fprintf(stderr, "%s: option %s: parameter expected\n", pname, prog_opt[opt_idx].name); exit(1); #endif case '?': exit(1); } } if (chrootdir) { if (!username) { fprintf(stderr, "Chroot as root is not safe, exiting\n"); exit(1); } if (chroot(chrootdir) == -1) { perror("chroot"); exit (1); } if (chdir("/") == -1) { perror("chdir"); exit (1); } /* username will be switched later */ } if (configtest) { log_method = L_STDERR; } if (log_open(log_method, pname, logfile, facility) < 0) { perror("log_open"); exit(1); } if (!configtest) { flog(LOG_INFO, "version %s started", VERSION); } /* get a raw socket for sending and receiving ICMPv6 messages */ sock = open_icmpv6_socket(); if (sock < 0) { perror("open_icmpv6_socket"); exit(1); } /* check that 'other' cannot write the file * for non-root, also that self/own group can't either */ if (check_conffile_perm(username, conf_file) < 0) { if (get_debuglevel() == 0) { flog(LOG_ERR, "Exiting, permissions on conf_file invalid.\n"); exit(1); } else flog(LOG_WARNING, "Insecure file permissions, but continuing anyway"); } /* if we know how to do it, check whether forwarding is enabled */ if (check_ip6_forwarding()) { flog(LOG_WARNING, "IPv6 forwarding seems to be disabled, but continuing anyway."); } /* parse config file */ if (readin_config(conf_file) < 0) { flog(LOG_ERR, "Exiting, failed to read config file.\n"); exit(1); } if (configtest) { fprintf(stderr, "Syntax OK\n"); exit(0); } /* drop root privileges if requested. */ if (username) { if (!singleprocess) { dlog(LOG_DEBUG, 3, "Initializing privsep"); if (privsep_init() < 0) flog(LOG_WARNING, "Failed to initialize privsep."); } if (drop_root_privileges(username) < 0) { perror("drop_root_privileges"); exit(1); } } if ((fd = open(pidfile, O_RDONLY, 0)) > 0) { ret = read(fd, pidstr, sizeof(pidstr) - 1); if (ret < 0) { flog(LOG_ERR, "cannot read radvd pid file, terminating: %s", strerror(errno)); exit(1); } pidstr[ret] = '\0'; if (!kill((pid_t)atol(pidstr), 0)) { flog(LOG_ERR, "radvd already running, terminating."); exit(1); } close(fd); fd = open(pidfile, O_CREAT|O_TRUNC|O_WRONLY, 0644); } else /* FIXME: not atomic if pidfile is on an NFS mounted volume */ fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644); if (fd < 0) { flog(LOG_ERR, "cannot create radvd pid file, terminating: %s", strerror(errno)); exit(1); } /* * okay, config file is read in, socket and stuff is setup, so * lets fork now... */ if (get_debuglevel() == 0) { /* Detach from controlling terminal */ if (daemon(0, 0) < 0) perror("daemon"); /* close old logfiles, including stderr */ log_close(); /* reopen logfiles, but don't log to stderr unless explicitly requested */ if (log_method == L_STDERR_SYSLOG) log_method = L_SYSLOG; if (log_open(log_method, pname, logfile, facility) < 0) { perror("log_open"); exit(1); } } /* * config signal handlers */ signal(SIGHUP, sighup_handler); signal(SIGTERM, sigterm_handler); signal(SIGINT, sigint_handler); signal(SIGUSR1, sigusr1_handler); snprintf(pidstr, sizeof(pidstr), "%ld\n", (long)getpid()); ret = write(fd, pidstr, strlen(pidstr)); if (ret != strlen(pidstr)) { flog(LOG_ERR, "cannot write radvd pid file, terminating: %s", strerror(errno)); exit(1); } close(fd); config_interface(); kickoff_adverts(); main_loop(); stop_adverts(); unlink(pidfile); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'main() must fail on privsep_init() errors, it must not run without privilege separation as privsep is expected.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: main(int argc, char *argv[]) { char pidstr[16]; ssize_t ret; int c, log_method; char *logfile, *pidfile; int facility, fd; char *username = NULL; char *chrootdir = NULL; int configtest = 0; int singleprocess = 0; #ifdef HAVE_GETOPT_LONG int opt_idx; #endif pname = ((pname=strrchr(argv[0],'/')) != NULL)?pname+1:argv[0]; srand((unsigned int)time(NULL)); log_method = L_STDERR_SYSLOG; logfile = PATH_RADVD_LOG; conf_file = PATH_RADVD_CONF; facility = LOG_FACILITY; pidfile = PATH_RADVD_PID; /* parse args */ #define OPTIONS_STR "d:C:l:m:p:t:u:vhcs" #ifdef HAVE_GETOPT_LONG while ((c = getopt_long(argc, argv, OPTIONS_STR, prog_opt, &opt_idx)) > 0) #else while ((c = getopt(argc, argv, OPTIONS_STR)) > 0) #endif { switch (c) { case 'C': conf_file = optarg; break; case 'd': set_debuglevel(atoi(optarg)); break; case 'f': facility = atoi(optarg); break; case 'l': logfile = optarg; break; case 'p': pidfile = optarg; break; case 'm': if (!strcmp(optarg, "syslog")) { log_method = L_SYSLOG; } else if (!strcmp(optarg, "stderr_syslog")) { log_method = L_STDERR_SYSLOG; } else if (!strcmp(optarg, "stderr")) { log_method = L_STDERR; } else if (!strcmp(optarg, "logfile")) { log_method = L_LOGFILE; } else if (!strcmp(optarg, "none")) { log_method = L_NONE; } else { fprintf(stderr, "%s: unknown log method: %s\n", pname, optarg); exit(1); } break; case 't': chrootdir = strdup(optarg); break; case 'u': username = strdup(optarg); break; case 'v': version(); break; case 'c': configtest = 1; break; case 's': singleprocess = 1; break; case 'h': usage(); #ifdef HAVE_GETOPT_LONG case ':': fprintf(stderr, "%s: option %s: parameter expected\n", pname, prog_opt[opt_idx].name); exit(1); #endif case '?': exit(1); } } if (chrootdir) { if (!username) { fprintf(stderr, "Chroot as root is not safe, exiting\n"); exit(1); } if (chroot(chrootdir) == -1) { perror("chroot"); exit (1); } if (chdir("/") == -1) { perror("chdir"); exit (1); } /* username will be switched later */ } if (configtest) { log_method = L_STDERR; } if (log_open(log_method, pname, logfile, facility) < 0) { perror("log_open"); exit(1); } if (!configtest) { flog(LOG_INFO, "version %s started", VERSION); } /* get a raw socket for sending and receiving ICMPv6 messages */ sock = open_icmpv6_socket(); if (sock < 0) { perror("open_icmpv6_socket"); exit(1); } /* check that 'other' cannot write the file * for non-root, also that self/own group can't either */ if (check_conffile_perm(username, conf_file) < 0) { if (get_debuglevel() == 0) { flog(LOG_ERR, "Exiting, permissions on conf_file invalid.\n"); exit(1); } else flog(LOG_WARNING, "Insecure file permissions, but continuing anyway"); } /* if we know how to do it, check whether forwarding is enabled */ if (check_ip6_forwarding()) { flog(LOG_WARNING, "IPv6 forwarding seems to be disabled, but continuing anyway."); } /* parse config file */ if (readin_config(conf_file) < 0) { flog(LOG_ERR, "Exiting, failed to read config file.\n"); exit(1); } if (configtest) { fprintf(stderr, "Syntax OK\n"); exit(0); } /* drop root privileges if requested. */ if (username) { if (!singleprocess) { dlog(LOG_DEBUG, 3, "Initializing privsep"); if (privsep_init() < 0) perror("Failed to initialize privsep."); } if (drop_root_privileges(username) < 0) { perror("drop_root_privileges"); exit(1); } } if ((fd = open(pidfile, O_RDONLY, 0)) > 0) { ret = read(fd, pidstr, sizeof(pidstr) - 1); if (ret < 0) { flog(LOG_ERR, "cannot read radvd pid file, terminating: %s", strerror(errno)); exit(1); } pidstr[ret] = '\0'; if (!kill((pid_t)atol(pidstr), 0)) { flog(LOG_ERR, "radvd already running, terminating."); exit(1); } close(fd); fd = open(pidfile, O_CREAT|O_TRUNC|O_WRONLY, 0644); } else /* FIXME: not atomic if pidfile is on an NFS mounted volume */ fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644); if (fd < 0) { flog(LOG_ERR, "cannot create radvd pid file, terminating: %s", strerror(errno)); exit(1); } /* * okay, config file is read in, socket and stuff is setup, so * lets fork now... */ if (get_debuglevel() == 0) { /* Detach from controlling terminal */ if (daemon(0, 0) < 0) perror("daemon"); /* close old logfiles, including stderr */ log_close(); /* reopen logfiles, but don't log to stderr unless explicitly requested */ if (log_method == L_STDERR_SYSLOG) log_method = L_SYSLOG; if (log_open(log_method, pname, logfile, facility) < 0) { perror("log_open"); exit(1); } } /* * config signal handlers */ signal(SIGHUP, sighup_handler); signal(SIGTERM, sigterm_handler); signal(SIGINT, sigint_handler); signal(SIGUSR1, sigusr1_handler); snprintf(pidstr, sizeof(pidstr), "%ld\n", (long)getpid()); ret = write(fd, pidstr, strlen(pidstr)); if (ret != strlen(pidstr)) { flog(LOG_ERR, "cannot write radvd pid file, terminating: %s", strerror(errno)); exit(1); } close(fd); config_interface(); kickoff_adverts(); main_loop(); stop_adverts(); unlink(pidfile); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Really exit on privsep init failure.'</s>
<s>[INST] Given the following code containing errors, provide 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_rs(struct Interface *iface, unsigned char *msg, int len, struct sockaddr_in6 *addr) { double delay; double next; struct timeval tv; uint8_t *opt_str; /* validation */ len -= sizeof(struct nd_router_solicit); opt_str = (uint8_t *)(msg + sizeof(struct nd_router_solicit)); while (len > 0) { int optlen; if (len < 2) { flog(LOG_WARNING, "trailing garbage in RS"); return; } optlen = (opt_str[1] << 3); if (optlen == 0) { flog(LOG_WARNING, "zero length option in RS"); return; } else if (optlen > len) { flog(LOG_WARNING, "option length greater than total length in RS"); return; } if (*opt_str == ND_OPT_SOURCE_LINKADDR && IN6_IS_ADDR_UNSPECIFIED(&addr->sin6_addr)) { flog(LOG_WARNING, "received icmpv6 RS packet with unspecified source address and there is a lladdr option"); return; } len -= optlen; opt_str += optlen; } gettimeofday(&tv, NULL); delay = MAX_RA_DELAY_TIME * rand() / (RAND_MAX +1.0); if (iface->UnicastOnly) { dlog(LOG_DEBUG, 5, "random mdelay for %s: %g seconds.", iface->Name, delay/1000.0); mdelay(delay); send_ra_forall(iface, &addr->sin6_addr); } else if ( timevaldiff(&tv, &iface->last_multicast) / 1000.0 < iface->MinDelayBetweenRAs ) { /* last RA was sent only a few moments ago, don't send another immediately. */ next = iface->MinDelayBetweenRAs - (tv.tv_sec + tv.tv_usec / 1000000.0) + (iface->last_multicast.tv_sec + iface->last_multicast.tv_usec / 1000000.0) + delay/1000.0; iface->next_multicast = next_timeval(next); } else { /* no RA sent in a while, send a multicast reply */ send_ra_forall(iface, NULL); next = rand_between(iface->MinRtrAdvInterval, iface->MaxRtrAdvInterval); iface->next_multicast = next_timeval(next); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'removing mdelay in unicast only case'</s>
<s>[INST] Given the following code containing errors, provide 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 _expand_arg(pam_handle_t *pamh, char **value) { const char *orig=*value, *tmpptr=NULL; char *ptr; /* * Sure would be nice to use tmpptr but it needs to be * a constant so that the compiler will shut up when I * call pam_getenv and _pam_get_item_byname -- sigh */ /* No unexpanded variable can be bigger than BUF_SIZE */ char type, tmpval[BUF_SIZE]; /* I know this shouldn't be hard-coded but it's so much easier this way */ char tmp[MAX_ENV]; D(("Remember to initialize tmp!")); memset(tmp, 0, MAX_ENV); /* * (possibly non-existent) environment variables can be used as values * by prepending a "$" and wrapping in {} (ie: ${HOST}), can escape with "\" * (possibly non-existent) PAM items can be used as values * by prepending a "@" and wrapping in {} (ie: @{PAM_RHOST}, can escape * */ D(("Expanding <%s>",orig)); while (*orig) { /* while there is some input to deal with */ if ('\\' == *orig) { ++orig; if ('$' != *orig && '@' != *orig) { D(("Unrecognized escaped character: <%c> - ignoring", *orig)); pam_syslog(pamh, LOG_ERR, "Unrecognized escaped character: <%c> - ignoring", *orig); } else if ((strlen(tmp) + 1) < MAX_ENV) { tmp[strlen(tmp)] = *orig++; /* Note the increment */ } else { /* is it really a good idea to try to log this? */ D(("Variable buffer overflow: <%s> + <%s>", tmp, tmpptr)); pam_syslog (pamh, LOG_ERR, "Variable buffer overflow: <%s> + <%s>", tmp, tmpptr); } continue; } if ('$' == *orig || '@' == *orig) { if ('{' != *(orig+1)) { D(("Expandable variables must be wrapped in {}" " <%s> - ignoring", orig)); pam_syslog(pamh, LOG_ERR, "Expandable variables must be wrapped in {}" " <%s> - ignoring", orig); if ((strlen(tmp) + 1) < MAX_ENV) { tmp[strlen(tmp)] = *orig++; /* Note the increment */ } continue; } else { D(("Expandable argument: <%s>", orig)); type = *orig; orig+=2; /* skip the ${ or @{ characters */ ptr = strchr(orig, '}'); if (ptr) { *ptr++ = '\0'; } else { D(("Unterminated expandable variable: <%s>", orig-2)); pam_syslog(pamh, LOG_ERR, "Unterminated expandable variable: <%s>", orig-2); return PAM_ABORT; } strncpy(tmpval, orig, sizeof(tmpval)); tmpval[sizeof(tmpval)-1] = '\0'; orig=ptr; /* * so, we know we need to expand tmpval, it is either * an environment variable or a PAM_ITEM. type will tell us which */ switch (type) { case '$': D(("Expanding env var: <%s>",tmpval)); tmpptr = pam_getenv(pamh, tmpval); D(("Expanded to <%s>", tmpptr)); break; case '@': D(("Expanding pam item: <%s>",tmpval)); tmpptr = _pam_get_item_byname(pamh, tmpval); D(("Expanded to <%s>", tmpptr)); break; default: D(("Impossible error, type == <%c>", type)); pam_syslog(pamh, LOG_CRIT, "Impossible error, type == <%c>", type); return PAM_ABORT; } /* switch */ if (tmpptr) { if ((strlen(tmp) + strlen(tmpptr)) < MAX_ENV) { strcat(tmp, tmpptr); } else { /* is it really a good idea to try to log this? */ D(("Variable buffer overflow: <%s> + <%s>", tmp, tmpptr)); pam_syslog (pamh, LOG_ERR, "Variable buffer overflow: <%s> + <%s>", tmp, tmpptr); } } } /* if ('{' != *orig++) */ } else { /* if ( '$' == *orig || '@' == *orig) */ if ((strlen(tmp) + 1) < MAX_ENV) { tmp[strlen(tmp)] = *orig++; /* Note the increment */ } else { /* is it really a good idea to try to log this? */ D(("Variable buffer overflow: <%s> + <%s>", tmp, tmpptr)); pam_syslog(pamh, LOG_ERR, "Variable buffer overflow: <%s> + <%s>", tmp, tmpptr); } } } /* for (;*orig;) */ if (strlen(tmp) > strlen(*value)) { free(*value); if ((*value = malloc(strlen(tmp) +1)) == NULL) { D(("Couldn't malloc %d bytes for expanded var", strlen(tmp)+1)); pam_syslog (pamh, LOG_ERR, "Couldn't malloc %lu bytes for expanded var", (unsigned long)strlen(tmp)+1); return PAM_BUF_ERR; } } strcpy(*value, tmp); memset(tmp,'\0',sizeof(tmp)); D(("Exit.")); return PAM_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'pam_env: abort when encountering an overflowed environment variable expansion * modules/pam_env/pam_env.c (_expand_arg): Abort when encountering an overflowed environment variable expansion. Fixes CVE-2011-3149. Bug-Ubuntu: https://bugs.launchpad.net/ubuntu/+source/pam/+bug/874565'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int cli_bytecode_runhook(cli_ctx *cctx, const struct cl_engine *engine, struct cli_bc_ctx *ctx, unsigned id, fmap_t *map, const char **virname) { const unsigned *hooks = engine->hooks[id - _BC_START_HOOKS]; unsigned i, hooks_cnt = engine->hooks_cnt[id - _BC_START_HOOKS]; int ret; unsigned executed = 0, breakflag = 0, errorflag = 0; cli_dbgmsg("Bytecode executing hook id %u (%u hooks)\n", id, hooks_cnt); /* restore match counts */ cli_bytecode_context_setfile(ctx, map); ctx->hooks.match_counts = ctx->lsigcnt; ctx->hooks.match_offsets = ctx->lsigoff; for (i=0;i < hooks_cnt;i++) { const struct cli_bc *bc = &engine->bcs.all_bcs[hooks[i]]; if (bc->lsig) { if (!cctx->hook_lsig_matches || !cli_bitset_test(cctx->hook_lsig_matches, bc->hook_lsig_id-1)) continue; cli_dbgmsg("Bytecode: executing bytecode %u (lsig matched)\n" , bc->id); } cli_bytecode_context_setfuncid(ctx, bc, 0); ret = cli_bytecode_run(&engine->bcs, bc, ctx); executed++; if (ret != CL_SUCCESS) { cli_warnmsg("Bytecode %u failed to run: %s\n", bc->id, cl_strerror(ret)); errorflag = 1; continue; } if (ctx->virname) { cli_dbgmsg("Bytecode found virus: %s\n", ctx->virname); if (virname) *virname = ctx->virname; cli_bytecode_context_clear(ctx); return CL_VIRUS; } ret = cli_bytecode_context_getresult_int(ctx); /* TODO: use prefix here */ cli_dbgmsg("Bytecode %u returned %u\n", bc->id, ret); if (ret == 0xcea5e) { cli_dbgmsg("Bytecode set BREAK flag in hook!\n"); breakflag = 1; } if (!ret) { char *tempfile; int fd = cli_bytecode_context_getresult_file(ctx, &tempfile); if (fd && fd != -1) { if (cctx && cctx->engine->keeptmp) cli_dbgmsg("Bytecode %u unpacked file saved in %s\n", bc->id, tempfile); else cli_dbgmsg("Bytecode %u unpacked file\n", bc->id); lseek(fd, 0, SEEK_SET); cli_dbgmsg("***** Scanning unpacked file ******\n"); ret = cli_magic_scandesc(fd, cctx); if (!cctx || !cctx->engine->keeptmp) if (ftruncate(fd, 0) == -1) cli_dbgmsg("ftruncate failed on %d\n", fd); close(fd); if (!cctx || !cctx->engine->keeptmp) { if (tempfile && cli_unlink(tempfile)) ret = CL_EUNLINK; } free(tempfile); if (ret != CL_CLEAN) { if (ret == CL_VIRUS) cli_dbgmsg("Scanning unpacked file by bytecode %u found a virus\n", bc->id); cli_bytecode_context_clear(ctx); return ret; } cli_bytecode_context_reset(ctx); continue; } } cli_bytecode_context_reset(ctx); } if (executed) cli_dbgmsg("Bytecode: executed %u bytecodes for this hook\n", executed); else cli_dbgmsg("Bytecode: no logical signature matched, no bytecode executed\n"); if (errorflag && cctx && cctx->engine->bytecode_mode == CL_BYTECODE_MODE_TEST) return CL_EBYTECODE_TESTFAIL; return breakflag ? CL_BREAK : CL_CLEAN; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'fix recursion level crash (bb #3706). Thanks to Stephane Chazelas for the analysis.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms) { uint_fast8_t tmp; int i; /* Eliminate compiler warning about unused variables. */ ms = 0; cstate = 0; if (jpc_getuint8(in, &compparms->numdlvls) || jpc_getuint8(in, &compparms->cblkwidthval) || jpc_getuint8(in, &compparms->cblkheightval) || jpc_getuint8(in, &compparms->cblksty) || jpc_getuint8(in, &compparms->qmfbid)) { return -1; } compparms->numrlvls = compparms->numdlvls + 1; if (prtflag) { for (i = 0; i < compparms->numrlvls; ++i) { if (jpc_getuint8(in, &tmp)) { jpc_cox_destroycompparms(compparms); return -1; } compparms->rlvls[i].parwidthval = tmp & 0xf; compparms->rlvls[i].parheightval = (tmp >> 4) & 0xf; } /* Sigh. This bit should be in the same field in both COC and COD mrk segs. */ compparms->csty |= JPC_COX_PRT; } else { } if (jas_stream_eof(in)) { jpc_cox_destroycompparms(compparms); return -1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Incorporated changes from patch jasper-1.900.3-CVE-2011-4516-CVE-2011-4517-CERT-VU-887409.patch'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: theme_adium_append_message (EmpathyChatView *view, EmpathyMessage *msg) { EmpathyThemeAdium *theme = EMPATHY_THEME_ADIUM (view); EmpathyThemeAdiumPriv *priv = GET_PRIV (theme); EmpathyContact *sender; TpMessage *tp_msg; TpAccount *account; gchar *body_escaped, *name_escaped; const gchar *name; const gchar *contact_id; EmpathyAvatar *avatar; const gchar *avatar_filename = NULL; gint64 timestamp; const gchar *html = NULL; const gchar *func; const gchar *service_name; GString *message_classes = NULL; gboolean is_backlog; gboolean consecutive; gboolean action; if (priv->pages_loading != 0) { queue_item (&priv->message_queue, QUEUED_MESSAGE, msg, NULL); return; } /* Get information */ sender = empathy_message_get_sender (msg); account = empathy_contact_get_account (sender); service_name = empathy_protocol_name_to_display_name (tp_account_get_protocol (account)); if (service_name == NULL) service_name = tp_account_get_protocol (account); timestamp = empathy_message_get_timestamp (msg); body_escaped = theme_adium_parse_body (theme, empathy_message_get_body (msg), empathy_message_get_token (msg)); name = empathy_contact_get_logged_alias (sender); contact_id = empathy_contact_get_id (sender); action = (empathy_message_get_tptype (msg) == TP_CHANNEL_TEXT_MESSAGE_TYPE_ACTION); /* If this is a /me probably */ if (action) { gchar *str; if (priv->data->version >= 4 || !priv->data->custom_template) { str = g_strdup_printf ("<span class='actionMessageUserName'>%s</span>" "<span class='actionMessageBody'>%s</span>", name, body_escaped); } else { str = g_strdup_printf ("*%s*", body_escaped); } g_free (body_escaped); body_escaped = str; } /* Get the avatar filename, or a fallback */ avatar = empathy_contact_get_avatar (sender); if (avatar) { avatar_filename = avatar->filename; } if (!avatar_filename) { if (empathy_contact_is_user (sender)) { avatar_filename = priv->data->default_outgoing_avatar_filename; } else { avatar_filename = priv->data->default_incoming_avatar_filename; } if (!avatar_filename) { if (!priv->data->default_avatar_filename) { priv->data->default_avatar_filename = empathy_filename_from_icon_name (EMPATHY_IMAGE_AVATAR_DEFAULT, GTK_ICON_SIZE_DIALOG); } avatar_filename = priv->data->default_avatar_filename; } } /* We want to join this message with the last one if * - senders are the same contact, * - last message was recieved recently, * - last message and this message both are/aren't backlog, and * - DisableCombineConsecutive is not set in theme's settings */ is_backlog = empathy_message_is_backlog (msg); consecutive = empathy_contact_equal (priv->last_contact, sender) && (timestamp - priv->last_timestamp < MESSAGE_JOIN_PERIOD) && (is_backlog == priv->last_is_backlog) && !tp_asv_get_boolean (priv->data->info, "DisableCombineConsecutive", NULL); /* Define message classes */ message_classes = g_string_new ("message"); if (!priv->has_focus && !is_backlog) { if (!priv->has_unread_message) { g_string_append (message_classes, " firstFocus"); priv->has_unread_message = TRUE; } g_string_append (message_classes, " focus"); } if (is_backlog) { g_string_append (message_classes, " history"); } if (consecutive) { g_string_append (message_classes, " consecutive"); } if (empathy_contact_is_user (sender)) { g_string_append (message_classes, " outgoing"); } else { g_string_append (message_classes, " incoming"); } if (empathy_message_should_highlight (msg)) { g_string_append (message_classes, " mention"); } if (empathy_message_get_tptype (msg) == TP_CHANNEL_TEXT_MESSAGE_TYPE_AUTO_REPLY) { g_string_append (message_classes, " autoreply"); } if (action) { g_string_append (message_classes, " action"); } /* FIXME: other classes: * status - the message is a status change * event - the message is a notification of something happening * (for example, encryption being turned on) * %status% - See %status% in theme_adium_append_html () */ /* This is slightly a hack, but it's the only way to add * arbitrary data to messages in the HTML. We add another * class called "x-empathy-message-id-*" to the message. This * way, we can remove the unread marker for this specific * message later. */ tp_msg = empathy_message_get_tp_message (msg); if (tp_msg != NULL) { guint32 id; gboolean valid; id = tp_message_get_pending_message_id (tp_msg, &valid); if (valid) { g_string_append_printf (message_classes, " x-empathy-message-id-%u", id); } } /* Define javascript function to use */ if (consecutive) { func = priv->allow_scrolling ? "appendNextMessage" : "appendNextMessageNoScroll"; } else { func = priv->allow_scrolling ? "appendMessage" : "appendMessageNoScroll"; } if (empathy_contact_is_user (sender)) { /* out */ if (is_backlog) { /* context */ html = consecutive ? priv->data->out_nextcontext_html : priv->data->out_context_html; } else { /* content */ html = consecutive ? priv->data->out_nextcontent_html : priv->data->out_content_html; } /* remove all the unread marks when we are sending a message */ theme_adium_remove_all_focus_marks (theme); } else { /* in */ if (is_backlog) { /* context */ html = consecutive ? priv->data->in_nextcontext_html : priv->data->in_context_html; } else { /* content */ html = consecutive ? priv->data->in_nextcontent_html : priv->data->in_content_html; } } name_escaped = g_markup_escape_text (name, -1); theme_adium_append_html (theme, func, html, body_escaped, avatar_filename, name_escaped, contact_id, service_name, message_classes->str, timestamp, is_backlog, empathy_contact_is_user (sender)); /* Keep the sender of the last displayed message */ if (priv->last_contact) { g_object_unref (priv->last_contact); } priv->last_contact = g_object_ref (sender); priv->last_timestamp = timestamp; priv->last_is_backlog = is_backlog; g_free (body_escaped); g_free (name_escaped); g_string_free (message_classes, TRUE); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-79'], 'message': 'theme-adium: escape the name in actions as well'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: tor_tls_context_new(crypto_pk_env_t *identity, unsigned int key_lifetime) { crypto_pk_env_t *rsa = NULL; EVP_PKEY *pkey = NULL; tor_tls_context_t *result = NULL; X509 *cert = NULL, *idcert = NULL; char *nickname = NULL, *nn2 = NULL; tor_tls_init(); nickname = crypto_random_hostname(8, 20, "www.", ".net"); nn2 = crypto_random_hostname(8, 20, "www.", ".net"); /* Generate short-term RSA key. */ if (!(rsa = crypto_new_pk_env())) goto error; if (crypto_pk_generate_key(rsa)<0) goto error; /* Create certificate signed by identity key. */ cert = tor_tls_create_certificate(rsa, identity, nickname, nn2, key_lifetime); /* Create self-signed certificate for identity key. */ idcert = tor_tls_create_certificate(identity, identity, nn2, nn2, IDENTITY_CERT_LIFETIME); if (!cert || !idcert) { log(LOG_WARN, LD_CRYPTO, "Error creating certificate"); goto error; } result = tor_malloc_zero(sizeof(tor_tls_context_t)); result->refcnt = 1; result->my_cert = X509_dup(cert); result->my_id_cert = X509_dup(idcert); result->key = crypto_pk_dup_key(rsa); #ifdef EVERYONE_HAS_AES /* Tell OpenSSL to only use TLS1 */ if (!(result->ctx = SSL_CTX_new(TLSv1_method()))) goto error; #else /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */ if (!(result->ctx = SSL_CTX_new(SSLv23_method()))) goto error; SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2); #endif SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE); #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION SSL_CTX_set_options(result->ctx, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); #endif /* Yes, we know what we are doing here. No, we do not treat a renegotiation * as authenticating any earlier-received data. */ if (use_unsafe_renegotiation_op) { SSL_CTX_set_options(result->ctx, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); } /* Don't actually allow compression; it uses ram and time, but the data * we transmit is all encrypted anyway. */ if (result->ctx->comp_methods) result->ctx->comp_methods = NULL; #ifdef SSL_MODE_RELEASE_BUFFERS SSL_CTX_set_mode(result->ctx, SSL_MODE_RELEASE_BUFFERS); #endif if (cert && !SSL_CTX_use_certificate(result->ctx,cert)) goto error; X509_free(cert); /* We just added a reference to cert. */ cert=NULL; if (idcert) { X509_STORE *s = SSL_CTX_get_cert_store(result->ctx); tor_assert(s); X509_STORE_add_cert(s, idcert); X509_free(idcert); /* The context now owns the reference to idcert */ idcert = NULL; } SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF); tor_assert(rsa); if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1))) goto error; if (!SSL_CTX_use_PrivateKey(result->ctx, pkey)) goto error; EVP_PKEY_free(pkey); pkey = NULL; if (!SSL_CTX_check_private_key(result->ctx)) goto error; { crypto_dh_env_t *dh = crypto_dh_new(DH_TYPE_TLS); SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh)); crypto_dh_free(dh); } SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER, always_accept_verify_cb); /* let us realloc bufs that we're writing from */ SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); if (rsa) crypto_free_pk_env(rsa); tor_free(nickname); tor_free(nn2); return result; error: tls_log_errors(NULL, LOG_WARN, "creating TLS context"); tor_free(nickname); tor_free(nn2); if (pkey) EVP_PKEY_free(pkey); if (rsa) crypto_free_pk_env(rsa); if (result) tor_tls_context_decref(result); if (cert) X509_free(cert); if (idcert) X509_free(idcert); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Don't send a certificate chain on outgoing TLS connections from non-relays'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: set_routerstatus_from_routerinfo(routerstatus_t *rs, routerinfo_t *ri, time_t now, int naming, int listbadexits, int listbaddirs, int vote_on_hsdirs) { int unstable_version = !tor_version_as_new_as(ri->platform,"0.1.1.16-rc-cvs"); memset(rs, 0, sizeof(routerstatus_t)); rs->is_authority = router_digest_is_trusted_dir(ri->cache_info.identity_digest); /* Already set by compute_performance_thresholds. */ rs->is_exit = ri->is_exit; rs->is_stable = ri->is_stable = router_is_active(ri, now) && !dirserv_thinks_router_is_unreliable(now, ri, 1, 0) && !unstable_version; rs->is_fast = ri->is_fast = router_is_active(ri, now) && !dirserv_thinks_router_is_unreliable(now, ri, 0, 1); rs->is_running = ri->is_running; /* computed above */ if (naming) { uint32_t name_status = dirserv_get_name_status( ri->cache_info.identity_digest, ri->nickname); rs->is_named = (naming && (name_status & FP_NAMED)) ? 1 : 0; rs->is_unnamed = (naming && (name_status & FP_UNNAMED)) ? 1 : 0; } rs->is_valid = ri->is_valid; if (rs->is_fast && (router_get_advertised_bandwidth(ri) >= BANDWIDTH_TO_GUARANTEE_GUARD || router_get_advertised_bandwidth(ri) >= MIN(guard_bandwidth_including_exits, guard_bandwidth_excluding_exits))) { long tk = rep_hist_get_weighted_time_known( ri->cache_info.identity_digest, now); double wfu = rep_hist_get_weighted_fractional_uptime( ri->cache_info.identity_digest, now); rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0; } else { rs->is_possible_guard = 0; } rs->is_bad_directory = listbaddirs && ri->is_bad_directory; rs->is_bad_exit = listbadexits && ri->is_bad_exit; ri->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, now); rs->is_hs_dir = vote_on_hsdirs && ri->is_hs_dir; rs->is_v2_dir = ri->dir_port != 0; if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME)) rs->is_named = rs->is_unnamed = 0; rs->published_on = ri->cache_info.published_on; memcpy(rs->identity_digest, ri->cache_info.identity_digest, DIGEST_LEN); memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest, DIGEST_LEN); rs->addr = ri->addr; strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname)); rs->or_port = ri->or_port; rs->dir_port = ri->dir_port; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Don't give the Guard flag to relays without the CVE-2011-2768 fix'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: command_process_create_cell(cell_t *cell, or_connection_t *conn) { or_circuit_t *circ; int id_is_high; if (we_are_hibernating()) { log_info(LD_OR, "Received create cell but we're shutting down. Sending back " "destroy."); connection_or_send_destroy(cell->circ_id, conn, END_CIRC_REASON_HIBERNATING); return; } if (!server_mode(get_options())) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Received create cell (type %d) from %s:%d, but we're a client. " "Sending back a destroy.", (int)cell->command, conn->_base.address, conn->_base.port); connection_or_send_destroy(cell->circ_id, conn, END_CIRC_REASON_TORPROTOCOL); return; } /* If the high bit of the circuit ID is not as expected, close the * circ. */ id_is_high = cell->circ_id & (1<<15); if ((id_is_high && conn->circ_id_type == CIRC_ID_TYPE_HIGHER) || (!id_is_high && conn->circ_id_type == CIRC_ID_TYPE_LOWER)) { log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Received create cell with unexpected circ_id %d. Closing.", cell->circ_id); connection_or_send_destroy(cell->circ_id, conn, END_CIRC_REASON_TORPROTOCOL); return; } if (circuit_id_in_use_on_orconn(cell->circ_id, conn)) { routerinfo_t *router = router_get_by_digest(conn->identity_digest); log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Received CREATE cell (circID %d) for known circ. " "Dropping (age %d).", cell->circ_id, (int)(time(NULL) - conn->_base.timestamp_created)); if (router) log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL, "Details: nickname \"%s\", platform %s.", router->nickname, escaped(router->platform)); return; } circ = or_circuit_new(cell->circ_id, conn); circ->_base.purpose = CIRCUIT_PURPOSE_OR; circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_ONIONSKIN_PENDING); if (cell->command == CELL_CREATE) { char *onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN); memcpy(onionskin, cell->payload, ONIONSKIN_CHALLENGE_LEN); /* hand it off to the cpuworkers, and then return. */ if (assign_onionskin_to_cpuworker(NULL, circ, onionskin) < 0) { log_warn(LD_GENERAL,"Failed to hand off onionskin. Closing."); circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL); return; } log_debug(LD_OR,"success: handed off onionskin."); } else { /* This is a CREATE_FAST cell; we can handle it immediately without using * a CPU worker. */ char keys[CPATH_KEY_MATERIAL_LEN]; char reply[DIGEST_LEN*2]; tor_assert(cell->command == CELL_CREATE_FAST); /* Make sure we never try to use the OR connection on which we * received this cell to satisfy an EXTEND request, */ conn->is_connection_with_client = 1; if (fast_server_handshake(cell->payload, (uint8_t*)reply, (uint8_t*)keys, sizeof(keys))<0) { log_warn(LD_OR,"Failed to generate key material. Closing."); circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL); return; } if (onionskin_answer(circ, CELL_CREATED_FAST, reply, keys)<0) { log_warn(LD_OR,"Failed to reply to CREATE_FAST cell. Closing."); circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL); return; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Reject create cells on outgoing OR connections from bridges'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: genrand_real(void) { unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; return(a*67108864.0+b)*(1.0/9007199254740992.0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': '* random.c (rb_genrand_int32, rb_genrand_real), intern.h: Export. * string.c (rb_str_tmp_new), intern.h: New function. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_8@16014 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: limited_big_rand(struct RBignum *limit) { unsigned long mask, lim, rnd; struct RBignum *val; int i, len, boundary; len = (limit->len * SIZEOF_BDIGITS + 3) / 4; val = (struct RBignum *)rb_big_clone((VALUE)limit); val->sign = 1; #if SIZEOF_BDIGITS == 2 # define BIG_GET32(big,i) (((BDIGIT *)(big)->digits)[(i)*2] | \ ((i)*2+1 < (big)->len ? (((BDIGIT *)(big)->digits)[(i)*2+1] << 16) \ : 0)) # define BIG_SET32(big,i,d) ((((BDIGIT *)(big)->digits)[(i)*2] = (d) & 0xffff), \ ((i)*2+1 < (big)->len ? (((BDIGIT *)(big)->digits)[(i)*2+1] = (d) >> 16) \ : 0)) #else /* SIZEOF_BDIGITS == 4 */ # define BIG_GET32(big,i) (((BDIGIT *)(big)->digits)[i]) # define BIG_SET32(big,i,d) (((BDIGIT *)(big)->digits)[i] = (d)) #endif retry: mask = 0; boundary = 1; for (i = len-1; 0 <= i; i--) { lim = BIG_GET32(limit, i); mask = mask ? 0xffffffff : make_mask(lim); if (mask) { rnd = genrand_int32() & mask; if (boundary) { if (lim < rnd) goto retry; if (rnd < lim) boundary = 0; } } else { rnd = 0; } BIG_SET32(val, i, rnd); } return rb_big_norm((VALUE)val); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': '* random.c (rb_genrand_int32, rb_genrand_real), intern.h: Export. * string.c (rb_str_tmp_new), intern.h: New function. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_8@16014 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s>
<s>[INST] Given the following code containing errors, provide 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 user_update(struct key *key, const void *data, size_t datalen) { struct user_key_payload *upayload, *zap; int ret; ret = -EINVAL; if (datalen <= 0 || datalen > 32767 || !data) goto error; /* construct a replacement payload */ ret = -ENOMEM; upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL); if (!upayload) goto error; upayload->datalen = datalen; memcpy(upayload->data, data, datalen); /* check the quota and attach the new data */ zap = upayload; ret = key_payload_reserve(key, datalen); if (ret == 0) { /* attach the new data, displacing the old */ zap = key->payload.data; rcu_assign_pointer(key->payload.data, upayload); key->expiry = 0; } kfree_rcu(zap, rcu); error: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'KEYS: Fix a NULL pointer deref in the user-defined key type Fix a NULL pointer deref in the user-defined key type whereby updating a negative key into a fully instantiated key will cause an oops to occur when the code attempts to free the non-existent old payload. This results in an oops that looks something like the following: BUG: unable to handle kernel NULL pointer dereference at 0000000000000008 IP: [<ffffffff81085fa1>] __call_rcu+0x11/0x13e PGD 3391d067 PUD 3894a067 PMD 0 Oops: 0002 [#1] SMP CPU 1 Pid: 4354, comm: keyctl Not tainted 3.1.0-fsdevel+ #1140 /DG965RY RIP: 0010:[<ffffffff81085fa1>] [<ffffffff81085fa1>] __call_rcu+0x11/0x13e RSP: 0018:ffff88003d591df8 EFLAGS: 00010246 RAX: 0000000000000000 RBX: 0000000000000000 RCX: 000000000000006e RDX: ffffffff8161d0c0 RSI: 0000000000000000 RDI: 0000000000000000 RBP: ffff88003d591e18 R08: 0000000000000000 R09: ffffffff8152fa6c R10: 0000000000000000 R11: 0000000000000300 R12: ffff88003b8f9538 R13: ffffffff8161d0c0 R14: ffff88003b8f9d50 R15: ffff88003c69f908 FS: 00007f97eb18c720(0000) GS:ffff88003bd00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 0000000000000008 CR3: 000000003d47a000 CR4: 00000000000006e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 Process keyctl (pid: 4354, threadinfo ffff88003d590000, task ffff88003c78a040) Stack: ffff88003e0ffde0 ffff88003b8f9538 0000000000000001 ffff88003b8f9d50 ffff88003d591e28 ffffffff810860f0 ffff88003d591e68 ffffffff8117bfea ffff88003d591e68 ffffffff00000000 ffff88003e0ffde1 ffff88003e0ffde0 Call Trace: [<ffffffff810860f0>] call_rcu_sched+0x10/0x12 [<ffffffff8117bfea>] user_update+0x8d/0xa2 [<ffffffff8117723a>] key_create_or_update+0x236/0x270 [<ffffffff811789b1>] sys_add_key+0x123/0x17e [<ffffffff813b84bb>] system_call_fastpath+0x16/0x1b Signed-off-by: David Howells <[email protected]> Acked-by: Jeff Layton <[email protected]> Acked-by: Neil Horman <[email protected]> Acked-by: Steve Dickson <[email protected]> Acked-by: James Morris <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } if (psession.size > *session_data_size) { ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } *session_data_size = psession.size; if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'bug fix in gnutls_session_get_data().'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { int ret = 0; int avail, tlen; xmlChar cur, next; const xmlChar *lastlt, *lastgt; if (ctxt->input == NULL) return(0); #ifdef DEBUG_PUSH switch (ctxt->instate) { case XML_PARSER_EOF: xmlGenericError(xmlGenericErrorContext, "PP: try EOF\n"); break; case XML_PARSER_START: xmlGenericError(xmlGenericErrorContext, "PP: try START\n"); break; case XML_PARSER_MISC: xmlGenericError(xmlGenericErrorContext, "PP: try MISC\n");break; case XML_PARSER_COMMENT: xmlGenericError(xmlGenericErrorContext, "PP: try COMMENT\n");break; case XML_PARSER_PROLOG: xmlGenericError(xmlGenericErrorContext, "PP: try PROLOG\n");break; case XML_PARSER_START_TAG: xmlGenericError(xmlGenericErrorContext, "PP: try START_TAG\n");break; case XML_PARSER_CONTENT: xmlGenericError(xmlGenericErrorContext, "PP: try CONTENT\n");break; case XML_PARSER_CDATA_SECTION: xmlGenericError(xmlGenericErrorContext, "PP: try CDATA_SECTION\n");break; case XML_PARSER_END_TAG: xmlGenericError(xmlGenericErrorContext, "PP: try END_TAG\n");break; case XML_PARSER_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "PP: try ENTITY_DECL\n");break; case XML_PARSER_ENTITY_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: try ENTITY_VALUE\n");break; case XML_PARSER_ATTRIBUTE_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: try ATTRIBUTE_VALUE\n");break; case XML_PARSER_DTD: xmlGenericError(xmlGenericErrorContext, "PP: try DTD\n");break; case XML_PARSER_EPILOG: xmlGenericError(xmlGenericErrorContext, "PP: try EPILOG\n");break; case XML_PARSER_PI: xmlGenericError(xmlGenericErrorContext, "PP: try PI\n");break; case XML_PARSER_IGNORE: xmlGenericError(xmlGenericErrorContext, "PP: try IGNORE\n");break; } #endif if ((ctxt->input != NULL) && (ctxt->input->cur - ctxt->input->base > 4096)) { xmlSHRINK(ctxt); ctxt->checkIndex = 0; } xmlParseGetLasts(ctxt, &lastlt, &lastgt); while (1) { if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(0); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if (ctxt->input == NULL) break; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else { /* * If we are operating on converted input, try to flush * remainng chars to avoid them stalling in the non-converted * buffer. */ if ((ctxt->input->buf->raw != NULL) && (ctxt->input->buf->raw->use > 0)) { int base = ctxt->input->base - ctxt->input->buf->buffer->content; int current = ctxt->input->cur - ctxt->input->base; xmlParserInputBufferPush(ctxt->input->buf, 0, ""); ctxt->input->base = ctxt->input->buf->buffer->content + base; ctxt->input->cur = ctxt->input->base + current; ctxt->input->end = &ctxt->input->buf->buffer->content[ ctxt->input->buf->buffer->use]; } avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); } if (avail < 1) goto done; switch (ctxt->instate) { case XML_PARSER_EOF: /* * Document parsing is done ! */ goto done; case XML_PARSER_START: if (ctxt->charset == XML_CHAR_ENCODING_NONE) { xmlChar start[4]; xmlCharEncoding enc; /* * Very first chars read from the document flow. */ if (avail < 4) goto done; /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines, * else xmlSwitchEncoding will set to (default) * UTF8. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); xmlSwitchEncoding(ctxt, enc); break; } if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if (cur == 0) { if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); ctxt->instate = XML_PARSER_EOF; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering EOF\n"); #endif if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } if ((cur == '<') && (next == '?')) { /* PI or XML decl */ if (avail < 5) return(ret); if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) return(ret); if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if ((ctxt->input->cur[2] == 'x') && (ctxt->input->cur[3] == 'm') && (ctxt->input->cur[4] == 'l') && (IS_BLANK_CH(ctxt->input->cur[5]))) { ret += 5; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing XML Decl\n"); #endif xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right * here */ ctxt->instate = XML_PARSER_EOF; return(0); } ctxt->standalone = ctxt->input->standalone; if ((ctxt->encoding == NULL) && (ctxt->input->encoding != NULL)) ctxt->encoding = xmlStrdup(ctxt->input->encoding); if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } } else { if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); if (ctxt->version == NULL) { xmlErrMemory(ctxt, NULL); break; } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); ctxt->instate = XML_PARSER_MISC; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering MISC\n"); #endif } break; case XML_PARSER_START_TAG: { const xmlChar *name; const xmlChar *prefix = NULL; const xmlChar *URI = NULL; int nsNr = ctxt->nsNr; if ((avail < 2) && (ctxt->inputNr == 1)) goto done; cur = ctxt->input->cur[0]; if (cur != '<') { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); ctxt->instate = XML_PARSER_EOF; if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } if (!terminate) { if (ctxt->progressive) { /* > can be found unescaped in attribute values */ if ((lastgt == NULL) || (ctxt->input->cur >= lastgt)) goto done; } else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) { goto done; } } if (ctxt->spaceNr == 0) spacePush(ctxt, -1); else if (*ctxt->space == -2) spacePush(ctxt, -1); else spacePush(ctxt, *ctxt->space); #ifdef LIBXML_SAX1_ENABLED if (ctxt->sax2) #endif /* LIBXML_SAX1_ENABLED */ name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen); #ifdef LIBXML_SAX1_ENABLED else name = xmlParseStartTag(ctxt); #endif /* LIBXML_SAX1_ENABLED */ if (name == NULL) { spacePop(ctxt); ctxt->instate = XML_PARSER_EOF; if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } #ifdef LIBXML_VALID_ENABLED /* * [ VC: Root Element Type ] * The Name in the document type declaration must match * the element type of the root element. */ if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc && ctxt->node && (ctxt->node == ctxt->myDoc->children)) ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc); #endif /* LIBXML_VALID_ENABLED */ /* * Check for an Empty Element. */ if ((RAW == '/') && (NXT(1) == '>')) { SKIP(2); if (ctxt->sax2) { if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI); if (ctxt->nsNr - nsNr > 0) nsPop(ctxt, ctxt->nsNr - nsNr); #ifdef LIBXML_SAX1_ENABLED } else { if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) && (!ctxt->disableSAX)) ctxt->sax->endElement(ctxt->userData, name); #endif /* LIBXML_SAX1_ENABLED */ } spacePop(ctxt); if (ctxt->nameNr == 0) { ctxt->instate = XML_PARSER_EPILOG; } else { ctxt->instate = XML_PARSER_CONTENT; } break; } if (RAW == '>') { NEXT; } else { xmlFatalErrMsgStr(ctxt, XML_ERR_GT_REQUIRED, "Couldn't find end of Start Tag %s\n", name); nodePop(ctxt); spacePop(ctxt); } if (ctxt->sax2) nameNsPush(ctxt, name, prefix, URI, ctxt->nsNr - nsNr); #ifdef LIBXML_SAX1_ENABLED else namePush(ctxt, name); #endif /* LIBXML_SAX1_ENABLED */ ctxt->instate = XML_PARSER_CONTENT; break; } case XML_PARSER_CONTENT: { const xmlChar *test; unsigned int cons; if ((avail < 2) && (ctxt->inputNr == 1)) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; test = CUR_PTR; cons = ctxt->input->consumed; if ((cur == '<') && (next == '/')) { ctxt->instate = XML_PARSER_END_TAG; break; } else if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; xmlParsePI(ctxt); } else if ((cur == '<') && (next != '!')) { ctxt->instate = XML_PARSER_START_TAG; break; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { int term; if (avail < 4) goto done; ctxt->input->cur += 4; term = xmlParseLookupSequence(ctxt, '-', '-', '>'); ctxt->input->cur -= 4; if ((!terminate) && (term < 0)) goto done; xmlParseComment(ctxt); ctxt->instate = XML_PARSER_CONTENT; } else if ((cur == '<') && (ctxt->input->cur[1] == '!') && (ctxt->input->cur[2] == '[') && (ctxt->input->cur[3] == 'C') && (ctxt->input->cur[4] == 'D') && (ctxt->input->cur[5] == 'A') && (ctxt->input->cur[6] == 'T') && (ctxt->input->cur[7] == 'A') && (ctxt->input->cur[8] == '[')) { SKIP(9); ctxt->instate = XML_PARSER_CDATA_SECTION; break; } else if ((cur == '<') && (next == '!') && (avail < 9)) { goto done; } else if (cur == '&') { if ((!terminate) && (xmlParseLookupSequence(ctxt, ';', 0, 0) < 0)) goto done; xmlParseReference(ctxt); } else { /* TODO Avoid the extra copy, handle directly !!! */ /* * Goal of the following test is: * - minimize calls to the SAX 'character' callback * when they are mergeable * - handle an problem for isBlank when we only parse * a sequence of blank chars and the next one is * not available to check against '<' presence. * - tries to homogenize the differences in SAX * callbacks between the push and pull versions * of the parser. */ if ((ctxt->inputNr == 1) && (avail < XML_PARSER_BIG_BUFFER_SIZE)) { if (!terminate) { if (ctxt->progressive) { if ((lastlt == NULL) || (ctxt->input->cur > lastlt)) goto done; } else if (xmlParseLookupSequence(ctxt, '<', 0, 0) < 0) { goto done; } } } ctxt->checkIndex = 0; xmlParseCharData(ctxt, 0); } /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((cons == ctxt->input->consumed) && (test == CUR_PTR)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "detected an error in element content\n"); ctxt->instate = XML_PARSER_EOF; break; } break; } case XML_PARSER_END_TAG: if (avail < 2) goto done; if (!terminate) { if (ctxt->progressive) { /* > can be found unescaped in attribute values */ if ((lastgt == NULL) || (ctxt->input->cur >= lastgt)) goto done; } else if (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0) { goto done; } } if (ctxt->sax2) { xmlParseEndTag2(ctxt, (void *) ctxt->pushTab[ctxt->nameNr * 3 - 3], (void *) ctxt->pushTab[ctxt->nameNr * 3 - 2], 0, (int) (long) ctxt->pushTab[ctxt->nameNr * 3 - 1], 0); nameNsPop(ctxt); } #ifdef LIBXML_SAX1_ENABLED else xmlParseEndTag1(ctxt, 0); #endif /* LIBXML_SAX1_ENABLED */ if (ctxt->nameNr == 0) { ctxt->instate = XML_PARSER_EPILOG; } else { ctxt->instate = XML_PARSER_CONTENT; } break; case XML_PARSER_CDATA_SECTION: { /* * The Push mode need to have the SAX callback for * cdataBlock merge back contiguous callbacks. */ int base; base = xmlParseLookupSequence(ctxt, ']', ']', '>'); if (base < 0) { if (avail >= XML_PARSER_BIG_BUFFER_SIZE + 2) { int tmp; tmp = xmlCheckCdataPush(ctxt->input->cur, XML_PARSER_BIG_BUFFER_SIZE); if (tmp < 0) { tmp = -tmp; ctxt->input->cur += tmp; goto encoding_error; } if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, ctxt->input->cur, tmp); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, tmp); } SKIPL(tmp); ctxt->checkIndex = 0; } goto done; } else { int tmp; tmp = xmlCheckCdataPush(ctxt->input->cur, base); if ((tmp < 0) || (tmp != base)) { tmp = -tmp; ctxt->input->cur += tmp; goto encoding_error; } if ((ctxt->sax != NULL) && (base == 0) && (ctxt->sax->cdataBlock != NULL) && (!ctxt->disableSAX)) { /* * Special case to provide identical behaviour * between pull and push parsers on enpty CDATA * sections */ if ((ctxt->input->cur - ctxt->input->base >= 9) && (!strncmp((const char *)&ctxt->input->cur[-9], "<![CDATA[", 9))) ctxt->sax->cdataBlock(ctxt->userData, BAD_CAST "", 0); } else if ((ctxt->sax != NULL) && (base > 0) && (!ctxt->disableSAX)) { if (ctxt->sax->cdataBlock != NULL) ctxt->sax->cdataBlock(ctxt->userData, ctxt->input->cur, base); else if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, base); } SKIPL(base + 3); ctxt->checkIndex = 0; ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif } break; } case XML_PARSER_MISC: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); ctxt->checkIndex = 0; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); ctxt->instate = XML_PARSER_MISC; ctxt->checkIndex = 0; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == 'D') && (ctxt->input->cur[3] == 'O') && (ctxt->input->cur[4] == 'C') && (ctxt->input->cur[5] == 'T') && (ctxt->input->cur[6] == 'Y') && (ctxt->input->cur[7] == 'P') && (ctxt->input->cur[8] == 'E')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '>', 0, 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing internal subset\n"); #endif ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif } else { /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->externalSubset != NULL)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering PROLOG\n"); #endif } } else if ((cur == '<') && (next == '!') && (avail < 9)) { goto done; } else { ctxt->instate = XML_PARSER_START_TAG; ctxt->progressive = 1; xmlParseGetLasts(ctxt, &lastlt, &lastgt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif } break; case XML_PARSER_PROLOG: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); ctxt->instate = XML_PARSER_PROLOG; } else if ((cur == '<') && (next == '!') && (avail < 4)) { goto done; } else { ctxt->instate = XML_PARSER_START_TAG; if (ctxt->progressive == 0) ctxt->progressive = 1; xmlParseGetLasts(ctxt, &lastlt, &lastgt); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif } break; case XML_PARSER_EPILOG: SKIP_BLANKS; if (ctxt->input->buf == NULL) avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else avail = ctxt->input->buf->buffer->use - (ctxt->input->cur - ctxt->input->base); if (avail < 2) goto done; cur = ctxt->input->cur[0]; next = ctxt->input->cur[1]; if ((cur == '<') && (next == '?')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '?', '>', 0) < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing PI\n"); #endif xmlParsePI(ctxt); ctxt->instate = XML_PARSER_EPILOG; } else if ((cur == '<') && (next == '!') && (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { if ((!terminate) && (xmlParseLookupSequence(ctxt, '-', '-', '>') < 0)) goto done; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: Parsing Comment\n"); #endif xmlParseComment(ctxt); ctxt->instate = XML_PARSER_EPILOG; } else if ((cur == '<') && (next == '!') && (avail < 4)) { goto done; } else { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); ctxt->instate = XML_PARSER_EOF; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering EOF\n"); #endif if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); goto done; } break; case XML_PARSER_DTD: { /* * Sorry but progressive parsing of the internal subset * is not expected to be supported. We first check that * the full content of the internal subset is available and * the parsing is launched only at that point. * Internal subset ends up with "']' S? '>'" in an unescaped * section and not in a ']]>' sequence which are conditional * sections (whoever argued to keep that crap in XML deserve * a place in hell !). */ int base, i; xmlChar *buf; xmlChar quote = 0; base = ctxt->input->cur - ctxt->input->base; if (base < 0) return(0); if (ctxt->checkIndex > base) base = ctxt->checkIndex; buf = ctxt->input->buf->buffer->content; for (;(unsigned int) base < ctxt->input->buf->buffer->use; base++) { if (quote != 0) { if (buf[base] == quote) quote = 0; continue; } if ((quote == 0) && (buf[base] == '<')) { int found = 0; /* special handling of comments */ if (((unsigned int) base + 4 < ctxt->input->buf->buffer->use) && (buf[base + 1] == '!') && (buf[base + 2] == '-') && (buf[base + 3] == '-')) { for (;(unsigned int) base + 3 < ctxt->input->buf->buffer->use; base++) { if ((buf[base] == '-') && (buf[base + 1] == '-') && (buf[base + 2] == '>')) { found = 1; base += 2; break; } } if (!found) { #if 0 fprintf(stderr, "unfinished comment\n"); #endif break; /* for */ } continue; } } if (buf[base] == '"') { quote = '"'; continue; } if (buf[base] == '\'') { quote = '\''; continue; } if (buf[base] == ']') { #if 0 fprintf(stderr, "%c%c%c%c: ", buf[base], buf[base + 1], buf[base + 2], buf[base + 3]); #endif if ((unsigned int) base +1 >= ctxt->input->buf->buffer->use) break; if (buf[base + 1] == ']') { /* conditional crap, skip both ']' ! */ base++; continue; } for (i = 1; (unsigned int) base + i < ctxt->input->buf->buffer->use; i++) { if (buf[base + i] == '>') { #if 0 fprintf(stderr, "found\n"); #endif goto found_end_int_subset; } if (!IS_BLANK_CH(buf[base + i])) { #if 0 fprintf(stderr, "not found\n"); #endif goto not_end_of_int_subset; } } #if 0 fprintf(stderr, "end of stream\n"); #endif break; } not_end_of_int_subset: continue; /* for */ } /* * We didn't found the end of the Internal subset */ #ifdef DEBUG_PUSH if (next == 0) xmlGenericError(xmlGenericErrorContext, "PP: lookup of int subset end filed\n"); #endif goto done; found_end_int_subset: xmlParseInternalSubset(ctxt); ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && (ctxt->sax->externalSubset != NULL)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; ctxt->checkIndex = 0; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering PROLOG\n"); #endif break; } case XML_PARSER_COMMENT: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == COMMENT\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif break; case XML_PARSER_IGNORE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == IGNORE"); ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_PI: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == PI\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering CONTENT\n"); #endif break; case XML_PARSER_ENTITY_DECL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ENTITY_DECL\n"); ctxt->instate = XML_PARSER_DTD; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_ENTITY_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ENTITY_VALUE\n"); ctxt->instate = XML_PARSER_CONTENT; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering DTD\n"); #endif break; case XML_PARSER_ATTRIBUTE_VALUE: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == ATTRIBUTE_VALUE\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; case XML_PARSER_SYSTEM_LITERAL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == SYSTEM_LITERAL\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; case XML_PARSER_PUBLIC_LITERAL: xmlGenericError(xmlGenericErrorContext, "PP: internal error, state == PUBLIC_LITERAL\n"); ctxt->instate = XML_PARSER_START_TAG; #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: entering START_TAG\n"); #endif break; } } done: #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: done %d\n", ret); #endif return(ret); encoding_error: { char buffer[150]; snprintf(buffer, 149, "Bytes: 0x%02X 0x%02X 0x%02X 0x%02X\n", ctxt->input->cur[0], ctxt->input->cur[1], ctxt->input->cur[2], ctxt->input->cur[3]); __xmlErrEncoding(ctxt, XML_ERR_INVALID_CHAR, "Input is not proper UTF-8, indicate encoding !\n%s", BAD_CAST buffer, NULL); } return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Make sure the parser returns when getting a Stop order patch backported from chromiun bug fixes, assuming author is Chris'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t bat_socket_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct socket_client *socket_client = file->private_data; struct socket_packet *socket_packet; size_t packet_len; int error; if ((file->f_flags & O_NONBLOCK) && (socket_client->queue_len == 0)) return -EAGAIN; if ((!buf) || (count < sizeof(struct icmp_packet))) return -EINVAL; if (!access_ok(VERIFY_WRITE, buf, count)) return -EFAULT; error = wait_event_interruptible(socket_client->queue_wait, socket_client->queue_len); if (error) return error; spin_lock_bh(&socket_client->lock); socket_packet = list_first_entry(&socket_client->queue_list, struct socket_packet, list); list_del(&socket_packet->list); socket_client->queue_len--; spin_unlock_bh(&socket_client->lock); error = copy_to_user(buf, &socket_packet->icmp_packet, socket_packet->icmp_len); packet_len = socket_packet->icmp_len; kfree(socket_packet); if (error) return -EFAULT; return packet_len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'batman-adv: Only write requested number of byte to user buffer Don't write more than the requested number of bytes of an batman-adv icmp packet to the userspace buffer. Otherwise unrelated userspace memory might get overridden by the kernel. Signed-off-by: Sven Eckelmann <[email protected]> Signed-off-by: Marek Lindner <[email protected]>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ciphertext_to_compressed (gnutls_session_t session, gnutls_datum_t *ciphertext, opaque * compress_data, int compress_size, uint8_t type, record_parameters_st * params, uint64* sequence) { uint8_t tag[MAX_HASH_SIZE]; uint8_t pad; int length, length_to_decrypt; uint16_t blocksize; int ret, i, pad_failed = 0; opaque preamble[MAX_PREAMBLE_SIZE]; int preamble_size; int ver = gnutls_protocol_get_version (session); int tag_size = _gnutls_auth_cipher_tag_len (&params->read.cipher_state); int explicit_iv = _gnutls_version_has_explicit_iv (session->security_parameters.version); blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm); /* actual decryption (inplace) */ switch (_gnutls_cipher_is_block (params->cipher_algorithm)) { case CIPHER_STREAM: /* The way AEAD ciphers are defined in RFC5246, it allows * only stream ciphers. */ if (explicit_iv && _gnutls_auth_cipher_is_aead(&params->read.cipher_state)) { uint8_t nonce[blocksize]; /* Values in AEAD are pretty fixed in TLS 1.2 for 128-bit block */ if (params->read.IV.data == NULL || params->read.IV.size != 4) return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR); if (ciphertext->size < tag_size+AEAD_EXPLICIT_DATA_SIZE) return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH); memcpy(nonce, params->read.IV.data, AEAD_IMPLICIT_DATA_SIZE); memcpy(&nonce[AEAD_IMPLICIT_DATA_SIZE], ciphertext->data, AEAD_EXPLICIT_DATA_SIZE); _gnutls_auth_cipher_setiv(&params->read.cipher_state, nonce, AEAD_EXPLICIT_DATA_SIZE+AEAD_IMPLICIT_DATA_SIZE); ciphertext->data += AEAD_EXPLICIT_DATA_SIZE; ciphertext->size -= AEAD_EXPLICIT_DATA_SIZE; length_to_decrypt = ciphertext->size - tag_size; } else { if (ciphertext->size < tag_size) return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH); length_to_decrypt = ciphertext->size; } length = ciphertext->size - tag_size; /* Pass the type, version, length and compressed through * MAC. */ preamble_size = make_preamble (UINT64DATA(*sequence), type, length, ver, preamble); _gnutls_auth_cipher_add_auth (&params->read.cipher_state, preamble, preamble_size); if ((ret = _gnutls_auth_cipher_decrypt (&params->read.cipher_state, ciphertext->data, length_to_decrypt)) < 0) return gnutls_assert_val(ret); break; case CIPHER_BLOCK: if (ciphertext->size < MAX(blocksize, tag_size) || (ciphertext->size % blocksize != 0)) return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH); /* ignore the IV in TLS 1.1+ */ if (explicit_iv) { _gnutls_auth_cipher_setiv(&params->read.cipher_state, ciphertext->data, blocksize); ciphertext->size -= blocksize; ciphertext->data += blocksize; if (ciphertext->size == 0) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } } /* we don't use the auth_cipher interface here, since * TLS with block ciphers is impossible to be used under such * an API. (the length of plaintext is required to calculate * auth_data, but it is not available before decryption). */ if ((ret = _gnutls_cipher_decrypt (&params->read.cipher_state.cipher, ciphertext->data, ciphertext->size)) < 0) return gnutls_assert_val(ret); pad = ciphertext->data[ciphertext->size - 1] + 1; /* pad */ if ((int) pad > (int) ciphertext->size - tag_size) { gnutls_assert (); _gnutls_record_log ("REC[%p]: Short record length %d > %d - %d (under attack?)\n", session, pad, ciphertext->size, tag_size); /* We do not fail here. We check below for the * the pad_failed. If zero means success. */ pad_failed = GNUTLS_E_DECRYPTION_FAILED; pad %= blocksize; } length = ciphertext->size - tag_size - pad; /* Check the pading bytes (TLS 1.x) */ if (ver != GNUTLS_SSL3) for (i = 2; i < pad; i++) { if (ciphertext->data[ciphertext->size - i] != ciphertext->data[ciphertext->size - 1]) pad_failed = GNUTLS_E_DECRYPTION_FAILED; } if (length < 0) length = 0; /* Pass the type, version, length and compressed through * MAC. */ preamble_size = make_preamble (UINT64DATA(*sequence), type, length, ver, preamble); _gnutls_auth_cipher_add_auth (&params->read.cipher_state, preamble, preamble_size); _gnutls_auth_cipher_add_auth (&params->read.cipher_state, ciphertext->data, length); break; default: return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR); } ret = _gnutls_auth_cipher_tag(&params->read.cipher_state, tag, tag_size); if (ret < 0) return gnutls_assert_val(ret); /* This one was introduced to avoid a timing attack against the TLS * 1.0 protocol. */ /* HMAC was not the same. */ if (memcmp (tag, &ciphertext->data[length], tag_size) != 0 || pad_failed != 0) return gnutls_assert_val(GNUTLS_E_DECRYPTION_FAILED); /* copy the decrypted stuff to compress_data. */ if (compress_size < length) return gnutls_assert_val(GNUTLS_E_DECOMPRESSION_FAILED); if (compress_data != ciphertext->data) memcpy (compress_data, ciphertext->data, length); return length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'provide less timing information when decoding packets. Patch by Nadhem Alfardan.'</s>
<s>[INST] Given the following code containing errors, provide 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 EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) { if (sMessage.Equals("DCC ", false, 4) && m_pUser->IsUserAttached()) { // DCC CHAT chat 2453612361 44592 CString sType = sMessage.Token(1); CString sFile = sMessage.Token(2); unsigned long uLongIP = sMessage.Token(3).ToULong(); unsigned short uPort = sMessage.Token(4).ToUShort(); unsigned long uFileSize = sMessage.Token(5).ToULong(); if (sType.Equals("CHAT")) { CNick FromNick(Nick.GetNickMask()); unsigned short uBNCPort = CDCCBounce::DCCRequest(FromNick.GetNick(), uLongIP, uPort, "", true, this, CUtils::GetIP(uLongIP)); if (uBNCPort) { CString sIP = GetLocalDCCIP(); m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pUser->GetNick() + " :\001DCC CHAT chat " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + "\001"); } } else if (sType.Equals("SEND")) { // DCC SEND readme.txt 403120438 5550 1104 unsigned short uBNCPort = CDCCBounce::DCCRequest(Nick.GetNick(), uLongIP, uPort, sFile, false, this, CUtils::GetIP(uLongIP)); if (uBNCPort) { CString sIP = GetLocalDCCIP(); m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pUser->GetNick() + " :\001DCC SEND " + sFile + " " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + " " + CString(uFileSize) + "\001"); } } else if (sType.Equals("RESUME")) { // Need to lookup the connection by port, filter the port, and forward to the user unsigned short uResumePort = sMessage.Token(3).ToUShort(); set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; if (pSock->GetLocalPort() == uResumePort) { m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pClient->GetNick() + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetUserPort()) + " " + sMessage.Token(4) + "\001"); } } } else if (sType.Equals("ACCEPT")) { // Need to lookup the connection by port, filter the port, and forward to the user set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; if (pSock->GetUserPort() == sMessage.Token(3).ToUShort()) { m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pClient->GetNick() + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetLocalPort()) + " " + sMessage.Token(4) + "\001"); } } } return HALTCORE; } return CONTINUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Fix crash in bouncedcc module. It happens when DCC RESUME is received. Affected ZNC versions: 0.200, 0.202. Thanks to howeyc for reporting this and providing the patch.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char *suhosin_encrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key TSRMLS_DC) { char buffer[4096]; char buffer2[4096]; char *buf = buffer, *buf2 = buffer2, *d, *d_url; int l; if (name_len > sizeof(buffer)-2) { buf = estrndup(name, name_len); } else { memcpy(buf, name, name_len); buf[name_len] = 0; } name_len = php_url_decode(buf, name_len); normalize_varname(buf); name_len = strlen(buf); if (SUHOSIN_G(cookie_plainlist)) { if (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) { encrypt_return_plain: if (buf != buffer) { efree(buf); } return estrndup(value, value_len); } } else if (SUHOSIN_G(cookie_cryptlist)) { if (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) { goto encrypt_return_plain; } } if (strlen(value) <= sizeof(buffer2)-2) { memcpy(buf2, value, value_len); buf2[value_len] = 0; } else { buf2 = estrndup(value, value_len); } value_len = php_url_decode(buf2, value_len); d = suhosin_encrypt_string(buf2, value_len, buf, name_len, key TSRMLS_CC); d_url = php_url_encode(d, strlen(d), &l); efree(d); if (buf != buffer) { efree(buf); } if (buf2 != buffer2) { efree(buf2); } return d_url; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fixed stack based buffer overflow in transparent cookie encryption (see separate advisory)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlDictComputeFastKey(const xmlChar *name, int namelen) { unsigned long value = 0L; if (name == NULL) return(0); value = *name; value <<= 5; if (namelen > 10) { value += name[namelen - 1]; namelen = 10; } switch (namelen) { case 10: value += name[9]; case 9: value += name[8]; case 8: value += name[7]; case 7: value += name[6]; case 6: value += name[5]; case 5: value += name[4]; case 4: value += name[3]; case 3: value += name[2]; case 2: value += name[1]; default: break; } return(value); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Add hash randomization to hash and dict structures Following http://www.ocert.org/advisories/ocert-2011-003.html it seems that having hash randomization might be a good idea when using XML with untrusted data * configure.in: lookup for rand, srand and time * dict.c: add randomization to dictionaries hash tables * hash.c: add randomization to normal hash tables'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int xmlInitializeDict(void) { if (xmlDictInitialized) return(1); if ((xmlDictMutex = xmlNewRMutex()) == NULL) return(0); xmlDictInitialized = 1; return(1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Add hash randomization to hash and dict structures Following http://www.ocert.org/advisories/ocert-2011-003.html it seems that having hash randomization might be a good idea when using XML with untrusted data * configure.in: lookup for rand, srand and time * dict.c: add randomization to dictionaries hash tables * hash.c: add randomization to normal hash tables'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlHashCreate(int size) { xmlHashTablePtr table; if (size <= 0) size = 256; table = xmlMalloc(sizeof(xmlHashTable)); if (table) { table->dict = NULL; table->size = size; table->nbElems = 0; table->table = xmlMalloc(size * sizeof(xmlHashEntry)); if (table->table) { memset(table->table, 0, size * sizeof(xmlHashEntry)); return(table); } xmlFree(table); } return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Add hash randomization to hash and dict structures Following http://www.ocert.org/advisories/ocert-2011-003.html it seems that having hash randomization might be a good idea when using XML with untrusted data * configure.in: lookup for rand, srand and time * dict.c: add randomization to dictionaries hash tables * hash.c: add randomization to normal hash tables'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlDictComputeBigQKey(const xmlChar *prefix, int plen, const xmlChar *name, int len) { uint32_t hash; int i; hash = 0; for (i = 0;i < plen; i++) { hash += prefix[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += ':'; hash += (hash << 10); hash ^= (hash >> 6); for (i = 0;i < len; i++) { hash += name[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Add hash randomization to hash and dict structures Following http://www.ocert.org/advisories/ocert-2011-003.html it seems that having hash randomization might be a good idea when using XML with untrusted data * configure.in: lookup for rand, srand and time * dict.c: add randomization to dictionaries hash tables * hash.c: add randomization to normal hash tables'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlDictCreate(void) { xmlDictPtr dict; if (!xmlDictInitialized) if (!xmlInitializeDict()) return(NULL); #ifdef DICT_DEBUG_PATTERNS fprintf(stderr, "C"); #endif dict = xmlMalloc(sizeof(xmlDict)); if (dict) { dict->ref_counter = 1; dict->size = MIN_DICT_SIZE; dict->nbElems = 0; dict->dict = xmlMalloc(MIN_DICT_SIZE * sizeof(xmlDictEntry)); dict->strings = NULL; dict->subdict = NULL; if (dict->dict) { memset(dict->dict, 0, MIN_DICT_SIZE * sizeof(xmlDictEntry)); return(dict); } xmlFree(dict); } return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Add hash randomization to hash and dict structures Following http://www.ocert.org/advisories/ocert-2011-003.html it seems that having hash randomization might be a good idea when using XML with untrusted data * configure.in: lookup for rand, srand and time * dict.c: add randomization to dictionaries hash tables * hash.c: add randomization to normal hash tables'</s>