text
stringlengths
517
228k
<s>[INST] Given the following code containing errors, provide 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 credssp_skip_nego_token(int length) { length = der_skip_octet_string(length); length += der_skip_contextual_tag(length); return length; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed a range of BER boundary encoding bugs which would occur when any NLA packet hit the 127 character mark. Removed ber#get_content_length as it was not behaving deterministically.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rdpCredssp* credssp_new(freerdp* instance, rdpTransport* transport, rdpSettings* settings) { rdpCredssp* credssp; credssp = (rdpCredssp*) malloc(sizeof(rdpCredssp)); ZeroMemory(credssp, sizeof(rdpCredssp)); if (credssp != NULL) { HKEY hKey; LONG status; DWORD dwType; DWORD dwSize; credssp->instance = instance; credssp->settings = settings; credssp->server = settings->ServerMode; credssp->transport = transport; credssp->send_seq_num = 0; credssp->recv_seq_num = 0; ZeroMemory(&credssp->negoToken, sizeof(SecBuffer)); ZeroMemory(&credssp->pubKeyAuth, sizeof(SecBuffer)); ZeroMemory(&credssp->authInfo, sizeof(SecBuffer)); if (credssp->server) { status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\FreeRDP\\Server"), 0, KEY_READ | KEY_WOW64_64KEY, &hKey); if (status == ERROR_SUCCESS) { status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, NULL, &dwSize); if (status == ERROR_SUCCESS) { credssp->SspiModule = (LPTSTR) malloc(dwSize + sizeof(TCHAR)); status = RegQueryValueEx(hKey, _T("SspiModule"), NULL, &dwType, (BYTE*) credssp->SspiModule, &dwSize); if (status == ERROR_SUCCESS) { _tprintf(_T("Using SSPI Module: %s\n"), credssp->SspiModule); RegCloseKey(hKey); } } } } } return credssp; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) { const xmlChar *ptr; xmlChar cur; xmlChar *name; xmlEntityPtr entity = NULL; if ((str == NULL) || (*str == NULL)) return(NULL); ptr = *str; cur = *ptr; if (cur != '%') return(NULL); ptr++; name = xmlParseStringName(ctxt, &ptr); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseStringPEReference: no name\n"); *str = ptr; return(NULL); } cur = *ptr; if (cur != ';') { xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL); xmlFree(name); *str = ptr; return(NULL); } ptr++; /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Request the entity from SAX */ if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must * precede any reference to it... */ xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } } else { /* * Internal checking in case the entity quest barfed */ if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) { xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "%%%s; is not a parameter entity\n", name, NULL); } } ctxt->hasPErefs = 1; xmlFree(name); *str = ptr; return(entity); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Improve handling of xmlStopParser() Add a specific parser error Try to stop parsing as quickly as possible'</s>
<s>[INST] Given the following code containing errors, provide 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 xml_parser_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) { xml_parser *parser = (xml_parser *)rsrc->ptr; if (parser->parser) { XML_ParserFree(parser->parser); } if (parser->ltags) { int inx; for (inx = 0; inx < parser->level; inx++) efree(parser->ltags[ inx ]); efree(parser->ltags); } if (parser->startElementHandler) { zval_ptr_dtor(&parser->startElementHandler); } if (parser->endElementHandler) { zval_ptr_dtor(&parser->endElementHandler); } if (parser->characterDataHandler) { zval_ptr_dtor(&parser->characterDataHandler); } if (parser->processingInstructionHandler) { zval_ptr_dtor(&parser->processingInstructionHandler); } if (parser->defaultHandler) { zval_ptr_dtor(&parser->defaultHandler); } if (parser->unparsedEntityDeclHandler) { zval_ptr_dtor(&parser->unparsedEntityDeclHandler); } if (parser->notationDeclHandler) { zval_ptr_dtor(&parser->notationDeclHandler); } if (parser->externalEntityRefHandler) { zval_ptr_dtor(&parser->externalEntityRefHandler); } if (parser->unknownEncodingHandler) { zval_ptr_dtor(&parser->unknownEncodingHandler); } if (parser->startNamespaceDeclHandler) { zval_ptr_dtor(&parser->startNamespaceDeclHandler); } if (parser->endNamespaceDeclHandler) { zval_ptr_dtor(&parser->endNamespaceDeclHandler); } if (parser->baseURI) { efree(parser->baseURI); } if (parser->object) { zval_ptr_dtor(&parser->object); } efree(parser); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'truncate results at depth of 255 to prevent corruption'</s>
<s>[INST] Given the following code containing errors, provide 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 br_multicast_del_pg(struct net_bridge *br, struct net_bridge_port_group *pg) { struct net_bridge_mdb_htable *mdb; struct net_bridge_mdb_entry *mp; struct net_bridge_port_group *p; struct net_bridge_port_group __rcu **pp; mdb = mlock_dereference(br->mdb, br); mp = br_mdb_ip_get(mdb, &pg->addr); if (WARN_ON(!mp)) return; for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (p != pg) continue; rcu_assign_pointer(*pp, p->next); hlist_del_init(&p->mglist); del_timer(&p->timer); call_rcu_bh(&p->rcu, br_multicast_free_pg); if (!mp->ports && !mp->mglist && netif_running(br->dev)) mod_timer(&mp->timer, jiffies); return; } WARN_ON(1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'bridge: fix some kernel warning in multicast timer Several people reported the warning: "kernel BUG at kernel/timer.c:729!" and the stack trace is: #7 [ffff880214d25c10] mod_timer+501 at ffffffff8106d905 #8 [ffff880214d25c50] br_multicast_del_pg.isra.20+261 at ffffffffa0731d25 [bridge] #9 [ffff880214d25c80] br_multicast_disable_port+88 at ffffffffa0732948 [bridge] #10 [ffff880214d25cb0] br_stp_disable_port+154 at ffffffffa072bcca [bridge] #11 [ffff880214d25ce8] br_device_event+520 at ffffffffa072a4e8 [bridge] #12 [ffff880214d25d18] notifier_call_chain+76 at ffffffff8164aafc #13 [ffff880214d25d50] raw_notifier_call_chain+22 at ffffffff810858f6 #14 [ffff880214d25d60] call_netdevice_notifiers+45 at ffffffff81536aad #15 [ffff880214d25d80] dev_close_many+183 at ffffffff81536d17 #16 [ffff880214d25dc0] rollback_registered_many+168 at ffffffff81537f68 #17 [ffff880214d25de8] rollback_registered+49 at ffffffff81538101 #18 [ffff880214d25e10] unregister_netdevice_queue+72 at ffffffff815390d8 #19 [ffff880214d25e30] __tun_detach+272 at ffffffffa074c2f0 [tun] #20 [ffff880214d25e88] tun_chr_close+45 at ffffffffa074c4bd [tun] #21 [ffff880214d25ea8] __fput+225 at ffffffff8119b1f1 #22 [ffff880214d25ef0] ____fput+14 at ffffffff8119b3fe #23 [ffff880214d25f00] task_work_run+159 at ffffffff8107cf7f #24 [ffff880214d25f30] do_notify_resume+97 at ffffffff810139e1 #25 [ffff880214d25f50] int_signal+18 at ffffffff8164f292 this is due to I forgot to check if mp->timer is armed in br_multicast_del_pg(). This bug is introduced by commit 9f00b2e7cf241fa389733d41b6 (bridge: only expire the mdb entry when query is received). Same for __br_mdb_del(). Tested-by: poma <pomidorabelisima@gmail.com> Reported-by: LiYonghua <809674045@qq.com> Reported-by: Robert Hancock <hancockrwd@gmail.com> Cc: Herbert Xu <herbert@gondor.apana.org.au> Cc: Stephen Hemminger <stephen@networkplumber.org> Cc: "David S. Miller" <davem@davemloft.net> Signed-off-by: Cong Wang <amwang@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void createDirectory(const string &path) const { // We do not use makeDirTree() here. If an attacker creates a directory // just before we do, then we want to abort because we want the directory // to have specific permissions. if (mkdir(path.c_str(), parseModeString("u=rwx,g=rx,o=rx")) == -1) { int e = errno; throw FileSystemException("Cannot create server instance directory '" + path + "'", e, path); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'Fixed a problem with graceful web server restarts. This problem was introduced in 4.0.6 during the attempt to fix issue #910.'</s>
<s>[INST] Given the following code containing errors, provide 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 ps_files_open(ps_files *data, const char *key TSRMLS_DC) { char buf[MAXPATHLEN]; if (data->fd < 0 || !data->lastkey || strcmp(key, data->lastkey)) { if (data->lastkey) { efree(data->lastkey); data->lastkey = NULL; } ps_files_close(data); if (!ps_files_valid_key(key)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'"); PS(invalid_session_id) = 1; return; } if (!ps_files_path_create(buf, sizeof(buf), data, key)) { return; } data->lastkey = estrdup(key); data->fd = VCWD_OPEN_MODE(buf, O_CREAT | O_RDWR | O_BINARY, data->filemode); if (data->fd != -1) { #ifndef PHP_WIN32 /* check to make sure that the opened file is not a symlink, linking to data outside of allowable dirs */ if (PG(open_basedir)) { struct stat sbuf; if (fstat(data->fd, &sbuf)) { close(data->fd); return; } if (S_ISLNK(sbuf.st_mode) && php_check_open_basedir(buf TSRMLS_CC)) { close(data->fd); return; } } #endif flock(data->fd, LOCK_EX); #ifdef F_SETFD # ifndef FD_CLOEXEC # define FD_CLOEXEC 1 # endif if (fcntl(data->fd, F_SETFD, FD_CLOEXEC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "fcntl(%d, F_SETFD, FD_CLOEXEC) failed: %s (%d)", data->fd, strerror(errno), errno); } #endif } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "open(%s, O_RDWR) failed: %s (%d)", buf, strerror(errno), errno); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Strict session'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(openssl_x509_parse) { zval ** zcert; X509 * cert = NULL; long certresource = -1; int i; zend_bool useshortnames = 1; char * tmpstr; zval * subitem; X509_EXTENSION *extension; char *extname; BIO *bio_out; BUF_MEM *bio_buf; char buf[256]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|b", &zcert, &useshortnames) == FAILURE) { return; } cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC); if (cert == NULL) { RETURN_FALSE; } array_init(return_value); if (cert->name) { add_assoc_string(return_value, "name", cert->name, 1); } /* add_assoc_bool(return_value, "valid", cert->valid); */ add_assoc_name_entry(return_value, "subject", X509_get_subject_name(cert), useshortnames TSRMLS_CC); /* hash as used in CA directories to lookup cert by subject name */ { char buf[32]; snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert)); add_assoc_string(return_value, "hash", buf, 1); } add_assoc_name_entry(return_value, "issuer", X509_get_issuer_name(cert), useshortnames TSRMLS_CC); add_assoc_long(return_value, "version", X509_get_version(cert)); add_assoc_string(return_value, "serialNumber", i2s_ASN1_INTEGER(NULL, X509_get_serialNumber(cert)), 1); add_assoc_asn1_string(return_value, "validFrom", X509_get_notBefore(cert)); add_assoc_asn1_string(return_value, "validTo", X509_get_notAfter(cert)); add_assoc_long(return_value, "validFrom_time_t", asn1_time_to_time_t(X509_get_notBefore(cert) TSRMLS_CC)); add_assoc_long(return_value, "validTo_time_t", asn1_time_to_time_t(X509_get_notAfter(cert) TSRMLS_CC)); tmpstr = (char *)X509_alias_get0(cert, NULL); if (tmpstr) { add_assoc_string(return_value, "alias", tmpstr, 1); } /* add_assoc_long(return_value, "signaturetypeLONG", X509_get_signature_type(cert)); add_assoc_string(return_value, "signaturetype", OBJ_nid2sn(X509_get_signature_type(cert)), 1); add_assoc_string(return_value, "signaturetypeLN", OBJ_nid2ln(X509_get_signature_type(cert)), 1); */ MAKE_STD_ZVAL(subitem); array_init(subitem); /* NOTE: the purposes are added as integer keys - the keys match up to the X509_PURPOSE_SSL_XXX defines in x509v3.h */ for (i = 0; i < X509_PURPOSE_get_count(); i++) { int id, purpset; char * pname; X509_PURPOSE * purp; zval * subsub; MAKE_STD_ZVAL(subsub); array_init(subsub); purp = X509_PURPOSE_get0(i); id = X509_PURPOSE_get_id(purp); purpset = X509_check_purpose(cert, id, 0); add_index_bool(subsub, 0, purpset); purpset = X509_check_purpose(cert, id, 1); add_index_bool(subsub, 1, purpset); pname = useshortnames ? X509_PURPOSE_get0_sname(purp) : X509_PURPOSE_get0_name(purp); add_index_string(subsub, 2, pname, 1); /* NOTE: if purpset > 1 then it's a warning - we should mention it ? */ add_index_zval(subitem, id, subsub); } add_assoc_zval(return_value, "purposes", subitem); MAKE_STD_ZVAL(subitem); array_init(subitem); for (i = 0; i < X509_get_ext_count(cert); i++) { extension = X509_get_ext(cert, i); if (OBJ_obj2nid(X509_EXTENSION_get_object(extension)) != NID_undef) { extname = (char *)OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(extension))); } else { OBJ_obj2txt(buf, sizeof(buf)-1, X509_EXTENSION_get_object(extension), 1); extname = buf; } bio_out = BIO_new(BIO_s_mem()); if (X509V3_EXT_print(bio_out, extension, 0, 0)) { BIO_get_mem_ptr(bio_out, &bio_buf); add_assoc_stringl(subitem, extname, bio_buf->data, bio_buf->length, 1); } else { add_assoc_asn1_string(subitem, extname, X509_EXTENSION_get_data(extension)); } BIO_free(bio_out); } add_assoc_zval(return_value, "extensions", subitem); if (certresource == -1 && cert) { X509_free(cert); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix CVE-2013-4073 - handling of certs with null bytes'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void CLASS apply_tiff() { int max_samp=0, raw=-1, thm=-1, i; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } for (i=0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && (tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width*tiff_ifd[i].t_height > raw_width*raw_height) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; #ifdef LIBRAW_LIBRARY_BUILD data_size = tile_length < INT_MAX && tile_length>0 ? tiff_ifd[i].tile_maxbytes: tiff_ifd[i].bytes; #endif raw = i; } } if (!tile_width ) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i=tiff_nifds; i--; ) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width*raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; break; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else load_raw = &CLASS nikon_load_raw; break; case 34892: load_raw = &CLASS lossy_dng_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: break; default: is_raw = 0; } if (!dng_version) if ( (tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && tiff_bps != 2048 && tiff_compress != 32769 && tiff_compress != 32770) || (tiff_bps == 8 && !strstr(make,"KODAK") && !strstr(make,"Kodak") && !strstr(model2,"DEBUG RAW"))) is_raw = 0; for (i=0; i < tiff_nifds; i++) if (i != raw && tiff_ifd[i].samples == max_samp && tiff_ifd[i].t_width * tiff_ifd[i].t_height / SQR(tiff_ifd[i].bps+1) > thumb_width * thumb_height / SQR(thumb_misc+1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strcmp(make,"Imacon")) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'cumulated data checks 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: int main( int argc, char *argv[] ) { FILE *f; int ret; size_t n, buflen; int server_fd = -1; unsigned char *p, *end; unsigned char buf[2048]; unsigned char hash[20]; const char *pers = "dh_client"; entropy_context entropy; ctr_drbg_context ctr_drbg; rsa_context rsa; dhm_context dhm; aes_context aes; ((void) argc); ((void) argv); memset( &rsa, 0, sizeof( rsa ) ); memset( &dhm, 0, sizeof( dhm ) ); /* * 1. Setup the RNG */ printf( "\n . Seeding the random number generator" ); fflush( stdout ); entropy_init( &entropy ); if( ( ret = ctr_drbg_init( &ctr_drbg, entropy_func, &entropy, (const unsigned char *) pers, strlen( pers ) ) ) != 0 ) { printf( " failed\n ! ctr_drbg_init returned %d\n", ret ); goto exit; } /* * 2. Read the server's public RSA key */ printf( "\n . Reading public key from rsa_pub.txt" ); fflush( stdout ); if( ( f = fopen( "rsa_pub.txt", "rb" ) ) == NULL ) { ret = 1; printf( " failed\n ! Could not open rsa_pub.txt\n" \ " ! Please run rsa_genkey first\n\n" ); goto exit; } rsa_init( &rsa, RSA_PKCS_V15, 0 ); if( ( ret = mpi_read_file( &rsa.N, 16, f ) ) != 0 || ( ret = mpi_read_file( &rsa.E, 16, f ) ) != 0 ) { printf( " failed\n ! mpi_read_file returned %d\n\n", ret ); goto exit; } rsa.len = ( mpi_msb( &rsa.N ) + 7 ) >> 3; fclose( f ); /* * 3. Initiate the connection */ printf( "\n . Connecting to tcp/%s/%d", SERVER_NAME, SERVER_PORT ); fflush( stdout ); if( ( ret = net_connect( &server_fd, SERVER_NAME, SERVER_PORT ) ) != 0 ) { printf( " failed\n ! net_connect returned %d\n\n", ret ); goto exit; } /* * 4a. First get the buffer length */ printf( "\n . Receiving the server's DH parameters" ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); if( ( ret = net_recv( &server_fd, buf, 2 ) ) != 2 ) { printf( " failed\n ! net_recv returned %d\n\n", ret ); goto exit; } n = buflen = ( buf[0] << 8 ) | buf[1]; if( buflen < 1 || buflen > sizeof( buf ) ) { printf( " failed\n ! Got an invalid buffer length\n\n" ); goto exit; } /* * 4b. Get the DHM parameters: P, G and Ys = G^Xs mod P */ memset( buf, 0, sizeof( buf ) ); if( ( ret = net_recv( &server_fd, buf, n ) ) != (int) n ) { printf( " failed\n ! net_recv returned %d\n\n", ret ); goto exit; } p = buf, end = buf + buflen; if( ( ret = dhm_read_params( &dhm, &p, end ) ) != 0 ) { printf( " failed\n ! dhm_read_params returned %d\n\n", ret ); goto exit; } if( dhm.len < 64 || dhm.len > 512 ) { ret = 1; printf( " failed\n ! Invalid DHM modulus size\n\n" ); goto exit; } /* * 5. Check that the server's RSA signature matches * the SHA-1 hash of (P,G,Ys) */ printf( "\n . Verifying the server's RSA signature" ); fflush( stdout ); p += 2; if( ( n = (size_t) ( end - p ) ) != rsa.len ) { ret = 1; printf( " failed\n ! Invalid RSA signature size\n\n" ); goto exit; } sha1( buf, (int)( p - 2 - buf ), hash ); if( ( ret = rsa_pkcs1_verify( &rsa, RSA_PUBLIC, SIG_RSA_SHA1, 0, hash, p ) ) != 0 ) { printf( " failed\n ! rsa_pkcs1_verify returned %d\n\n", ret ); goto exit; } /* * 6. Send our public value: Yc = G ^ Xc mod P */ printf( "\n . Sending own public value to server" ); fflush( stdout ); n = dhm.len; if( ( ret = dhm_make_public( &dhm, dhm.len, buf, n, ctr_drbg_random, &ctr_drbg ) ) != 0 ) { printf( " failed\n ! dhm_make_public returned %d\n\n", ret ); goto exit; } if( ( ret = net_send( &server_fd, buf, n ) ) != (int) n ) { printf( " failed\n ! net_send returned %d\n\n", ret ); goto exit; } /* * 7. Derive the shared secret: K = Ys ^ Xc mod P */ printf( "\n . Shared secret: " ); fflush( stdout ); n = dhm.len; if( ( ret = dhm_calc_secret( &dhm, buf, &n ) ) != 0 ) { printf( " failed\n ! dhm_calc_secret returned %d\n\n", ret ); goto exit; } for( n = 0; n < 16; n++ ) printf( "%02x", buf[n] ); /* * 8. Setup the AES-256 decryption key * * This is an overly simplified example; best practice is * to hash the shared secret with a random value to derive * the keying material for the encryption/decryption keys, * IVs and MACs. */ printf( "...\n . Receiving and decrypting the ciphertext" ); fflush( stdout ); aes_setkey_dec( &aes, buf, 256 ); memset( buf, 0, sizeof( buf ) ); if( ( ret = net_recv( &server_fd, buf, 16 ) ) != 16 ) { printf( " failed\n ! net_recv returned %d\n\n", ret ); goto exit; } aes_crypt_ecb( &aes, AES_DECRYPT, buf, buf ); buf[16] = '\0'; printf( "\n . Plaintext is \"%s\"\n\n", (char *) buf ); exit: net_close( server_fd ); rsa_free( &rsa ); dhm_free( &dhm ); #if defined(_WIN32) printf( " + Press Enter to exit this program.\n" ); fflush( stdout ); getchar(); #endif return( ret ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 x509parse_verifycrl(x509_cert *crt, x509_cert *ca, x509_crl *crl_list) { int flags = 0; int hash_id; unsigned char hash[64]; if( ca == NULL ) return( flags ); /* * TODO: What happens if no CRL is present? * Suggestion: Revocation state should be unknown if no CRL is present. * For backwards compatibility this is not yet implemented. */ while( crl_list != NULL ) { if( crl_list->version == 0 || crl_list->issuer_raw.len != ca->subject_raw.len || memcmp( crl_list->issuer_raw.p, ca->subject_raw.p, crl_list->issuer_raw.len ) != 0 ) { crl_list = crl_list->next; continue; } /* * Check if CRL is correctly signed by the trusted CA */ hash_id = crl_list->sig_alg; x509_hash( crl_list->tbs.p, crl_list->tbs.len, hash_id, hash ); if( !rsa_pkcs1_verify( &ca->rsa, RSA_PUBLIC, hash_id, 0, hash, crl_list->sig.p ) == 0 ) { /* * CRL is not trusted */ flags |= BADCRL_NOT_TRUSTED; break; } /* * Check for validity of CRL (Do not drop out) */ if( x509parse_time_expired( &crl_list->next_update ) ) flags |= BADCRL_EXPIRED; /* * Check if certificate is revoked */ if( x509parse_revoked(crt, crl_list) ) { flags |= BADCERT_REVOKED; break; } crl_list = crl_list->next; } return flags; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 ssl_parse_client_key_exchange( ssl_context *ssl ) { int ret; size_t i, n = 0; SSL_DEBUG_MSG( 2, ( "=> parse client key exchange" ) ); if( ( ret = ssl_read_record( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != SSL_MSG_HANDSHAKE ) { SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->in_msg[0] != SSL_HS_CLIENT_KEY_EXCHANGE ) { SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_DES_CBC_SHA || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 || ssl->session_negotiate->ciphersuite == TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 ) { #if !defined(POLARSSL_DHM_C) SSL_DEBUG_MSG( 1, ( "support for dhm is not available" ) ); return( POLARSSL_ERR_SSL_FEATURE_UNAVAILABLE ); #else /* * Receive G^Y mod P, premaster = (G^Y)^X mod P */ n = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; if( n < 1 || n > ssl->handshake->dhm_ctx.len || n + 6 != ssl->in_hslen ) { SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ( ret = dhm_read_public( &ssl->handshake->dhm_ctx, ssl->in_msg + 6, n ) ) != 0 ) { SSL_DEBUG_RET( 1, "dhm_read_public", ret ); return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_DHM_RP ); } SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY ); ssl->handshake->pmslen = ssl->handshake->dhm_ctx.len; if( ( ret = dhm_calc_secret( &ssl->handshake->dhm_ctx, ssl->handshake->premaster, &ssl->handshake->pmslen ) ) != 0 ) { SSL_DEBUG_RET( 1, "dhm_calc_secret", ret ); return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_DHM_CS ); } SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K ); #endif } else { if( ssl->rsa_key == NULL ) { SSL_DEBUG_MSG( 1, ( "got no private key" ) ); return( POLARSSL_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* * Decrypt the premaster using own private RSA key */ i = 4; if( ssl->rsa_key ) n = ssl->rsa_key_len( ssl->rsa_key ); ssl->handshake->pmslen = 48; if( ssl->minor_ver != SSL_MINOR_VERSION_0 ) { i += 2; if( ssl->in_msg[4] != ( ( n >> 8 ) & 0xFF ) || ssl->in_msg[5] != ( ( n ) & 0xFF ) ) { SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } } if( ssl->in_hslen != i + n ) { SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->rsa_key ) { ret = ssl->rsa_decrypt( ssl->rsa_key, RSA_PRIVATE, &ssl->handshake->pmslen, ssl->in_msg + i, ssl->handshake->premaster, sizeof(ssl->handshake->premaster) ); } if( ret != 0 || ssl->handshake->pmslen != 48 || ssl->handshake->premaster[0] != ssl->max_major_ver || ssl->handshake->premaster[1] != ssl->max_minor_ver ) { SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); /* * Protection against Bleichenbacher's attack: * invalid PKCS#1 v1.5 padding must not cause * the connection to end immediately; instead, * send a bad_record_mac later in the handshake. */ ssl->handshake->pmslen = 48; ret = ssl->f_rng( ssl->p_rng, ssl->handshake->premaster, ssl->handshake->pmslen ); if( ret != 0 ) return( ret ); } } if( ( ret = ssl_derive_keys( ssl ) ) != 0 ) { SSL_DEBUG_RET( 1, "ssl_derive_keys", ret ); return( ret ); } ssl->state++; SSL_DEBUG_MSG( 2, ( "<= parse client key exchange" ) ); return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 x509parse_verify_top( x509_cert *child, x509_cert *trust_ca, x509_crl *ca_crl, int path_cnt, int *flags, int (*f_vrfy)(void *, x509_cert *, int, int *), void *p_vrfy ) { int hash_id, ret; int ca_flags = 0, check_path_cnt = path_cnt + 1; unsigned char hash[64]; if( x509parse_time_expired( &child->valid_to ) ) *flags |= BADCERT_EXPIRED; /* * Child is the top of the chain. Check against the trust_ca list. */ *flags |= BADCERT_NOT_TRUSTED; while( trust_ca != NULL ) { if( trust_ca->version == 0 || child->issuer_raw.len != trust_ca->subject_raw.len || memcmp( child->issuer_raw.p, trust_ca->subject_raw.p, child->issuer_raw.len ) != 0 ) { trust_ca = trust_ca->next; continue; } /* * Reduce path_len to check against if top of the chain is * the same as the trusted CA */ if( child->subject_raw.len == trust_ca->subject_raw.len && memcmp( child->subject_raw.p, trust_ca->subject_raw.p, child->issuer_raw.len ) == 0 ) { check_path_cnt--; } if( trust_ca->max_pathlen > 0 && trust_ca->max_pathlen < check_path_cnt ) { trust_ca = trust_ca->next; continue; } hash_id = child->sig_alg; x509_hash( child->tbs.p, child->tbs.len, hash_id, hash ); if( rsa_pkcs1_verify( &trust_ca->rsa, RSA_PUBLIC, hash_id, 0, hash, child->sig.p ) != 0 ) { trust_ca = trust_ca->next; continue; } /* * Top of chain is signed by a trusted CA */ *flags &= ~BADCERT_NOT_TRUSTED; break; } /* * If top of chain is not the same as the trusted CA send a verify request * to the callback for any issues with validity and CRL presence for the * trusted CA certificate. */ if( trust_ca != NULL && ( child->subject_raw.len != trust_ca->subject_raw.len || memcmp( child->subject_raw.p, trust_ca->subject_raw.p, child->issuer_raw.len ) != 0 ) ) { /* Check trusted CA's CRL for then chain's top crt */ *flags |= x509parse_verifycrl( child, trust_ca, ca_crl ); if( x509parse_time_expired( &trust_ca->valid_to ) ) ca_flags |= BADCERT_EXPIRED; if( NULL != f_vrfy ) { if( ( ret = f_vrfy( p_vrfy, trust_ca, path_cnt + 1, &ca_flags ) ) != 0 ) return( ret ); } } /* Call callback on top cert */ if( NULL != f_vrfy ) { if( ( ret = f_vrfy(p_vrfy, child, path_cnt, flags ) ) != 0 ) return( ret ); } *flags |= ca_flags; return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'RSA blinding on CRT operations to counter timing attacks'</s>
<s>[INST] Given the following code containing errors, provide 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 crt_to_pubkey(const gnutls_datum_t *raw_crt, gnutls_datum_t * out) { gnutls_pubkey_t pub = NULL; gnutls_x509_crt_t crt = NULL; int ret; out->data = NULL; ret = gnutls_x509_crt_init(&crt); if (ret < 0) return gnutls_assert_val(DANE_E_PUBKEY_ERROR); ret = gnutls_pubkey_init( &pub); if (ret < 0) { gnutls_assert(); ret = DANE_E_PUBKEY_ERROR; goto cleanup; } ret = gnutls_x509_crt_import(crt, raw_crt, GNUTLS_X509_FMT_DER); if (ret < 0) { gnutls_assert(); ret = DANE_E_PUBKEY_ERROR; goto cleanup; } ret = gnutls_pubkey_import_x509(pub, crt, 0); if (ret < 0) { gnutls_assert(); ret = DANE_E_PUBKEY_ERROR; goto cleanup; } ret = gnutls_pubkey_export2(pub, GNUTLS_X509_FMT_DER, out); if (ret < 0) { gnutls_assert(); ret = DANE_E_PUBKEY_ERROR; goto cleanup; } ret = 0; goto clean_certs; cleanup: free(out->data); out->data = NULL; clean_certs: if (pub) gnutls_pubkey_deinit(pub); if (crt) gnutls_x509_crt_deinit(crt); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Adding dane_raw_tlsa to allow initialization of dane_query_t from DANE records based on external DNS resolutions. Also fixing a buffer overflow. Signed-off-by: Nikos Mavrogiannopoulos <nmav@gnutls.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void* ipc_rcu_alloc(int size) { void* out; /* * We prepend the allocation with the rcu struct, and * workqueue if necessary (for vmalloc). */ if (rcu_use_vmalloc(size)) { out = vmalloc(HDRLEN_VMALLOC + size); if (out) { out += HDRLEN_VMALLOC; container_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 1; container_of(out, struct ipc_rcu_hdr, data)->refcount = 1; } } else { out = kmalloc(HDRLEN_KMALLOC + size, GFP_KERNEL); if (out) { out += HDRLEN_KMALLOC; container_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 0; container_of(out, struct ipc_rcu_hdr, data)->refcount = 1; } } return out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [davidlohr.bueso@hp.com: do not call sem_lock when bogus sma] [davidlohr.bueso@hp.com: make refcounter atomic] Signed-off-by: Rik van Riel <riel@redhat.com> Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Acked-by: Davidlohr Bueso <davidlohr.bueso@hp.com> Cc: Chegu Vinod <chegu_vinod@hp.com> Cc: Jason Low <jason.low2@hp.com> Reviewed-by: Michel Lespinasse <walken@google.com> Cc: Peter Hurley <peter@hurleysoftware.com> Cc: Stanislav Kinsbursky <skinsbursky@parallels.com> Tested-by: Emmanuel Benisty <benisty.e@gmail.com> Tested-by: Sedat Dilek <sedat.dilek@gmail.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops, unsigned, nsops, const struct timespec __user *, timeout) { int error = -EINVAL; struct sem_array *sma; struct sembuf fast_sops[SEMOPM_FAST]; struct sembuf* sops = fast_sops, *sop; struct sem_undo *un; int undos = 0, alter = 0, max; struct sem_queue queue; unsigned long jiffies_left = 0; struct ipc_namespace *ns; struct list_head tasks; ns = current->nsproxy->ipc_ns; if (nsops < 1 || semid < 0) return -EINVAL; if (nsops > ns->sc_semopm) return -E2BIG; if(nsops > SEMOPM_FAST) { sops = kmalloc(sizeof(*sops)*nsops,GFP_KERNEL); if(sops==NULL) return -ENOMEM; } if (copy_from_user (sops, tsops, nsops * sizeof(*tsops))) { error=-EFAULT; goto out_free; } if (timeout) { struct timespec _timeout; if (copy_from_user(&_timeout, timeout, sizeof(*timeout))) { error = -EFAULT; goto out_free; } if (_timeout.tv_sec < 0 || _timeout.tv_nsec < 0 || _timeout.tv_nsec >= 1000000000L) { error = -EINVAL; goto out_free; } jiffies_left = timespec_to_jiffies(&_timeout); } max = 0; for (sop = sops; sop < sops + nsops; sop++) { if (sop->sem_num >= max) max = sop->sem_num; if (sop->sem_flg & SEM_UNDO) undos = 1; if (sop->sem_op != 0) alter = 1; } if (undos) { un = find_alloc_undo(ns, semid); if (IS_ERR(un)) { error = PTR_ERR(un); goto out_free; } } else un = NULL; INIT_LIST_HEAD(&tasks); rcu_read_lock(); sma = sem_obtain_object_check(ns, semid); if (IS_ERR(sma)) { if (un) rcu_read_unlock(); error = PTR_ERR(sma); goto out_free; } error = -EFBIG; if (max >= sma->sem_nsems) { rcu_read_unlock(); goto out_wakeup; } error = -EACCES; if (ipcperms(ns, &sma->sem_perm, alter ? S_IWUGO : S_IRUGO)) { rcu_read_unlock(); goto out_wakeup; } error = security_sem_semop(sma, sops, nsops, alter); if (error) { rcu_read_unlock(); goto out_wakeup; } /* * semid identifiers are not unique - find_alloc_undo may have * allocated an undo structure, it was invalidated by an RMID * and now a new array with received the same id. Check and fail. * This case can be detected checking un->semid. The existence of * "un" itself is guaranteed by rcu. */ error = -EIDRM; ipc_lock_object(&sma->sem_perm); if (un) { if (un->semid == -1) { rcu_read_unlock(); goto out_unlock_free; } else { /* * rcu lock can be released, "un" cannot disappear: * - sem_lock is acquired, thus IPC_RMID is * impossible. * - exit_sem is impossible, it always operates on * current (or a dead task). */ rcu_read_unlock(); } } error = try_atomic_semop (sma, sops, nsops, un, task_tgid_vnr(current)); if (error <= 0) { if (alter && error == 0) do_smart_update(sma, sops, nsops, 1, &tasks); goto out_unlock_free; } /* We need to sleep on this operation, so we put the current * task into the pending queue and go to sleep. */ queue.sops = sops; queue.nsops = nsops; queue.undo = un; queue.pid = task_tgid_vnr(current); queue.alter = alter; if (nsops == 1) { struct sem *curr; curr = &sma->sem_base[sops->sem_num]; if (alter) list_add_tail(&queue.list, &curr->sem_pending); else list_add(&queue.list, &curr->sem_pending); } else { if (alter) list_add_tail(&queue.list, &sma->sem_pending); else list_add(&queue.list, &sma->sem_pending); sma->complex_count++; } queue.status = -EINTR; queue.sleeper = current; sleep_again: current->state = TASK_INTERRUPTIBLE; sem_unlock(sma); if (timeout) jiffies_left = schedule_timeout(jiffies_left); else schedule(); error = get_queue_result(&queue); if (error != -EINTR) { /* fast path: update_queue already obtained all requested * resources. * Perform a smp_mb(): User space could assume that semop() * is a memory barrier: Without the mb(), the cpu could * speculatively read in user space stale data that was * overwritten by the previous owner of the semaphore. */ smp_mb(); goto out_free; } sma = sem_obtain_lock(ns, semid); /* * Wait until it's guaranteed that no wakeup_sem_queue_do() is ongoing. */ error = get_queue_result(&queue); /* * Array removed? If yes, leave without sem_unlock(). */ if (IS_ERR(sma)) { goto out_free; } /* * If queue.status != -EINTR we are woken up by another process. * Leave without unlink_queue(), but with sem_unlock(). */ if (error != -EINTR) { goto out_unlock_free; } /* * If an interrupt occurred we have to clean up the queue */ if (timeout && jiffies_left == 0) error = -EAGAIN; /* * If the wakeup was spurious, just retry */ if (error == -EINTR && !signal_pending(current)) goto sleep_again; unlink_queue(sma, &queue); out_unlock_free: sem_unlock(sma); out_wakeup: wake_up_sem_queue_do(&tasks); out_free: if(sops != fast_sops) kfree(sops); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'ipc,sem: fine grained locking for semtimedop Introduce finer grained locking for semtimedop, to handle the common case of a program wanting to manipulate one semaphore from an array with multiple semaphores. If the call is a semop manipulating just one semaphore in an array with multiple semaphores, only take the lock for that semaphore itself. If the call needs to manipulate multiple semaphores, or another caller is in a transaction that manipulates multiple semaphores, the sem_array lock is taken, as well as all the locks for the individual semaphores. On a 24 CPU system, performance numbers with the semop-multi test with N threads and N semaphores, look like this: vanilla Davidlohr's Davidlohr's + Davidlohr's + threads patches rwlock patches v3 patches 10 610652 726325 1783589 2142206 20 341570 365699 1520453 1977878 30 288102 307037 1498167 2037995 40 290714 305955 1612665 2256484 50 288620 312890 1733453 2650292 60 289987 306043 1649360 2388008 70 291298 306347 1723167 2717486 80 290948 305662 1729545 2763582 90 290996 306680 1736021 2757524 100 292243 306700 1773700 3059159 [davidlohr.bueso@hp.com: do not call sem_lock when bogus sma] [davidlohr.bueso@hp.com: make refcounter atomic] Signed-off-by: Rik van Riel <riel@redhat.com> Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Acked-by: Davidlohr Bueso <davidlohr.bueso@hp.com> Cc: Chegu Vinod <chegu_vinod@hp.com> Cc: Jason Low <jason.low2@hp.com> Reviewed-by: Michel Lespinasse <walken@google.com> Cc: Peter Hurley <peter@hurleysoftware.com> Cc: Stanislav Kinsbursky <skinsbursky@parallels.com> Tested-by: Emmanuel Benisty <benisty.e@gmail.com> Tested-by: Sedat Dilek <sedat.dilek@gmail.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int client_func(const test_param_t *test) { struct gg_session *gs; struct gg_login_params glp; char tmp; gg_proxy_host = HOST_PROXY; gg_proxy_port = 8080; gg_proxy_enabled = test->proxy_mode; memset(&glp, 0, sizeof(glp)); glp.uin = 1; glp.password = "dupa.8"; glp.async = test->async_mode; glp.resolver = GG_RESOLVER_PTHREAD; if (test->server) glp.server_addr = inet_addr(HOST_LOCAL); if (test->ssl_mode) glp.tls = GG_SSL_REQUIRED; while (read(timeout_pipe[0], &tmp, 1) != -1); gs = gg_login(&glp); if (gs == NULL) return 0; if (!test->async_mode) { gg_free_session(gs); return 1; } else { for (;;) { fd_set rd, wr; int res; int max_fd; struct timeval *tv_ptr = NULL; #ifdef CLIENT_TIMEOUT struct timeval tv; tv.tv_sec = CLIENT_TIMEOUT; tv.tv_usec = 0; tv_ptr = &tv; #endif FD_ZERO(&rd); FD_ZERO(&wr); max_fd = timeout_pipe[0]; if (gs->fd > max_fd) max_fd = gs->fd; FD_SET(timeout_pipe[0], &rd); if ((gs->check & GG_CHECK_READ)) FD_SET(gs->fd, &rd); if ((gs->check & GG_CHECK_WRITE)) FD_SET(gs->fd, &wr); res = select(max_fd + 1, &rd, &wr, NULL, tv_ptr); if (res == 0) { debug("Test timeout\n"); gg_free_session(gs); return 0; } if (res == -1 && errno != EINTR) { debug("select() failed: %s\n", strerror(errno)); gg_free_session(gs); return -1; } if (res == -1) continue; if (FD_ISSET(timeout_pipe[0], &rd)) { if (read(timeout_pipe[0], &tmp, 1) != 1) { debug("Test error\n"); gg_free_session(gs); return -1; } if (!gs->soft_timeout) { debug("Hard timeout\n"); gg_free_session(gs); return 0; } } if (FD_ISSET(gs->fd, &rd) || FD_ISSET(gs->fd, &wr) || (FD_ISSET(timeout_pipe[0], &rd) && gs->soft_timeout)) { struct gg_event *ge; if (FD_ISSET(timeout_pipe[0], &rd)) { debug("Soft timeout\n"); gs->timeout = 0; } ge = gg_watch_fd(gs); if (!ge) { debug("gg_watch_fd() failed\n"); gg_free_session(gs); return -1; } switch (ge->type) { case GG_EVENT_CONN_SUCCESS: gg_event_free(ge); gg_free_session(gs); return 1; case GG_EVENT_CONN_FAILED: gg_event_free(ge); gg_free_session(gs); return 0; case GG_EVENT_NONE: break; default: debug("Unknown event %d\n", ge->type); gg_event_free(ge); gg_free_session(gs); return -1; } gg_event_free(ge); } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Odkąd biblioteka weryfikuje certyfikaty ciężko testować z self-signed.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: find_referral_tgs(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, krb5_principal *krbtgt_princ) { krb5_error_code retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; char **realms = NULL, *hostname = NULL; krb5_data srealm = request->server->realm; if (!is_referral_req(kdc_active_realm, request)) goto cleanup; hostname = data2string(krb5_princ_component(kdc_context, request->server, 1)); if (hostname == NULL) { retval = ENOMEM; goto cleanup; } /* If the hostname doesn't contain a '.', it's not a FQDN. */ if (strchr(hostname, '.') == NULL) goto cleanup; retval = krb5_get_host_realm(kdc_context, hostname, &realms); if (retval) { /* no match found */ kdc_err(kdc_context, retval, "unable to find realm of host"); goto cleanup; } /* Don't return a referral to the empty realm or the service realm. */ if (realms == NULL || realms[0] == '\0' || data_eq_string(srealm, realms[0])) { retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto cleanup; } retval = krb5_build_principal(kdc_context, krbtgt_princ, srealm.length, srealm.data, "krbtgt", realms[0], (char *)0); cleanup: krb5_free_host_realm(kdc_context, realms); free(hostname); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'KDC null deref due to referrals [CVE-2013-1417] An authenticated remote client can cause a KDC to crash by making a valid TGS-REQ to a KDC serving a realm with a single-component name. The process_tgs_req() function dereferences a null pointer because an unusual failure condition causes a helper function to return success. While attempting to provide cross-realm referrals for host-based service principals, the find_referral_tgs() function could return a TGS principal for a zero-length realm name (indicating that the hostname in the service principal has no known realm associated with it). Subsequently, the find_alternate_tgs() function would attempt to construct a path to this empty-string realm, and return success along with a null pointer in its output parameter. This happens because krb5_walk_realm_tree() returns a list of length one when it attempts to construct a transit path between a single-component realm and the empty-string realm. This list causes a loop in find_alternate_tgs() to iterate over zero elements, resulting in the unexpected output of a null pointer, which process_tgs_req() proceeds to dereference because there is no error condition. Add an error condition to find_referral_tgs() when krb5_get_host_realm() returns an empty realm name. Also add an error condition to find_alternate_tgs() to handle the length-one output from krb5_walk_realm_tree(). The vulnerable configuration is not likely to arise in practice. (Realm names that have a single component are likely to be test realms.) Releases prior to krb5-1.11 are not vulnerable. Thanks to Sol Jerome for reporting this problem. CVSSv2: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C (cherry picked from commit 3c7f1c21ffaaf6c90f1045f0f5440303c766acc0) ticket: 7668 version_fixed: 1.11.4 status: resolved'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: unsigned long lh_char_hash(const void *k) { unsigned int h = 0; const char* data = (const char*)k; while( *data!=0 ) h = h*129 + (unsigned int)(*data++) + LH_PRIME; return h; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-310'], 'message': 'Patch to address the following issues: * CVE-2013-6371: hash collision denial of service * CVE-2013-6370: buffer overflow if size_t is larger than int'</s>
<s>[INST] Given the following code containing errors, provide 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 *hashtable_get(hashtable_t *hashtable, const char *key) { pair_t *pair; size_t hash; bucket_t *bucket; hash = hash_str(key); bucket = &hashtable->buckets[hash % num_buckets(hashtable)]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(!pair) return NULL; return pair->value; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void read_conf(FILE *conffile) { char *buffer, *line, *val; buffer = loadfile(conffile); for (line = strtok(buffer, "\r\n"); line; line = strtok(NULL, "\r\n")) { if (!strncmp(line, "export ", 7)) continue; val = strchr(line, '='); if (!val) { printf("invalid configuration line\n"); break; } *val++ = '\0'; if (!strcmp(line, "JSON_INDENT")) conf.indent = atoi(val); if (!strcmp(line, "JSON_COMPACT")) conf.compact = atoi(val); if (!strcmp(line, "JSON_ENSURE_ASCII")) conf.ensure_ascii = atoi(val); if (!strcmp(line, "JSON_PRESERVE_ORDER")) conf.preserve_order = atoi(val); if (!strcmp(line, "JSON_SORT_KEYS")) conf.sort_keys = atoi(val); if (!strcmp(line, "STRIP")) conf.strip = atoi(val); } free(buffer); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing.'</s>
<s>[INST] Given the following code containing errors, provide 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 early_init_amd(struct cpuinfo_x86 *c) { early_init_amd_mc(c); /* * c->x86_power is 8000_0007 edx. Bit 8 is TSC runs at constant rate * with P/T states and does not stop in deep C-states */ if (c->x86_power & (1 << 8)) { set_cpu_cap(c, X86_FEATURE_CONSTANT_TSC); set_cpu_cap(c, X86_FEATURE_NONSTOP_TSC); if (!check_tsc_unstable()) sched_clock_stable = 1; } #ifdef CONFIG_X86_64 set_cpu_cap(c, X86_FEATURE_SYSCALL32); #else /* Set MTRR capability flag if appropriate */ if (c->x86 == 5) if (c->x86_model == 13 || c->x86_model == 9 || (c->x86_model == 8 && c->x86_mask >= 8)) set_cpu_cap(c, X86_FEATURE_K6_MTRR); #endif #if defined(CONFIG_X86_LOCAL_APIC) && defined(CONFIG_PCI) /* check CPU config space for extended APIC ID */ if (cpu_has_apic && c->x86 >= 0xf) { unsigned int val; val = read_pci_config(0, 24, 0, 0x68); if ((val & ((1 << 17) | (1 << 18))) == ((1 << 17) | (1 << 18))) set_cpu_cap(c, X86_FEATURE_EXTD_APICID); } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'x86, cpu, amd: Add workaround for family 16h, erratum 793 This adds the workaround for erratum 793 as a precaution in case not every BIOS implements it. This addresses CVE-2013-6885. Erratum text: [Revision Guide for AMD Family 16h Models 00h-0Fh Processors, document 51810 Rev. 3.04 November 2013] 793 Specific Combination of Writes to Write Combined Memory Types and Locked Instructions May Cause Core Hang Description Under a highly specific and detailed set of internal timing conditions, a locked instruction may trigger a timing sequence whereby the write to a write combined memory type is not flushed, causing the locked instruction to stall indefinitely. Potential Effect on System Processor core hang. Suggested Workaround BIOS should set MSR C001_1020[15] = 1b. Fix Planned No fix planned [ hpa: updated description, fixed typo in MSR name ] Signed-off-by: Borislav Petkov <bp@suse.de> Link: http://lkml.kernel.org/r/20140114230711.GS29865@pd.tnic Tested-by: Aravind Gopalakrishnan <aravind.gopalakrishnan@amd.com> Signed-off-by: H. Peter Anvin <hpa@linux.intel.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int dummy_ipv6_recv_error(struct sock *sk, struct msghdr *msg, int len) { return -EAFNOSUPPORT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: fix addr_len/msg->msg_namelen assignment in recv_error and rxpmtu functions Commit bceaa90240b6019ed73b49965eac7d167610be69 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") conditionally updated addr_len if the msg_name is written to. The recv_error and rxpmtu functions relied on the recvmsg functions to set up addr_len before. As this does not happen any more we have to pass addr_len to those functions as well and set it to the size of the corresponding sockaddr length. This broke traceroute and such. Fixes: bceaa90240b6 ("inet: prevent leakage of uninitialized memory to user in recv syscalls") Reported-by: Brad Spengler <spender@grsecurity.net> Reported-by: Tom Labanowski Cc: mpb <mpb.mail@gmail.com> Cc: David S. Miller <davem@davemloft.net> Cc: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool winbind_name_list_to_sid_string_list(struct pwb_context *ctx, const char *user, const char *name_list, char *sid_list_buffer, int sid_list_buffer_size) { bool result = false; char *current_name = NULL; const char *search_location; const char *comma; int len; if (sid_list_buffer_size > 0) { sid_list_buffer[0] = 0; } search_location = name_list; while ((comma = strchr(search_location, ',')) != NULL) { current_name = strndup(search_location, comma - search_location); if (NULL == current_name) { goto out; } if (!winbind_name_to_sid_string(ctx, user, current_name, sid_list_buffer, sid_list_buffer_size)) { /* * If one group name failed, we must not fail * the authentication totally, continue with * the following group names. If user belongs to * one of the valid groups, we must allow it * login. -- BoYang */ _pam_log(ctx, LOG_INFO, "cannot convert group %s to sid, " "check if group %s is valid group.", current_name, current_name); _make_remark_format(ctx, PAM_TEXT_INFO, _("Cannot convert group %s " "to sid, please contact your administrator to see " "if group %s is valid."), current_name, current_name); SAFE_FREE(current_name); search_location = comma + 1; continue; } SAFE_FREE(current_name); if (!safe_append_string(sid_list_buffer, ",", sid_list_buffer_size)) { goto out; } search_location = comma + 1; } if (!winbind_name_to_sid_string(ctx, user, search_location, sid_list_buffer, sid_list_buffer_size)) { _pam_log(ctx, LOG_INFO, "cannot convert group %s to sid, " "check if group %s is valid group.", search_location, search_location); _make_remark_format(ctx, PAM_TEXT_INFO, _("Cannot convert group %s " "to sid, please contact your administrator to see " "if group %s is valid."), search_location, search_location); /* * The lookup of the last name failed.. * It results in require_member_of_sid ends with ',' * It is malformated parameter here, overwrite the last ','. */ len = strlen(sid_list_buffer); if ((len != 0) && (sid_list_buffer[len - 1] == ',')) { sid_list_buffer[len - 1] = '\0'; } } result = true; out: SAFE_FREE(current_name); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'fail authentication for single group name which cannot be converted to sid furthermore if more than one name is supplied and no sid is converted then also fail. Bug: https://bugzilla.samba.org/show_bug.cgi?id=8598 Signed-off-by: Noel Power <noel.power@suse.com> Reviewed-by: Andreas Schneider <asn@samba.org> Reviewed-by: David Disseldorp <ddiss@samba.org> Autobuild-User(master): David Disseldorp <ddiss@samba.org> Autobuild-Date(master): Fri Nov 29 15:45:11 CET 2013 on sn-devel-104'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void init_sasl_conn(conn *c) { assert(c); /* should something else be returned? */ if (!settings.sasl) return; if (!c->sasl_conn) { int result=sasl_server_new("memcached", NULL, my_sasl_hostname[0] ? my_sasl_hostname : NULL, NULL, NULL, NULL, 0, &c->sasl_conn); if (result != SASL_OK) { if (settings.verbose) { fprintf(stderr, "Failed to initialize SASL conn.\n"); } c->sasl_conn = NULL; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'explicitly record sasl auth states It was previously possible to bypass authentication due to implicit state management. Now we explicitly consider ourselves unauthenticated on any new connections and authentication attempts. bug316 Signed-off-by: Dustin Sallings <dustin@spy.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool BSONObj::valid() const { int mySize = objsize(); try { BSONObjIterator it(*this); while( it.moreWithEOO() ) { // both throw exception on failure BSONElement e = it.next(true); if ( e.size() >= mySize ) return false; e.validate(); if (e.eoo()) { if (it.moreWithEOO()) return false; return true; } else if (e.isABSONObj()) { if(!e.embeddedObject().valid()) return false; } else if (e.type() == CodeWScope) { if(!e.codeWScopeObject().valid()) return false; } } } catch (...) { } return false; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'SERVER-7769 - turn objcheck on by default and use new fast bson validate'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QueryParamsTest() : cxxtools::unit::TestSuite("queryparams") { registerMethod("testQueryParams", *this, &QueryParamsTest::testQueryParams); registerMethod("testCopy", *this, &QueryParamsTest::testCopy); registerMethod("testParseUrl", *this, &QueryParamsTest::testParseUrl); registerMethod("testParseUrlSpecialChar", *this, &QueryParamsTest::testParseUrlSpecialChar); registerMethod("testCount", *this, &QueryParamsTest::testCount); registerMethod("testCombine", *this, &QueryParamsTest::testCombine); registerMethod("testIterator", *this, &QueryParamsTest::testIterator); registerMethod("testGetUrl", *this, &QueryParamsTest::testGetUrl); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'fix parsing double % in query parameters'</s>
<s>[INST] Given the following code containing errors, provide 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 Bigint * Balloc(int k) { int x; Bigint *rv; _THREAD_PRIVATE_MUTEX_LOCK(dtoa_mutex); if ((rv = freelist[k])) { freelist[k] = rv->next; } else { x = 1 << k; rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(Long)); rv->k = k; rv->maxwds = x; } _THREAD_PRIVATE_MUTEX_UNLOCK(dtoa_mutex); rv->sign = rv->wds = 0; return rv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Added missing allocation checks'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(imageaffinematrixget) { double affine[6]; long type; zval *options; zval **tmp; int res = GD_FALSE, i; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) { return; } switch((gdAffineStandardMatrix)type) { case GD_AFFINE_TRANSLATE: case GD_AFFINE_SCALE: { double x, y; if (Z_TYPE_P(options) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options"); } if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) { convert_to_double_ex(tmp); x = Z_DVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) { convert_to_double_ex(tmp); y = Z_DVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (type == GD_AFFINE_TRANSLATE) { res = gdAffineTranslate(affine, x, y); } else { res = gdAffineScale(affine, x, y); } break; } case GD_AFFINE_ROTATE: case GD_AFFINE_SHEAR_HORIZONTAL: case GD_AFFINE_SHEAR_VERTICAL: { double angle; convert_to_double_ex(&options); angle = Z_DVAL_P(options); if (type == GD_AFFINE_SHEAR_HORIZONTAL) { res = gdAffineShearHorizontal(affine, angle); } else if (type == GD_AFFINE_SHEAR_VERTICAL) { res = gdAffineShearVertical(affine, angle); } else { res = gdAffineRotate(affine, angle); } break; } default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type); RETURN_FALSE; } if (res == GD_FALSE) { RETURN_FALSE; } else { array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, affine[i]); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: plpython2_validator(PG_FUNCTION_ARGS) { return plpython_validator(fcinfo); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Prevent privilege escalation in explicit calls to PL validators. The primary role of PL validators is to be called implicitly during CREATE FUNCTION, but they are also normal functions that a user can call explicitly. Add a permissions check to each validator to ensure that a user cannot use explicit validator calls to achieve things he could not otherwise achieve. Back-patch to 8.4 (all supported versions). Non-core procedural language extensions ought to make the same two-line change to their own validators. Andres Freund, reviewed by Tom Lane and Noah Misch. Security: CVE-2014-0061'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _outConstraint(StringInfo str, const Constraint *node) { WRITE_NODE_TYPE("CONSTRAINT"); WRITE_STRING_FIELD(conname); WRITE_BOOL_FIELD(deferrable); WRITE_BOOL_FIELD(initdeferred); WRITE_LOCATION_FIELD(location); appendStringInfoString(str, " :contype "); switch (node->contype) { case CONSTR_NULL: appendStringInfoString(str, "NULL"); break; case CONSTR_NOTNULL: appendStringInfoString(str, "NOT_NULL"); break; case CONSTR_DEFAULT: appendStringInfoString(str, "DEFAULT"); WRITE_NODE_FIELD(raw_expr); WRITE_STRING_FIELD(cooked_expr); break; case CONSTR_CHECK: appendStringInfoString(str, "CHECK"); WRITE_BOOL_FIELD(is_no_inherit); WRITE_NODE_FIELD(raw_expr); WRITE_STRING_FIELD(cooked_expr); break; case CONSTR_PRIMARY: appendStringInfoString(str, "PRIMARY_KEY"); WRITE_NODE_FIELD(keys); WRITE_NODE_FIELD(options); WRITE_STRING_FIELD(indexname); WRITE_STRING_FIELD(indexspace); /* access_method and where_clause not currently used */ break; case CONSTR_UNIQUE: appendStringInfoString(str, "UNIQUE"); WRITE_NODE_FIELD(keys); WRITE_NODE_FIELD(options); WRITE_STRING_FIELD(indexname); WRITE_STRING_FIELD(indexspace); /* access_method and where_clause not currently used */ break; case CONSTR_EXCLUSION: appendStringInfoString(str, "EXCLUSION"); WRITE_NODE_FIELD(exclusions); WRITE_NODE_FIELD(options); WRITE_STRING_FIELD(indexname); WRITE_STRING_FIELD(indexspace); WRITE_STRING_FIELD(access_method); WRITE_NODE_FIELD(where_clause); break; case CONSTR_FOREIGN: appendStringInfoString(str, "FOREIGN_KEY"); WRITE_NODE_FIELD(pktable); WRITE_NODE_FIELD(fk_attrs); WRITE_NODE_FIELD(pk_attrs); WRITE_CHAR_FIELD(fk_matchtype); WRITE_CHAR_FIELD(fk_upd_action); WRITE_CHAR_FIELD(fk_del_action); WRITE_NODE_FIELD(old_conpfeqop); WRITE_BOOL_FIELD(skip_validation); WRITE_BOOL_FIELD(initially_valid); break; case CONSTR_ATTR_DEFERRABLE: appendStringInfoString(str, "ATTR_DEFERRABLE"); break; case CONSTR_ATTR_NOT_DEFERRABLE: appendStringInfoString(str, "ATTR_NOT_DEFERRABLE"); break; case CONSTR_ATTR_DEFERRED: appendStringInfoString(str, "ATTR_DEFERRED"); break; case CONSTR_ATTR_IMMEDIATE: appendStringInfoString(str, "ATTR_IMMEDIATE"); break; default: appendStringInfo(str, "<unrecognized_constraint %d>", (int) node->contype); break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ATPostAlterTypeCleanup(List **wqueue, AlteredTableInfo *tab, LOCKMODE lockmode) { ObjectAddress obj; ListCell *def_item; ListCell *oid_item; /* * Re-parse the index and constraint definitions, and attach them to the * appropriate work queue entries. We do this before dropping because in * the case of a FOREIGN KEY constraint, we might not yet have exclusive * lock on the table the constraint is attached to, and we need to get * that before dropping. It's safe because the parser won't actually look * at the catalogs to detect the existing entry. */ forboth(oid_item, tab->changedConstraintOids, def_item, tab->changedConstraintDefs) ATPostAlterTypeParse(lfirst_oid(oid_item), (char *) lfirst(def_item), wqueue, lockmode, tab->rewrite); forboth(oid_item, tab->changedIndexOids, def_item, tab->changedIndexDefs) ATPostAlterTypeParse(lfirst_oid(oid_item), (char *) lfirst(def_item), wqueue, lockmode, tab->rewrite); /* * Now we can drop the existing constraints and indexes --- constraints * first, since some of them might depend on the indexes. In fact, we * have to delete FOREIGN KEY constraints before UNIQUE constraints, but * we already ordered the constraint list to ensure that would happen. It * should be okay to use DROP_RESTRICT here, since nothing else should be * depending on these objects. */ foreach(oid_item, tab->changedConstraintOids) { obj.classId = ConstraintRelationId; obj.objectId = lfirst_oid(oid_item); obj.objectSubId = 0; performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL); } foreach(oid_item, tab->changedIndexOids) { obj.classId = RelationRelationId; obj.objectId = lfirst_oid(oid_item); obj.objectSubId = 0; performDeletion(&obj, DROP_RESTRICT, PERFORM_DELETION_INTERNAL); } /* * The objects will get recreated during subsequent passes over the work * queue. */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Avoid repeated name lookups during table and index DDL. If the name lookups come to different conclusions due to concurrent activity, we might perform some parts of the DDL on a different table than other parts. At least in the case of CREATE INDEX, this can be used to cause the permissions checks to be performed against a different table than the index creation, allowing for a privilege escalation attack. This changes the calling convention for DefineIndex, CreateTrigger, transformIndexStmt, transformAlterTableStmt, CheckIndexCompatible (in 9.2 and newer), and AlterTable (in 9.1 and older). In addition, CheckRelationOwnership is removed in 9.2 and newer and the calling convention is changed in older branches. A field has also been added to the Constraint node (FkConstraint in 8.4). Third-party code calling these functions or using the Constraint node will require updating. Report by Andres Freund. Patch by Robert Haas and Andres Freund, reviewed by Tom Lane. Security: CVE-2014-0062'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: queryin(char *buf) { QPRS_STATE state; int32 i; ltxtquery *query; int32 commonlen; ITEM *ptr; NODE *tmp; int32 pos = 0; #ifdef BS_DEBUG char pbuf[16384], *cur; #endif /* init state */ state.buf = buf; state.state = WAITOPERAND; state.count = 0; state.num = 0; state.str = NULL; /* init list of operand */ state.sumlen = 0; state.lenop = 64; state.curop = state.op = (char *) palloc(state.lenop); *(state.curop) = '\0'; /* parse query & make polish notation (postfix, but in reverse order) */ makepol(&state); if (!state.num) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"), errdetail("Empty query."))); /* make finish struct */ commonlen = COMPUTESIZE(state.num, state.sumlen); query = (ltxtquery *) palloc(commonlen); SET_VARSIZE(query, commonlen); query->size = state.num; ptr = GETQUERY(query); /* set item in polish notation */ for (i = 0; i < state.num; i++) { ptr[i].type = state.str->type; ptr[i].val = state.str->val; ptr[i].distance = state.str->distance; ptr[i].length = state.str->length; ptr[i].flag = state.str->flag; tmp = state.str->next; pfree(state.str); state.str = tmp; } /* set user friendly-operand view */ memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen); pfree(state.op); /* set left operand's position for every operator */ pos = 0; findoprnd(ptr, &pos); return query; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: txid_current_snapshot(PG_FUNCTION_ARGS) { TxidSnapshot *snap; uint32 nxip, i, size; TxidEpoch state; Snapshot cur; cur = GetActiveSnapshot(); if (cur == NULL) elog(ERROR, "no active snapshot set"); load_xid_epoch(&state); /* allocate */ nxip = cur->xcnt; size = TXID_SNAPSHOT_SIZE(nxip); snap = palloc(size); SET_VARSIZE(snap, size); /* fill */ snap->xmin = convert_xid(cur->xmin, &state); snap->xmax = convert_xid(cur->xmax, &state); snap->nxip = nxip; for (i = 0; i < nxip; i++) snap->xip[i] = convert_xid(cur->xip[i], &state); /* we want them guaranteed to be in ascending order */ sort_snapshot(snap); PG_RETURN_POINTER(snap); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: hstore_from_record(PG_FUNCTION_ARGS) { HeapTupleHeader rec; int32 buflen; HStore *out; Pairs *pairs; Oid tupType; int32 tupTypmod; TupleDesc tupdesc; HeapTupleData tuple; RecordIOData *my_extra; int ncolumns; int i, j; Datum *values; bool *nulls; if (PG_ARGISNULL(0)) { Oid argtype = get_fn_expr_argtype(fcinfo->flinfo, 0); /* * have no tuple to look at, so the only source of type info is the * argtype. The lookup_rowtype_tupdesc call below will error out if we * don't have a known composite type oid here. */ tupType = argtype; tupTypmod = -1; rec = NULL; } else { rec = PG_GETARG_HEAPTUPLEHEADER(0); /* Extract type info from the tuple itself */ tupType = HeapTupleHeaderGetTypeId(rec); tupTypmod = HeapTupleHeaderGetTypMod(rec); } tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod); ncolumns = tupdesc->natts; /* * We arrange to look up the needed I/O info just once per series of * calls, assuming the record type doesn't change underneath us. */ my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra; if (my_extra == NULL || my_extra->ncolumns != ncolumns) { fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt, sizeof(RecordIOData) - sizeof(ColumnIOData) + ncolumns * sizeof(ColumnIOData)); my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra; my_extra->record_type = InvalidOid; my_extra->record_typmod = 0; } if (my_extra->record_type != tupType || my_extra->record_typmod != tupTypmod) { MemSet(my_extra, 0, sizeof(RecordIOData) - sizeof(ColumnIOData) + ncolumns * sizeof(ColumnIOData)); my_extra->record_type = tupType; my_extra->record_typmod = tupTypmod; my_extra->ncolumns = ncolumns; } pairs = palloc(ncolumns * sizeof(Pairs)); if (rec) { /* Build a temporary HeapTuple control structure */ tuple.t_len = HeapTupleHeaderGetDatumLength(rec); ItemPointerSetInvalid(&(tuple.t_self)); tuple.t_tableOid = InvalidOid; tuple.t_data = rec; values = (Datum *) palloc(ncolumns * sizeof(Datum)); nulls = (bool *) palloc(ncolumns * sizeof(bool)); /* Break down the tuple into fields */ heap_deform_tuple(&tuple, tupdesc, values, nulls); } else { values = NULL; nulls = NULL; } for (i = 0, j = 0; i < ncolumns; ++i) { ColumnIOData *column_info = &my_extra->columns[i]; Oid column_type = tupdesc->attrs[i]->atttypid; char *value; /* Ignore dropped columns in datatype */ if (tupdesc->attrs[i]->attisdropped) continue; pairs[j].key = NameStr(tupdesc->attrs[i]->attname); pairs[j].keylen = hstoreCheckKeyLen(strlen(NameStr(tupdesc->attrs[i]->attname))); if (!nulls || nulls[i]) { pairs[j].val = NULL; pairs[j].vallen = 4; pairs[j].isnull = true; pairs[j].needfree = false; ++j; continue; } /* * Convert the column value to text */ if (column_info->column_type != column_type) { bool typIsVarlena; getTypeOutputInfo(column_type, &column_info->typiofunc, &typIsVarlena); fmgr_info_cxt(column_info->typiofunc, &column_info->proc, fcinfo->flinfo->fn_mcxt); column_info->column_type = column_type; } value = OutputFunctionCall(&column_info->proc, values[i]); pairs[j].val = value; pairs[j].vallen = hstoreCheckValLen(strlen(value)); pairs[j].isnull = false; pairs[j].needfree = false; ++j; } ncolumns = hstoreUniquePairs(pairs, j, &buflen); out = hstorePairs(pairs, ncolumns, buflen); ReleaseTupleDesc(tupdesc); PG_RETURN_POINTER(out); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: BaseBackup(void) { PGresult *res; char *sysidentifier; uint32 latesttli; uint32 starttli; char current_path[MAXPGPATH]; char escaped_label[MAXPGPATH]; int i; char xlogstart[64]; char xlogend[64]; int minServerMajor, maxServerMajor; int serverMajor; /* * Connect in replication mode to the server */ conn = GetConnection(); if (!conn) /* Error message already written in GetConnection() */ exit(1); /* * Check server version. BASE_BACKUP command was introduced in 9.1, so we * can't work with servers older than 9.1. */ minServerMajor = 901; maxServerMajor = PG_VERSION_NUM / 100; serverMajor = PQserverVersion(conn) / 100; if (serverMajor < minServerMajor || serverMajor > maxServerMajor) { const char *serverver = PQparameterStatus(conn, "server_version"); fprintf(stderr, _("%s: incompatible server version %s\n"), progname, serverver ? serverver : "'unknown'"); disconnect_and_exit(1); } /* * If WAL streaming was requested, also check that the server is new * enough for that. */ if (streamwal && !CheckServerVersionForStreaming(conn)) { /* Error message already written in CheckServerVersionForStreaming() */ disconnect_and_exit(1); } /* * Build contents of recovery.conf if requested */ if (writerecoveryconf) GenerateRecoveryConf(conn); /* * Run IDENTIFY_SYSTEM so we can get the timeline */ res = PQexec(conn, "IDENTIFY_SYSTEM"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, _("%s: could not send replication command \"%s\": %s"), progname, "IDENTIFY_SYSTEM", PQerrorMessage(conn)); disconnect_and_exit(1); } if (PQntuples(res) != 1 || PQnfields(res) != 3) { fprintf(stderr, _("%s: could not identify system: got %d rows and %d fields, expected %d rows and %d fields\n"), progname, PQntuples(res), PQnfields(res), 1, 3); disconnect_and_exit(1); } sysidentifier = pg_strdup(PQgetvalue(res, 0, 0)); latesttli = atoi(PQgetvalue(res, 0, 1)); PQclear(res); /* * Start the actual backup */ PQescapeStringConn(conn, escaped_label, label, sizeof(escaped_label), &i); snprintf(current_path, sizeof(current_path), "BASE_BACKUP LABEL '%s' %s %s %s %s", escaped_label, showprogress ? "PROGRESS" : "", includewal && !streamwal ? "WAL" : "", fastcheckpoint ? "FAST" : "", includewal ? "NOWAIT" : ""); if (PQsendQuery(conn, current_path) == 0) { fprintf(stderr, _("%s: could not send replication command \"%s\": %s"), progname, "BASE_BACKUP", PQerrorMessage(conn)); disconnect_and_exit(1); } /* * Get the starting xlog position */ res = PQgetResult(conn); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, _("%s: could not initiate base backup: %s"), progname, PQerrorMessage(conn)); disconnect_and_exit(1); } if (PQntuples(res) != 1) { fprintf(stderr, _("%s: server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields\n"), progname, PQntuples(res), PQnfields(res), 1, 2); disconnect_and_exit(1); } strcpy(xlogstart, PQgetvalue(res, 0, 0)); /* * 9.3 and later sends the TLI of the starting point. With older servers, * assume it's the same as the latest timeline reported by * IDENTIFY_SYSTEM. */ if (PQnfields(res) >= 2) starttli = atoi(PQgetvalue(res, 0, 1)); else starttli = latesttli; PQclear(res); MemSet(xlogend, 0, sizeof(xlogend)); if (verbose && includewal) fprintf(stderr, _("transaction log start point: %s on timeline %u\n"), xlogstart, starttli); /* * Get the header */ res = PQgetResult(conn); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, _("%s: could not get backup header: %s"), progname, PQerrorMessage(conn)); disconnect_and_exit(1); } if (PQntuples(res) < 1) { fprintf(stderr, _("%s: no data returned from server\n"), progname); disconnect_and_exit(1); } /* * Sum up the total size, for progress reporting */ totalsize = totaldone = 0; tablespacecount = PQntuples(res); for (i = 0; i < PQntuples(res); i++) { totalsize += atol(PQgetvalue(res, i, 2)); /* * Verify tablespace directories are empty. Don't bother with the * first once since it can be relocated, and it will be checked before * we do anything anyway. */ if (format == 'p' && !PQgetisnull(res, i, 1)) verify_dir_is_empty_or_create(PQgetvalue(res, i, 1)); } /* * When writing to stdout, require a single tablespace */ if (format == 't' && strcmp(basedir, "-") == 0 && PQntuples(res) > 1) { fprintf(stderr, _("%s: can only write single tablespace to stdout, database has %d\n"), progname, PQntuples(res)); disconnect_and_exit(1); } /* * If we're streaming WAL, start the streaming session before we start * receiving the actual data chunks. */ if (streamwal) { if (verbose) fprintf(stderr, _("%s: starting background WAL receiver\n"), progname); StartLogStreamer(xlogstart, starttli, sysidentifier); } /* * Start receiving chunks */ for (i = 0; i < PQntuples(res); i++) { if (format == 't') ReceiveTarFile(conn, res, i); else ReceiveAndUnpackTarFile(conn, res, i); } /* Loop over all tablespaces */ if (showprogress) { progress_report(PQntuples(res), NULL, true); fprintf(stderr, "\n"); /* Need to move to next line */ } PQclear(res); /* * Get the stop position */ res = PQgetResult(conn); if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, _("%s: could not get transaction log end position from server: %s"), progname, PQerrorMessage(conn)); disconnect_and_exit(1); } if (PQntuples(res) != 1) { fprintf(stderr, _("%s: no transaction log end position returned from server\n"), progname); disconnect_and_exit(1); } strcpy(xlogend, PQgetvalue(res, 0, 0)); if (verbose && includewal) fprintf(stderr, "transaction log end point: %s\n", xlogend); PQclear(res); res = PQgetResult(conn); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, _("%s: final receive failed: %s"), progname, PQerrorMessage(conn)); disconnect_and_exit(1); } if (bgchild > 0) { #ifndef WIN32 int status; int r; #else DWORD status; uint32 hi, lo; #endif if (verbose) fprintf(stderr, _("%s: waiting for background process to finish streaming ...\n"), progname); #ifndef WIN32 if (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend)) { fprintf(stderr, _("%s: could not send command to background pipe: %s\n"), progname, strerror(errno)); disconnect_and_exit(1); } /* Just wait for the background process to exit */ r = waitpid(bgchild, &status, 0); if (r == -1) { fprintf(stderr, _("%s: could not wait for child process: %s\n"), progname, strerror(errno)); disconnect_and_exit(1); } if (r != bgchild) { fprintf(stderr, _("%s: child %d died, expected %d\n"), progname, r, (int) bgchild); disconnect_and_exit(1); } if (!WIFEXITED(status)) { fprintf(stderr, _("%s: child process did not exit normally\n"), progname); disconnect_and_exit(1); } if (WEXITSTATUS(status) != 0) { fprintf(stderr, _("%s: child process exited with error %d\n"), progname, WEXITSTATUS(status)); disconnect_and_exit(1); } /* Exited normally, we're happy! */ #else /* WIN32 */ /* * On Windows, since we are in the same process, we can just store the * value directly in the variable, and then set the flag that says * it's there. */ if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2) { fprintf(stderr, _("%s: could not parse transaction log location \"%s\"\n"), progname, xlogend); disconnect_and_exit(1); } xlogendptr = ((uint64) hi) << 32 | lo; InterlockedIncrement(&has_xlogendptr); /* First wait for the thread to exit */ if (WaitForSingleObjectEx((HANDLE) bgchild, INFINITE, FALSE) != WAIT_OBJECT_0) { _dosmaperr(GetLastError()); fprintf(stderr, _("%s: could not wait for child thread: %s\n"), progname, strerror(errno)); disconnect_and_exit(1); } if (GetExitCodeThread((HANDLE) bgchild, &status) == 0) { _dosmaperr(GetLastError()); fprintf(stderr, _("%s: could not get child thread exit status: %s\n"), progname, strerror(errno)); disconnect_and_exit(1); } if (status != 0) { fprintf(stderr, _("%s: child thread exited with error %u\n"), progname, (unsigned int) status); disconnect_and_exit(1); } /* Exited normally, we're happy */ #endif } /* Free the recovery.conf contents */ destroyPQExpBuffer(recoveryconfcontents); /* * End of copy data. Final result is already checked inside the loop. */ PQclear(res); PQfinish(conn); if (verbose) fprintf(stderr, "%s: base backup completed\n", progname); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent potential overruns of fixed-size buffers. Coverity identified a number of places in which it couldn't prove that a string being copied into a fixed-size buffer would fit. We believe that most, perhaps all of these are in fact safe, or are copying data that is coming from a trusted source so that any overrun is not really a security issue. Nonetheless it seems prudent to forestall any risk by using strlcpy() and similar functions. Fixes by Peter Eisentraut and Jozef Mlich based on Coverity reports. In addition, fix a potential null-pointer-dereference crash in contrib/chkpass. The crypt(3) function is defined to return NULL on failure, but chkpass.c didn't check for that before using the result. The main practical case in which this could be an issue is if libc is configured to refuse to execute unapproved hashing algorithms (e.g., "FIPS mode"). This ideally should've been a separate commit, but since it touches code adjacent to one of the buffer overrun changes, I included it in this commit to avoid last-minute merge issues. This issue was reported by Honza Horak. Security: CVE-2014-0065 for buffer overruns, CVE-2014-0066 for crypt()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum) { char current_path[MAXPGPATH]; char filename[MAXPGPATH]; int current_len_left; int current_padding = 0; bool basetablespace = PQgetisnull(res, rownum, 0); char *copybuf = NULL; FILE *file = NULL; if (basetablespace) strcpy(current_path, basedir); else strcpy(current_path, PQgetvalue(res, rownum, 1)); /* * Get the COPY data */ res = PQgetResult(conn); if (PQresultStatus(res) != PGRES_COPY_OUT) { fprintf(stderr, _("%s: could not get COPY data stream: %s"), progname, PQerrorMessage(conn)); disconnect_and_exit(1); } while (1) { int r; if (copybuf != NULL) { PQfreemem(copybuf); copybuf = NULL; } r = PQgetCopyData(conn, &copybuf, 0); if (r == -1) { /* * End of chunk */ if (file) fclose(file); break; } else if (r == -2) { fprintf(stderr, _("%s: could not read COPY data: %s"), progname, PQerrorMessage(conn)); disconnect_and_exit(1); } if (file == NULL) { int filemode; /* * No current file, so this must be the header for a new file */ if (r != 512) { fprintf(stderr, _("%s: invalid tar block header size: %d\n"), progname, r); disconnect_and_exit(1); } totaldone += 512; if (sscanf(copybuf + 124, "%11o", &current_len_left) != 1) { fprintf(stderr, _("%s: could not parse file size\n"), progname); disconnect_and_exit(1); } /* Set permissions on the file */ if (sscanf(&copybuf[100], "%07o ", &filemode) != 1) { fprintf(stderr, _("%s: could not parse file mode\n"), progname); disconnect_and_exit(1); } /* * All files are padded up to 512 bytes */ current_padding = ((current_len_left + 511) & ~511) - current_len_left; /* * First part of header is zero terminated filename */ snprintf(filename, sizeof(filename), "%s/%s", current_path, copybuf); if (filename[strlen(filename) - 1] == '/') { /* * Ends in a slash means directory or symlink to directory */ if (copybuf[156] == '5') { /* * Directory */ filename[strlen(filename) - 1] = '\0'; /* Remove trailing slash */ if (mkdir(filename, S_IRWXU) != 0) { /* * When streaming WAL, pg_xlog will have been created * by the wal receiver process. Also, when transaction * log directory location was specified, pg_xlog has * already been created as a symbolic link before * starting the actual backup. So just ignore failure * on them. */ if ((!streamwal && (strcmp(xlog_dir, "") == 0)) || strcmp(filename + strlen(filename) - 8, "/pg_xlog") != 0) { fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"), progname, filename, strerror(errno)); disconnect_and_exit(1); } } #ifndef WIN32 if (chmod(filename, (mode_t) filemode)) fprintf(stderr, _("%s: could not set permissions on directory \"%s\": %s\n"), progname, filename, strerror(errno)); #endif } else if (copybuf[156] == '2') { /* * Symbolic link */ filename[strlen(filename) - 1] = '\0'; /* Remove trailing slash */ if (symlink(&copybuf[157], filename) != 0) { fprintf(stderr, _("%s: could not create symbolic link from \"%s\" to \"%s\": %s\n"), progname, filename, &copybuf[157], strerror(errno)); disconnect_and_exit(1); } } else { fprintf(stderr, _("%s: unrecognized link indicator \"%c\"\n"), progname, copybuf[156]); disconnect_and_exit(1); } continue; /* directory or link handled */ } /* * regular file */ file = fopen(filename, "wb"); if (!file) { fprintf(stderr, _("%s: could not create file \"%s\": %s\n"), progname, filename, strerror(errno)); disconnect_and_exit(1); } #ifndef WIN32 if (chmod(filename, (mode_t) filemode)) fprintf(stderr, _("%s: could not set permissions on file \"%s\": %s\n"), progname, filename, strerror(errno)); #endif if (current_len_left == 0) { /* * Done with this file, next one will be a new tar header */ fclose(file); file = NULL; continue; } } /* new file */ else { /* * Continuing blocks in existing file */ if (current_len_left == 0 && r == current_padding) { /* * Received the padding block for this file, ignore it and * close the file, then move on to the next tar header. */ fclose(file); file = NULL; totaldone += r; continue; } if (fwrite(copybuf, r, 1, file) != 1) { fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"), progname, filename, strerror(errno)); disconnect_and_exit(1); } totaldone += r; progress_report(rownum, filename, false); current_len_left -= r; if (current_len_left == 0 && current_padding == 0) { /* * Received the last block, and there is no padding to be * expected. Close the file and move on to the next tar * header. */ fclose(file); file = NULL; continue; } } /* continuing data in existing file */ } /* loop over all data blocks */ progress_report(rownum, filename, true); if (file != NULL) { fprintf(stderr, _("%s: COPY stream ended before last file was finished\n"), progname); disconnect_and_exit(1); } if (copybuf != NULL) PQfreemem(copybuf); if (basetablespace && writerecoveryconf) WriteRecoveryConf(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent potential overruns of fixed-size buffers. Coverity identified a number of places in which it couldn't prove that a string being copied into a fixed-size buffer would fit. We believe that most, perhaps all of these are in fact safe, or are copying data that is coming from a trusted source so that any overrun is not really a security issue. Nonetheless it seems prudent to forestall any risk by using strlcpy() and similar functions. Fixes by Peter Eisentraut and Jozef Mlich based on Coverity reports. In addition, fix a potential null-pointer-dereference crash in contrib/chkpass. The crypt(3) function is defined to return NULL on failure, but chkpass.c didn't check for that before using the result. The main practical case in which this could be an issue is if libc is configured to refuse to execute unapproved hashing algorithms (e.g., "FIPS mode"). This ideally should've been a separate commit, but since it touches code adjacent to one of the buffer overrun changes, I included it in this commit to avoid last-minute merge issues. This issue was reported by Honza Horak. Security: CVE-2014-0065 for buffer overruns, CVE-2014-0066 for crypt()'</s>
<s>[INST] Given the following code containing errors, provide 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_scsi_load_request(QEMUFile *f, SCSIRequest *sreq) { SCSIBus *bus = sreq->bus; VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus); VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s); VirtIOSCSIReq *req; uint32_t n; req = g_malloc(sizeof(*req)); qemu_get_be32s(f, &n); assert(n < vs->conf.num_queues); qemu_get_buffer(f, (unsigned char *)&req->elem, sizeof(req->elem)); virtio_scsi_parse_req(s, vs->cmd_vqs[n], req); scsi_req_ref(sreq); req->sreq = sreq; if (req->sreq->cmd.mode != SCSI_XFER_NONE) { int req_mode = (req->elem.in_num > 1 ? SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV); assert(req->sreq->cmd.mode == req_mode); } return req; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'virtio-scsi: fix buffer overrun on invalid state load CVE-2013-4542 hw/scsi/scsi-bus.c invokes load_request. virtio_scsi_load_request does: qemu_get_buffer(f, (unsigned char *)&req->elem, sizeof(req->elem)); this probably can make elem invalid, for example, make in_num or out_num huge, then: virtio_scsi_parse_req(s, vs->cmd_vqs[n], req); will do: if (req->elem.out_num > 1) { qemu_sgl_init_external(req, &req->elem.out_sg[1], &req->elem.out_addr[1], req->elem.out_num - 1); } else { qemu_sgl_init_external(req, &req->elem.in_sg[1], &req->elem.in_addr[1], req->elem.in_num - 1); } and this will access out of array bounds. Note: this adds security checks within assert calls since SCSIBusInfo's load_request cannot fail. For now simply disable builds with NDEBUG - there seems to be little value in supporting these. Cc: Andreas Färber <afaerber@suse.de> Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Signed-off-by: Juan Quintela <quintela@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode) { if (file->f_flags & O_DSYNC) return 0; if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE)) return 1; if (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL || (inode->i_flock->fl_start == 0 && inode->i_flock->fl_end == OFFSET_MAX && inode->i_flock->fl_type != F_RDLCK))) return 1; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-200'], 'message': 'nfs: always make sure page is up-to-date before extending a write to cover the entire page We should always make sure the cached page is up-to-date when we're determining whether we can extend a write to cover the full page -- even if we've received a write delegation from the server. Commit c7559663 added logic to skip this check if we have a write delegation, which can lead to data corruption such as the following scenario if client B receives a write delegation from the NFS server: Client A: # echo 123456789 > /mnt/file Client B: # echo abcdefghi >> /mnt/file # cat /mnt/file 0�D0�abcdefghi Just because we hold a write delegation doesn't mean that we've read in the entire page contents. Cc: <stable@vger.kernel.org> # v3.11+ Signed-off-by: Scott Mayhew <smayhew@redhat.com> Signed-off-by: Trond Myklebust <trond.myklebust@primarydata.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: private int mget(struct magic_set *ms, const unsigned char *s, struct magic *m, size_t nbytes, size_t o, unsigned int cont_level, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t soffset, offset = ms->offset; uint32_t count = m->str_range; int rv, oneed_separator, in_type; char *sbuf, *rbuf; union VALUETYPE *p = &ms->ms_value; struct mlist ml; if (recursion_level >= 20) { file_error(ms, 0, "recursion nesting exceeded"); return -1; } if (mcopy(ms, p, m->type, m->flag & INDIR, s, (uint32_t)(offset + o), (uint32_t)nbytes, count) == -1) return -1; if ((ms->flags & MAGIC_DEBUG) != 0) { fprintf(stderr, "mget(type=%d, flag=%x, offset=%u, o=%zu, " "nbytes=%zu, count=%u)\n", m->type, m->flag, offset, o, nbytes, count); mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } if (m->flag & INDIR) { int off = m->in_offset; if (m->in_op & FILE_OPINDIRECT) { const union VALUETYPE *q = CAST(const union VALUETYPE *, ((const void *)(s + offset + off))); switch (cvt_flip(m->in_type, flip)) { case FILE_BYTE: off = q->b; break; case FILE_SHORT: off = q->h; break; case FILE_BESHORT: off = (short)((q->hs[0]<<8)|(q->hs[1])); break; case FILE_LESHORT: off = (short)((q->hs[1]<<8)|(q->hs[0])); break; case FILE_LONG: off = q->l; break; case FILE_BELONG: case FILE_BEID3: off = (int32_t)((q->hl[0]<<24)|(q->hl[1]<<16)| (q->hl[2]<<8)|(q->hl[3])); break; case FILE_LEID3: case FILE_LELONG: off = (int32_t)((q->hl[3]<<24)|(q->hl[2]<<16)| (q->hl[1]<<8)|(q->hl[0])); break; case FILE_MELONG: off = (int32_t)((q->hl[1]<<24)|(q->hl[0]<<16)| (q->hl[3]<<8)|(q->hl[2])); break; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect offs=%u\n", off); } switch (in_type = cvt_flip(m->in_type, flip)) { case FILE_BYTE: if (nbytes < offset || nbytes < (offset + 1)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->b & off; break; case FILE_OPOR: offset = p->b | off; break; case FILE_OPXOR: offset = p->b ^ off; break; case FILE_OPADD: offset = p->b + off; break; case FILE_OPMINUS: offset = p->b - off; break; case FILE_OPMULTIPLY: offset = p->b * off; break; case FILE_OPDIVIDE: offset = p->b / off; break; case FILE_OPMODULO: offset = p->b % off; break; } } else offset = p->b; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BESHORT: if (nbytes < offset || nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (short)((p->hs[0]<<8)| (p->hs[1])) & off; break; case FILE_OPOR: offset = (short)((p->hs[0]<<8)| (p->hs[1])) | off; break; case FILE_OPXOR: offset = (short)((p->hs[0]<<8)| (p->hs[1])) ^ off; break; case FILE_OPADD: offset = (short)((p->hs[0]<<8)| (p->hs[1])) + off; break; case FILE_OPMINUS: offset = (short)((p->hs[0]<<8)| (p->hs[1])) - off; break; case FILE_OPMULTIPLY: offset = (short)((p->hs[0]<<8)| (p->hs[1])) * off; break; case FILE_OPDIVIDE: offset = (short)((p->hs[0]<<8)| (p->hs[1])) / off; break; case FILE_OPMODULO: offset = (short)((p->hs[0]<<8)| (p->hs[1])) % off; break; } } else offset = (short)((p->hs[0]<<8)| (p->hs[1])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LESHORT: if (nbytes < offset || nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (short)((p->hs[1]<<8)| (p->hs[0])) & off; break; case FILE_OPOR: offset = (short)((p->hs[1]<<8)| (p->hs[0])) | off; break; case FILE_OPXOR: offset = (short)((p->hs[1]<<8)| (p->hs[0])) ^ off; break; case FILE_OPADD: offset = (short)((p->hs[1]<<8)| (p->hs[0])) + off; break; case FILE_OPMINUS: offset = (short)((p->hs[1]<<8)| (p->hs[0])) - off; break; case FILE_OPMULTIPLY: offset = (short)((p->hs[1]<<8)| (p->hs[0])) * off; break; case FILE_OPDIVIDE: offset = (short)((p->hs[1]<<8)| (p->hs[0])) / off; break; case FILE_OPMODULO: offset = (short)((p->hs[1]<<8)| (p->hs[0])) % off; break; } } else offset = (short)((p->hs[1]<<8)| (p->hs[0])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_SHORT: if (nbytes < offset || nbytes < (offset + 2)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->h & off; break; case FILE_OPOR: offset = p->h | off; break; case FILE_OPXOR: offset = p->h ^ off; break; case FILE_OPADD: offset = p->h + off; break; case FILE_OPMINUS: offset = p->h - off; break; case FILE_OPMULTIPLY: offset = p->h * off; break; case FILE_OPDIVIDE: offset = p->h / off; break; case FILE_OPMODULO: offset = p->h % off; break; } } else offset = p->h; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_BELONG: case FILE_BEID3: if (nbytes < offset || nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])) % off; break; } } else offset = (int32_t)((p->hl[0]<<24)| (p->hl[1]<<16)| (p->hl[2]<<8)| (p->hl[3])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LELONG: case FILE_LEID3: if (nbytes < offset || nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])) % off; break; } } else offset = (int32_t)((p->hl[3]<<24)| (p->hl[2]<<16)| (p->hl[1]<<8)| (p->hl[0])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_MELONG: if (nbytes < offset || nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) & off; break; case FILE_OPOR: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) | off; break; case FILE_OPXOR: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) ^ off; break; case FILE_OPADD: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) + off; break; case FILE_OPMINUS: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) - off; break; case FILE_OPMULTIPLY: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) * off; break; case FILE_OPDIVIDE: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) / off; break; case FILE_OPMODULO: offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])) % off; break; } } else offset = (int32_t)((p->hl[1]<<24)| (p->hl[0]<<16)| (p->hl[3]<<8)| (p->hl[2])); if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; case FILE_LONG: if (nbytes < offset || nbytes < (offset + 4)) return 0; if (off) { switch (m->in_op & FILE_OPS_MASK) { case FILE_OPAND: offset = p->l & off; break; case FILE_OPOR: offset = p->l | off; break; case FILE_OPXOR: offset = p->l ^ off; break; case FILE_OPADD: offset = p->l + off; break; case FILE_OPMINUS: offset = p->l - off; break; case FILE_OPMULTIPLY: offset = p->l * off; break; case FILE_OPDIVIDE: offset = p->l / off; break; case FILE_OPMODULO: offset = p->l % off; break; } } else offset = p->l; if (m->in_op & FILE_OPINVERSE) offset = ~offset; break; default: break; } switch (in_type) { case FILE_LEID3: case FILE_BEID3: offset = ((((offset >> 0) & 0x7f) << 0) | (((offset >> 8) & 0x7f) << 7) | (((offset >> 16) & 0x7f) << 14) | (((offset >> 24) & 0x7f) << 21)) + 10; break; default: break; } if (m->flag & INDIROFFADD) { offset += ms->c.li[cont_level-1].off; if (offset == 0) { if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect *zero* offset\n"); return 0; } if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect +offs=%u\n", offset); } if (mcopy(ms, p, m->type, 0, s, offset, nbytes, count) == -1) return -1; ms->offset = offset; if ((ms->flags & MAGIC_DEBUG) != 0) { mdebug(offset, (char *)(void *)p, sizeof(union VALUETYPE)); #ifndef COMPILE_ONLY file_mdump(m); #endif } } /* Verify we have enough data to match magic type */ switch (m->type) { case FILE_BYTE: if (nbytes < (offset + 1)) /* should alway be true */ return 0; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: if (nbytes < (offset + 2)) return 0; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: if (nbytes < (offset + 4)) return 0; break; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: if (nbytes < (offset + 8)) return 0; break; case FILE_STRING: case FILE_PSTRING: case FILE_SEARCH: if (nbytes < (offset + m->vallen)) return 0; break; case FILE_REGEX: if (nbytes < offset) return 0; break; case FILE_INDIRECT: if (nbytes < offset) return 0; sbuf = ms->o.buf; soffset = ms->offset; ms->o.buf = NULL; ms->offset = 0; rv = file_softmagic(ms, s + offset, nbytes - offset, BINTEST, text); if ((ms->flags & MAGIC_DEBUG) != 0) fprintf(stderr, "indirect @offs=%u[%d]\n", offset, rv); rbuf = ms->o.buf; ms->o.buf = sbuf; ms->offset = soffset; if (rv == 1) { if ((ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0 && file_printf(ms, F(m->desc, "%u"), offset) == -1) return -1; if (file_printf(ms, "%s", rbuf) == -1) return -1; free(rbuf); } return rv; case FILE_USE: if (nbytes < offset) return 0; sbuf = m->value.s; if (*sbuf == '^') { sbuf++; flip = !flip; } if (file_magicfind(ms, sbuf, &ml) == -1) { file_error(ms, 0, "cannot find entry `%s'", sbuf); return -1; } oneed_separator = *need_separator; if (m->flag & NOSPACE) *need_separator = 0; rv = match(ms, ml.magic, ml.nmagic, s, nbytes, offset + o, mode, text, flip, recursion_level, printed_something, need_separator, returnval); if (rv != 1) *need_separator = oneed_separator; return rv; case FILE_NAME: if (file_printf(ms, "%s", m->desc) == -1) return -1; return 1; case FILE_DEFAULT: /* nothing to check */ case FILE_CLEAR: default: break; } if (!mconvert(ms, m, flip)) return 0; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'PR/313: Aaron Reffett: Check properly for exceeding the offset.'</s>
<s>[INST] Given the following code containing errors, provide 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 qcow2_alloc_clusters_at(BlockDriverState *bs, uint64_t offset, int nb_clusters) { BDRVQcowState *s = bs->opaque; uint64_t cluster_index; uint64_t old_free_cluster_index; uint64_t i; int refcount, ret; assert(nb_clusters >= 0); if (nb_clusters == 0) { return 0; } /* Check how many clusters there are free */ cluster_index = offset >> s->cluster_bits; for(i = 0; i < nb_clusters; i++) { refcount = get_refcount(bs, cluster_index++); if (refcount < 0) { return refcount; } else if (refcount != 0) { break; } } /* And then allocate them */ old_free_cluster_index = s->free_cluster_index; s->free_cluster_index = cluster_index + i; ret = update_refcount(bs, offset, i << s->cluster_bits, 1, QCOW2_DISCARD_NEVER); if (ret < 0) { return ret; } s->free_cluster_index = old_free_cluster_index; return i; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'qcow2: Don't rely on free_cluster_index in alloc_refcount_block() (CVE-2014-0147) free_cluster_index is only correct if update_refcount() was called from an allocation function, and even there it's brittle because it's used to protect unfinished allocations which still have a refcount of 0 - if it moves in the wrong place, the unfinished allocation can be corrupted. So not using it any more seems to be a good idea. Instead, use the first requested cluster to do the calculations. Return -EAGAIN if unfinished allocations could become invalid and let the caller restart its search for some free clusters. The context of creating a snapsnot is one situation where update_refcount() is called outside of a cluster allocation. For this case, the change fixes a buffer overflow if a cluster is referenced in an L2 table that cannot be represented by an existing refcount block. (new_table[refcount_table_index] was out of bounds) [Bump the qemu-iotests 026 refblock_alloc.write leak count from 10 to 11. --Stefan] Signed-off-by: Kevin Wolf <kwolf@redhat.com> Reviewed-by: Max Reitz <mreitz@redhat.com> Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: nfqnl_build_packet_message(struct net *net, struct nfqnl_instance *queue, struct nf_queue_entry *entry, __be32 **packet_id_ptr) { size_t size; size_t data_len = 0, cap_len = 0; unsigned int hlen = 0; struct sk_buff *skb; struct nlattr *nla; struct nfqnl_msg_packet_hdr *pmsg; struct nlmsghdr *nlh; struct nfgenmsg *nfmsg; struct sk_buff *entskb = entry->skb; struct net_device *indev; struct net_device *outdev; struct nf_conn *ct = NULL; enum ip_conntrack_info uninitialized_var(ctinfo); bool csum_verify; size = nlmsg_total_size(sizeof(struct nfgenmsg)) + nla_total_size(sizeof(struct nfqnl_msg_packet_hdr)) + nla_total_size(sizeof(u_int32_t)) /* ifindex */ + nla_total_size(sizeof(u_int32_t)) /* ifindex */ #ifdef CONFIG_BRIDGE_NETFILTER + nla_total_size(sizeof(u_int32_t)) /* ifindex */ + nla_total_size(sizeof(u_int32_t)) /* ifindex */ #endif + nla_total_size(sizeof(u_int32_t)) /* mark */ + nla_total_size(sizeof(struct nfqnl_msg_packet_hw)) + nla_total_size(sizeof(u_int32_t)) /* skbinfo */ + nla_total_size(sizeof(u_int32_t)); /* cap_len */ if (entskb->tstamp.tv64) size += nla_total_size(sizeof(struct nfqnl_msg_packet_timestamp)); if (entry->hook <= NF_INET_FORWARD || (entry->hook == NF_INET_POST_ROUTING && entskb->sk == NULL)) csum_verify = !skb_csum_unnecessary(entskb); else csum_verify = false; outdev = entry->outdev; switch ((enum nfqnl_config_mode)ACCESS_ONCE(queue->copy_mode)) { case NFQNL_COPY_META: case NFQNL_COPY_NONE: break; case NFQNL_COPY_PACKET: if (!(queue->flags & NFQA_CFG_F_GSO) && entskb->ip_summed == CHECKSUM_PARTIAL && skb_checksum_help(entskb)) return NULL; data_len = ACCESS_ONCE(queue->copy_range); if (data_len > entskb->len) data_len = entskb->len; hlen = skb_zerocopy_headlen(entskb); hlen = min_t(unsigned int, hlen, data_len); size += sizeof(struct nlattr) + hlen; cap_len = entskb->len; break; } if (queue->flags & NFQA_CFG_F_CONNTRACK) ct = nfqnl_ct_get(entskb, &size, &ctinfo); if (queue->flags & NFQA_CFG_F_UID_GID) { size += (nla_total_size(sizeof(u_int32_t)) /* uid */ + nla_total_size(sizeof(u_int32_t))); /* gid */ } skb = nfnetlink_alloc_skb(net, size, queue->peer_portid, GFP_ATOMIC); if (!skb) return NULL; nlh = nlmsg_put(skb, 0, 0, NFNL_SUBSYS_QUEUE << 8 | NFQNL_MSG_PACKET, sizeof(struct nfgenmsg), 0); if (!nlh) { kfree_skb(skb); return NULL; } nfmsg = nlmsg_data(nlh); nfmsg->nfgen_family = entry->pf; nfmsg->version = NFNETLINK_V0; nfmsg->res_id = htons(queue->queue_num); nla = __nla_reserve(skb, NFQA_PACKET_HDR, sizeof(*pmsg)); pmsg = nla_data(nla); pmsg->hw_protocol = entskb->protocol; pmsg->hook = entry->hook; *packet_id_ptr = &pmsg->packet_id; indev = entry->indev; if (indev) { #ifndef CONFIG_BRIDGE_NETFILTER if (nla_put_be32(skb, NFQA_IFINDEX_INDEV, htonl(indev->ifindex))) goto nla_put_failure; #else if (entry->pf == PF_BRIDGE) { /* Case 1: indev is physical input device, we need to * look for bridge group (when called from * netfilter_bridge) */ if (nla_put_be32(skb, NFQA_IFINDEX_PHYSINDEV, htonl(indev->ifindex)) || /* this is the bridge group "brX" */ /* rcu_read_lock()ed by __nf_queue */ nla_put_be32(skb, NFQA_IFINDEX_INDEV, htonl(br_port_get_rcu(indev)->br->dev->ifindex))) goto nla_put_failure; } else { /* Case 2: indev is bridge group, we need to look for * physical device (when called from ipv4) */ if (nla_put_be32(skb, NFQA_IFINDEX_INDEV, htonl(indev->ifindex))) goto nla_put_failure; if (entskb->nf_bridge && entskb->nf_bridge->physindev && nla_put_be32(skb, NFQA_IFINDEX_PHYSINDEV, htonl(entskb->nf_bridge->physindev->ifindex))) goto nla_put_failure; } #endif } if (outdev) { #ifndef CONFIG_BRIDGE_NETFILTER if (nla_put_be32(skb, NFQA_IFINDEX_OUTDEV, htonl(outdev->ifindex))) goto nla_put_failure; #else if (entry->pf == PF_BRIDGE) { /* Case 1: outdev is physical output device, we need to * look for bridge group (when called from * netfilter_bridge) */ if (nla_put_be32(skb, NFQA_IFINDEX_PHYSOUTDEV, htonl(outdev->ifindex)) || /* this is the bridge group "brX" */ /* rcu_read_lock()ed by __nf_queue */ nla_put_be32(skb, NFQA_IFINDEX_OUTDEV, htonl(br_port_get_rcu(outdev)->br->dev->ifindex))) goto nla_put_failure; } else { /* Case 2: outdev is bridge group, we need to look for * physical output device (when called from ipv4) */ if (nla_put_be32(skb, NFQA_IFINDEX_OUTDEV, htonl(outdev->ifindex))) goto nla_put_failure; if (entskb->nf_bridge && entskb->nf_bridge->physoutdev && nla_put_be32(skb, NFQA_IFINDEX_PHYSOUTDEV, htonl(entskb->nf_bridge->physoutdev->ifindex))) goto nla_put_failure; } #endif } if (entskb->mark && nla_put_be32(skb, NFQA_MARK, htonl(entskb->mark))) goto nla_put_failure; if (indev && entskb->dev && entskb->mac_header != entskb->network_header) { struct nfqnl_msg_packet_hw phw; int len; memset(&phw, 0, sizeof(phw)); len = dev_parse_header(entskb, phw.hw_addr); if (len) { phw.hw_addrlen = htons(len); if (nla_put(skb, NFQA_HWADDR, sizeof(phw), &phw)) goto nla_put_failure; } } if (entskb->tstamp.tv64) { struct nfqnl_msg_packet_timestamp ts; struct timeval tv = ktime_to_timeval(entskb->tstamp); ts.sec = cpu_to_be64(tv.tv_sec); ts.usec = cpu_to_be64(tv.tv_usec); if (nla_put(skb, NFQA_TIMESTAMP, sizeof(ts), &ts)) goto nla_put_failure; } if ((queue->flags & NFQA_CFG_F_UID_GID) && entskb->sk && nfqnl_put_sk_uidgid(skb, entskb->sk) < 0) goto nla_put_failure; if (ct && nfqnl_ct_put(skb, ct, ctinfo) < 0) goto nla_put_failure; if (cap_len > data_len && nla_put_be32(skb, NFQA_CAP_LEN, htonl(cap_len))) goto nla_put_failure; if (nfqnl_put_packet_info(skb, entskb, csum_verify)) goto nla_put_failure; if (data_len) { struct nlattr *nla; if (skb_tailroom(skb) < sizeof(*nla) + hlen) goto nla_put_failure; nla = (struct nlattr *)skb_put(skb, sizeof(*nla)); nla->nla_type = NFQA_PAYLOAD; nla->nla_len = nla_attr_size(data_len); skb_zerocopy(skb, entskb, data_len, hlen); } nlh->nlmsg_len = skb->len; return skb; nla_put_failure: kfree_skb(skb); net_err_ratelimited("nf_queue: error creating packet message\n"); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'core, nfqueue, openvswitch: Orphan frags in skb_zerocopy and handle errors skb_zerocopy can copy elements of the frags array between skbs, but it doesn't orphan them. Also, it doesn't handle errors, so this patch takes care of that as well, and modify the callers accordingly. skb_tx_error() is also added to the callers so they will signal the failed delivery towards the creator of the skb. Signed-off-by: Zoltan Kiss <zoltan.kiss@citrix.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: cert_hostcheck(const char *match_pattern, const char *hostname) { if(!match_pattern || !*match_pattern || !hostname || !*hostname) /* sanity check */ return 0; if(Curl_raw_equal(hostname, match_pattern)) /* trivial case */ return 1; if(hostmatch(hostname,match_pattern) == HOST_MATCH) return 1; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'use hostmatch function from latest curl (addresses CVE-2014-0139)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static size_t curl_read_cb(void *ptr, size_t size, size_t nmemb, void *opaque) { CURLState *s = ((CURLState*)opaque); size_t realsize = size * nmemb; int i; DPRINTF("CURL: Just reading %zd bytes\n", realsize); if (!s || !s->orig_buf) goto read_end; memcpy(s->orig_buf + s->buf_off, ptr, realsize); s->buf_off += realsize; for(i=0; i<CURL_NUM_ACB; i++) { CURLAIOCB *acb = s->acb[i]; if (!acb) continue; if ((s->buf_off >= acb->end)) { qemu_iovec_from_buf(acb->qiov, 0, s->orig_buf + acb->start, acb->end - acb->start); acb->common.cb(acb->common.opaque, 0); qemu_aio_release(acb); s->acb[i] = NULL; } } read_end: return realsize; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'curl: check data size before memcpy to local buffer. (CVE-2014-0144) curl_read_cb is callback function for libcurl when data arrives. The data size passed in here is not guaranteed to be within the range of request we submitted, so we may overflow the guest IO buffer. Check the real size we have before memcpy to buffer to avoid overflow. Signed-off-by: Fam Zheng <famz@redhat.com> Reviewed-by: Stefan Hajnoczi <stefanha@redhat.com> Signed-off-by: Kevin Wolf <kwolf@redhat.com> Reviewed-by: Max Reitz <mreitz@redhat.com> Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static unsigned xenvif_tx_build_gops(struct xenvif *vif, int budget) { struct gnttab_map_grant_ref *gop = vif->tx_map_ops, *request_gop; struct sk_buff *skb; int ret; while (skb_queue_len(&vif->tx_queue) < budget) { struct xen_netif_tx_request txreq; struct xen_netif_tx_request txfrags[XEN_NETBK_LEGACY_SLOTS_MAX]; struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1]; u16 pending_idx; RING_IDX idx; int work_to_do; unsigned int data_len; pending_ring_idx_t index; if (vif->tx.sring->req_prod - vif->tx.req_cons > XEN_NETIF_TX_RING_SIZE) { netdev_err(vif->dev, "Impossible number of requests. " "req_prod %d, req_cons %d, size %ld\n", vif->tx.sring->req_prod, vif->tx.req_cons, XEN_NETIF_TX_RING_SIZE); xenvif_fatal_tx_err(vif); continue; } work_to_do = RING_HAS_UNCONSUMED_REQUESTS(&vif->tx); if (!work_to_do) break; idx = vif->tx.req_cons; rmb(); /* Ensure that we see the request before we copy it. */ memcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq)); /* Credit-based scheduling. */ if (txreq.size > vif->remaining_credit && tx_credit_exceeded(vif, txreq.size)) break; vif->remaining_credit -= txreq.size; work_to_do--; vif->tx.req_cons = ++idx; memset(extras, 0, sizeof(extras)); if (txreq.flags & XEN_NETTXF_extra_info) { work_to_do = xenvif_get_extras(vif, extras, work_to_do); idx = vif->tx.req_cons; if (unlikely(work_to_do < 0)) break; } ret = xenvif_count_requests(vif, &txreq, txfrags, work_to_do); if (unlikely(ret < 0)) break; idx += ret; if (unlikely(txreq.size < ETH_HLEN)) { netdev_dbg(vif->dev, "Bad packet size: %d\n", txreq.size); xenvif_tx_err(vif, &txreq, idx); break; } /* No crossing a page as the payload mustn't fragment. */ if (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) { netdev_err(vif->dev, "txreq.offset: %x, size: %u, end: %lu\n", txreq.offset, txreq.size, (txreq.offset&~PAGE_MASK) + txreq.size); xenvif_fatal_tx_err(vif); break; } index = pending_index(vif->pending_cons); pending_idx = vif->pending_ring[index]; data_len = (txreq.size > PKT_PROT_LEN && ret < XEN_NETBK_LEGACY_SLOTS_MAX) ? PKT_PROT_LEN : txreq.size; skb = xenvif_alloc_skb(data_len); if (unlikely(skb == NULL)) { netdev_dbg(vif->dev, "Can't allocate a skb in start_xmit.\n"); xenvif_tx_err(vif, &txreq, idx); break; } if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) { struct xen_netif_extra_info *gso; gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1]; if (xenvif_set_skb_gso(vif, skb, gso)) { /* Failure in xenvif_set_skb_gso is fatal. */ kfree_skb(skb); break; } } xenvif_tx_create_gop(vif, pending_idx, &txreq, gop); gop++; XENVIF_TX_CB(skb)->pending_idx = pending_idx; __skb_put(skb, data_len); skb_shinfo(skb)->nr_frags = ret; if (data_len < txreq.size) { skb_shinfo(skb)->nr_frags++; frag_set_pending_idx(&skb_shinfo(skb)->frags[0], pending_idx); } else { frag_set_pending_idx(&skb_shinfo(skb)->frags[0], INVALID_PENDING_IDX); } vif->pending_cons++; request_gop = xenvif_get_requests(vif, skb, txfrags, gop); if (request_gop == NULL) { kfree_skb(skb); xenvif_tx_err(vif, &txreq, idx); break; } gop = request_gop; __skb_queue_tail(&vif->tx_queue, skb); vif->tx.req_cons = idx; if ((gop-vif->tx_map_ops) >= ARRAY_SIZE(vif->tx_map_ops)) break; } return gop - vif->tx_map_ops; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'xen-netback: disable rogue vif in kthread context When netback discovers frontend is sending malformed packet it will disables the interface which serves that frontend. However disabling a network interface involving taking a mutex which cannot be done in softirq context, so we need to defer this process to kthread context. This patch does the following: 1. introduce a flag to indicate the interface is disabled. 2. check that flag in TX path, don't do any work if it's true. 3. check that flag in RX path, turn off that interface if it's true. The reason to disable it in RX path is because RX uses kthread. After this change the behavior of netback is still consistent -- it won't do any TX work for a rogue frontend, and the interface will be eventually turned off. Also change a "continue" to "break" after xenvif_fatal_tx_err, as it doesn't make sense to continue processing packets if frontend is rogue. This is a fix for XSA-90. Reported-by: Török Edwin <edwin@etorok.net> Signed-off-by: Wei Liu <wei.liu2@citrix.com> Cc: Ian Campbell <ian.campbell@citrix.com> Reviewed-by: David Vrabel <david.vrabel@citrix.com> Acked-by: Ian Campbell <ian.campbell@citrix.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ath_tx_aggr_sleep(struct ieee80211_sta *sta, struct ath_softc *sc, struct ath_node *an) { struct ath_atx_tid *tid; struct ath_atx_ac *ac; struct ath_txq *txq; bool buffered; int tidno; for (tidno = 0, tid = &an->tid[tidno]; tidno < IEEE80211_NUM_TIDS; tidno++, tid++) { if (!tid->sched) continue; ac = tid->ac; txq = ac->txq; ath_txq_lock(sc, txq); buffered = ath_tid_has_buffered(tid); tid->sched = false; list_del(&tid->list); if (ac->sched) { ac->sched = false; list_del(&ac->list); } ath_txq_unlock(sc, txq); ieee80211_sta_set_buffered(sta, tidno, buffered); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-241'], 'message': 'ath9k: protect tid->sched check We check tid->sched without a lock taken on ath_tx_aggr_sleep(). That is race condition which can result of doing list_del(&tid->list) twice (second time with poisoned list node) and cause crash like shown below: [424271.637220] BUG: unable to handle kernel paging request at 00100104 [424271.637328] IP: [<f90fc072>] ath_tx_aggr_sleep+0x62/0xe0 [ath9k] ... [424271.639953] Call Trace: [424271.639998] [<f90f6900>] ? ath9k_get_survey+0x110/0x110 [ath9k] [424271.640083] [<f90f6942>] ath9k_sta_notify+0x42/0x50 [ath9k] [424271.640177] [<f809cfef>] sta_ps_start+0x8f/0x1c0 [mac80211] [424271.640258] [<c10f730e>] ? free_compound_page+0x2e/0x40 [424271.640346] [<f809e915>] ieee80211_rx_handlers+0x9d5/0x2340 [mac80211] [424271.640437] [<c112f048>] ? kmem_cache_free+0x1d8/0x1f0 [424271.640510] [<c1345a84>] ? kfree_skbmem+0x34/0x90 [424271.640578] [<c10fc23c>] ? put_page+0x2c/0x40 [424271.640640] [<c1345a84>] ? kfree_skbmem+0x34/0x90 [424271.640706] [<c1345a84>] ? kfree_skbmem+0x34/0x90 [424271.640787] [<f809dde3>] ? ieee80211_rx_handlers_result+0x73/0x1d0 [mac80211] [424271.640897] [<f80a07a0>] ieee80211_prepare_and_rx_handle+0x520/0xad0 [mac80211] [424271.641009] [<f809e22d>] ? ieee80211_rx_handlers+0x2ed/0x2340 [mac80211] [424271.641104] [<c13846ce>] ? ip_output+0x7e/0xd0 [424271.641182] [<f80a1057>] ieee80211_rx+0x307/0x7c0 [mac80211] [424271.641266] [<f90fa6ee>] ath_rx_tasklet+0x88e/0xf70 [ath9k] [424271.641358] [<f80a0f2c>] ? ieee80211_rx+0x1dc/0x7c0 [mac80211] [424271.641445] [<f90f82db>] ath9k_tasklet+0xcb/0x130 [ath9k] Bug report: https://bugzilla.kernel.org/show_bug.cgi?id=70551 Reported-and-tested-by: Max Sydorenko <maxim.stargazer@gmail.com> Cc: stable@vger.kernel.org Signed-off-by: Stanislaw Gruszka <sgruszka@redhat.com> Signed-off-by: John W. Linville <linville@tuxdriver.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t n_tty_write(struct tty_struct *tty, struct file *file, const unsigned char *buf, size_t nr) { const unsigned char *b = buf; DECLARE_WAITQUEUE(wait, current); int c; ssize_t retval = 0; /* Job control check -- must be done at start (POSIX.1 7.1.1.4). */ if (L_TOSTOP(tty) && file->f_op->write != redirected_tty_write) { retval = tty_check_change(tty); if (retval) return retval; } down_read(&tty->termios_rwsem); /* Write out any echoed characters that are still pending */ process_echoes(tty); add_wait_queue(&tty->write_wait, &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (signal_pending(current)) { retval = -ERESTARTSYS; break; } if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) { retval = -EIO; break; } if (O_OPOST(tty)) { while (nr > 0) { ssize_t num = process_output_block(tty, b, nr); if (num < 0) { if (num == -EAGAIN) break; retval = num; goto break_out; } b += num; nr -= num; if (nr == 0) break; c = *b; if (process_output(c, tty) < 0) break; b++; nr--; } if (tty->ops->flush_chars) tty->ops->flush_chars(tty); } else { while (nr > 0) { c = tty->ops->write(tty, b, nr); if (c < 0) { retval = c; goto break_out; } if (!c) break; b += c; nr -= c; } } if (!nr) break; if (file->f_flags & O_NONBLOCK) { retval = -EAGAIN; break; } up_read(&tty->termios_rwsem); schedule(); down_read(&tty->termios_rwsem); } break_out: __set_current_state(TASK_RUNNING); remove_wait_queue(&tty->write_wait, &wait); if (b - buf != nr && tty->fasync) set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags); up_read(&tty->termios_rwsem); return (b - buf) ? b - buf : retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'n_tty: Fix n_tty_write crash when echoing in raw mode The tty atomic_write_lock does not provide an exclusion guarantee for the tty driver if the termios settings are LECHO & !OPOST. And since it is unexpected and not allowed to call TTY buffer helpers like tty_insert_flip_string concurrently, this may lead to crashes when concurrect writers call pty_write. In that case the following two writers: * the ECHOing from a workqueue and * pty_write from the process race and can overflow the corresponding TTY buffer like follows. If we look into tty_insert_flip_string_fixed_flag, there is: int space = __tty_buffer_request_room(port, goal, flags); struct tty_buffer *tb = port->buf.tail; ... memcpy(char_buf_ptr(tb, tb->used), chars, space); ... tb->used += space; so the race of the two can result in something like this: A B __tty_buffer_request_room __tty_buffer_request_room memcpy(buf(tb->used), ...) tb->used += space; memcpy(buf(tb->used), ...) ->BOOM B's memcpy is past the tty_buffer due to the previous A's tb->used increment. Since the N_TTY line discipline input processing can output concurrently with a tty write, obtain the N_TTY ldisc output_lock to serialize echo output with normal tty writes. This ensures the tty buffer helper tty_insert_flip_string is not called concurrently and everything is fine. Note that this is nicely reproducible by an ordinary user using forkpty and some setup around that (raw termios + ECHO). And it is present in kernels at least after commit d945cb9cce20ac7143c2de8d88b187f62db99bdc (pty: Rework the pty layer to use the normal buffering logic) in 2.6.31-rc3. js: add more info to the commit log js: switch to bool js: lock unconditionally js: lock only the tty->ops->write call References: CVE-2014-0196 Reported-and-tested-by: Jiri Slaby <jslaby@suse.cz> Signed-off-by: Peter Hurley <peter@hurleysoftware.com> Signed-off-by: Jiri Slaby <jslaby@suse.cz> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Alan Cox <alan@lxorguk.ukuu.org.uk> Cc: <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int packet_diag_dump(struct sk_buff *skb, struct netlink_callback *cb) { int num = 0, s_num = cb->args[0]; struct packet_diag_req *req; struct net *net; struct sock *sk; bool may_report_filterinfo; net = sock_net(skb->sk); req = nlmsg_data(cb->nlh); may_report_filterinfo = ns_capable(net->user_ns, CAP_NET_ADMIN); mutex_lock(&net->packet.sklist_lock); sk_for_each(sk, &net->packet.sklist) { if (!net_eq(sock_net(sk), net)) continue; if (num < s_num) goto next; if (sk_diag_fill(sk, skb, req, may_report_filterinfo, sk_user_ns(NETLINK_CB(cb->skb).sk), NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, NLM_F_MULTI, sock_i_ino(sk)) < 0) goto done; next: num++; } done: mutex_unlock(&net->packet.sklist_lock); cb->args[0] = num; return skb->len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'net: Use netlink_ns_capable to verify the permisions of netlink messages It is possible by passing a netlink socket to a more privileged executable and then to fool that executable into writing to the socket data that happens to be valid netlink message to do something that privileged executable did not intend to do. To keep this from happening replace bare capable and ns_capable calls with netlink_capable, netlink_net_calls and netlink_ns_capable calls. Which act the same as the previous calls except they verify that the opener of the socket had the desired permissions as well. Reported-by: Andy Lutomirski <luto@amacapital.net> Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct nlattr *attrs[XFRMA_MAX+1]; const struct xfrm_link *link; int type, err; type = nlh->nlmsg_type; if (type > XFRM_MSG_MAX) return -EINVAL; type -= XFRM_MSG_BASE; link = &xfrm_dispatch[type]; /* All operations require privileges, even GET */ if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) return -EPERM; if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) || type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) && (nlh->nlmsg_flags & NLM_F_DUMP)) { if (link->dump == NULL) return -EINVAL; { struct netlink_dump_control c = { .dump = link->dump, .done = link->done, }; return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c); } } err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs, XFRMA_MAX, xfrma_policy); if (err < 0) return err; if (link->doit == NULL) return -EINVAL; return link->doit(skb, nlh, attrs); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'net: Use netlink_ns_capable to verify the permisions of netlink messages It is possible by passing a netlink socket to a more privileged executable and then to fool that executable into writing to the socket data that happens to be valid netlink message to do something that privileged executable did not intend to do. To keep this from happening replace bare capable and ns_capable calls with netlink_capable, netlink_net_calls and netlink_ns_capable calls. Which act the same as the previous calls except they verify that the opener of the socket had the desired permissions as well. Reported-by: Andy Lutomirski <luto@amacapital.net> Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int crypto_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { struct nlattr *attrs[CRYPTOCFGA_MAX+1]; const struct crypto_link *link; int type, err; type = nlh->nlmsg_type; if (type > CRYPTO_MSG_MAX) return -EINVAL; type -= CRYPTO_MSG_BASE; link = &crypto_dispatch[type]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if ((type == (CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE) && (nlh->nlmsg_flags & NLM_F_DUMP))) { struct crypto_alg *alg; u16 dump_alloc = 0; if (link->dump == NULL) return -EINVAL; list_for_each_entry(alg, &crypto_alg_list, cra_list) dump_alloc += CRYPTO_REPORT_MAXSIZE; { struct netlink_dump_control c = { .dump = link->dump, .done = link->done, .min_dump_alloc = dump_alloc, }; return netlink_dump_start(crypto_nlsk, skb, nlh, &c); } } err = nlmsg_parse(nlh, crypto_msg_min[type], attrs, CRYPTOCFGA_MAX, crypto_policy); if (err < 0) return err; if (link->doit == NULL) return -EINVAL; return link->doit(skb, nlh, attrs); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'net: Use netlink_ns_capable to verify the permisions of netlink messages It is possible by passing a netlink socket to a more privileged executable and then to fool that executable into writing to the socket data that happens to be valid netlink message to do something that privileged executable did not intend to do. To keep this from happening replace bare capable and ns_capable calls with netlink_capable, netlink_net_calls and netlink_ns_capable calls. Which act the same as the previous calls except they verify that the opener of the socket had the desired permissions as well. Reported-by: Andy Lutomirski <luto@amacapital.net> Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb) { spin_unlock(&hb->lock); drop_futex_key_refs(&q->key); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'futex: Fix errors in nested key ref-counting futex_wait() is leaking key references due to futex_wait_setup() acquiring an additional reference via the queue_lock() routine. The nested key ref-counting has been masking bugs and complicating code analysis. queue_lock() is only called with a previously ref-counted key, so remove the additional ref-counting from the queue_(un)lock() functions. Also futex_wait_requeue_pi() drops one key reference too many in unqueue_me_pi(). Remove the key reference handling from unqueue_me_pi(). This was paired with a queue_lock() in futex_lock_pi(), so the count remains unchanged. Document remaining nested key ref-counting sites. Signed-off-by: Darren Hart <dvhart@linux.intel.com> Reported-and-tested-by: Matthieu Fertré<matthieu.fertre@kerlabs.com> Reported-by: Louis Rilling<louis.rilling@kerlabs.com> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Eric Dumazet <eric.dumazet@gmail.com> Cc: John Kacur <jkacur@redhat.com> Cc: Rusty Russell <rusty@rustcorp.com.au> LKML-Reference: <4CBB17A8.70401@linux.intel.com> Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Cc: stable@kernel.org'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int apparmor_bprm_set_creds(struct linux_binprm *bprm) { struct aa_task_cxt *cxt; struct aa_profile *profile, *new_profile = NULL; struct aa_namespace *ns; char *buffer = NULL; unsigned int state; struct file_perms perms = {}; struct path_cond cond = { bprm->file->f_path.dentry->d_inode->i_uid, bprm->file->f_path.dentry->d_inode->i_mode }; const char *name = NULL, *target = NULL, *info = NULL; int error = cap_bprm_set_creds(bprm); if (error) return error; if (bprm->cred_prepared) return 0; cxt = bprm->cred->security; BUG_ON(!cxt); profile = aa_get_profile(aa_newest_version(cxt->profile)); /* * get the namespace from the replacement profile as replacement * can change the namespace */ ns = profile->ns; state = profile->file.start; /* buffer freed below, name is pointer into buffer */ error = aa_path_name(&bprm->file->f_path, profile->path_flags, &buffer, &name, &info); if (error) { if (profile->flags & (PFLAG_IX_ON_NAME_ERROR | PFLAG_UNCONFINED)) error = 0; name = bprm->filename; goto audit; } /* Test for onexec first as onexec directives override other * x transitions. */ if (unconfined(profile)) { /* unconfined task */ if (cxt->onexec) /* change_profile on exec already been granted */ new_profile = aa_get_profile(cxt->onexec); else new_profile = find_attach(ns, &ns->base.profiles, name); if (!new_profile) goto cleanup; goto apply; } /* find exec permissions for name */ state = aa_str_perms(profile->file.dfa, state, name, &cond, &perms); if (cxt->onexec) { struct file_perms cp; info = "change_profile onexec"; if (!(perms.allow & AA_MAY_ONEXEC)) goto audit; /* test if this exec can be paired with change_profile onexec. * onexec permission is linked to exec with a standard pairing * exec\0change_profile */ state = aa_dfa_null_transition(profile->file.dfa, state); cp = change_profile_perms(profile, cxt->onexec->ns, cxt->onexec->base.name, AA_MAY_ONEXEC, state); if (!(cp.allow & AA_MAY_ONEXEC)) goto audit; new_profile = aa_get_profile(aa_newest_version(cxt->onexec)); goto apply; } if (perms.allow & MAY_EXEC) { /* exec permission determine how to transition */ new_profile = x_to_profile(profile, name, perms.xindex); if (!new_profile) { if (perms.xindex & AA_X_INHERIT) { /* (p|c|n)ix - don't change profile but do * use the newest version, which was picked * up above when getting profile */ info = "ix fallback"; new_profile = aa_get_profile(profile); goto x_clear; } else if (perms.xindex & AA_X_UNCONFINED) { new_profile = aa_get_profile(ns->unconfined); info = "ux fallback"; } else { error = -ENOENT; info = "profile not found"; } } } else if (COMPLAIN_MODE(profile)) { /* no exec permission - are we in learning mode */ new_profile = aa_new_null_profile(profile, 0); if (!new_profile) { error = -ENOMEM; info = "could not create null profile"; } else { error = -EACCES; target = new_profile->base.hname; } perms.xindex |= AA_X_UNSAFE; } else /* fail exec */ error = -EACCES; if (!new_profile) goto audit; if (bprm->unsafe & LSM_UNSAFE_SHARE) { /* FIXME: currently don't mediate shared state */ ; } if (bprm->unsafe & (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) { error = may_change_ptraced_domain(current, new_profile); if (error) { aa_put_profile(new_profile); goto audit; } } /* Determine if secure exec is needed. * Can be at this point for the following reasons: * 1. unconfined switching to confined * 2. confined switching to different confinement * 3. confined switching to unconfined * * Cases 2 and 3 are marked as requiring secure exec * (unless policy specified "unsafe exec") * * bprm->unsafe is used to cache the AA_X_UNSAFE permission * to avoid having to recompute in secureexec */ if (!(perms.xindex & AA_X_UNSAFE)) { AA_DEBUG("scrubbing environment variables for %s profile=%s\n", name, new_profile->base.hname); bprm->unsafe |= AA_SECURE_X_NEEDED; } apply: target = new_profile->base.hname; /* when transitioning profiles clear unsafe personality bits */ bprm->per_clear |= PER_CLEAR_ON_SETID; x_clear: aa_put_profile(cxt->profile); /* transfer new profile reference will be released when cxt is freed */ cxt->profile = new_profile; /* clear out all temporary/transitional state from the context */ aa_put_profile(cxt->previous); aa_put_profile(cxt->onexec); cxt->previous = NULL; cxt->onexec = NULL; cxt->token = 0; audit: error = aa_audit_file(profile, &perms, GFP_KERNEL, OP_EXEC, MAY_EXEC, name, target, cond.uid, info, error); cleanup: aa_put_profile(profile); kfree(buffer); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Add PR_{GET,SET}_NO_NEW_PRIVS to prevent execve from granting privs With this change, calling prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) disables privilege granting operations at execve-time. For example, a process will not be able to execute a setuid binary to change their uid or gid if this bit is set. The same is true for file capabilities. Additionally, LSM_UNSAFE_NO_NEW_PRIVS is defined to ensure that LSMs respect the requested behavior. To determine if the NO_NEW_PRIVS bit is set, a task may call prctl(PR_GET_NO_NEW_PRIVS, 0, 0, 0, 0); It returns 1 if set and 0 if it is not set. If any of the arguments are non-zero, it will return -1 and set errno to -EINVAL. (PR_SET_NO_NEW_PRIVS behaves similarly.) This functionality is desired for the proposed seccomp filter patch series. By using PR_SET_NO_NEW_PRIVS, it allows a task to modify the system call behavior for itself and its child tasks without being able to impact the behavior of a more privileged task. Another potential use is making certain privileged operations unprivileged. For example, chroot may be considered "safe" if it cannot affect privileged tasks. Note, this patch causes execve to fail when PR_SET_NO_NEW_PRIVS is set and AppArmor is in use. It is fixed in a subsequent patch. Signed-off-by: Andy Lutomirski <luto@amacapital.net> Signed-off-by: Will Drewry <wad@chromium.org> Acked-by: Eric Paris <eparis@redhat.com> Acked-by: Kees Cook <keescook@chromium.org> v18: updated change desc v17: using new define values as per 3.4 Signed-off-by: James Morris <james.l.morris@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sdap_ad_tokengroups_get_posix_members(TALLOC_CTX *mem_ctx, struct sdap_ad_tokengroups_initgr_posix_state *state, size_t num_sids, char **sids, size_t *_num_missing, char ***_missing, size_t *_num_valid, char ***_valid_groups) { TALLOC_CTX *tmp_ctx = NULL; struct sss_domain_info *domain = NULL; struct ldb_message *msg = NULL; const char *attrs[] = {SYSDB_NAME, SYSDB_POSIX, NULL}; const char *is_posix = NULL; const char *name = NULL; char *sid = NULL; char **valid_groups = NULL; size_t num_valid_groups; char **missing_sids = NULL; size_t num_missing_sids; size_t i; errno_t ret; tmp_ctx = talloc_new(NULL); if (tmp_ctx == NULL) { DEBUG(SSSDBG_CRIT_FAILURE, "talloc_new() failed\n"); ret = ENOMEM; goto done; } num_valid_groups = 0; valid_groups = talloc_zero_array(tmp_ctx, char*, num_sids + 1); if (valid_groups == NULL) { ret = ENOMEM; goto done; } num_missing_sids = 0; missing_sids = talloc_zero_array(tmp_ctx, char*, num_sids + 1); if (missing_sids == NULL) { ret = ENOMEM; goto done; } /* For each SID check if it is already present in the cache. If yes, we * will get name of the group and update the membership. Otherwise we need * to remember the SID and download missing groups one by one. */ for (i = 0; i < num_sids; i++) { sid = sids[i]; DEBUG(SSSDBG_TRACE_LIBS, "Processing membership SID [%s]\n", sid); domain = sss_get_domain_by_sid_ldap_fallback(state->domain, sid); if (domain == NULL) { DEBUG(SSSDBG_MINOR_FAILURE, "Domain not found for SID %s\n", sid); continue; } ret = sysdb_search_group_by_sid_str(tmp_ctx, domain->sysdb, domain, sid, attrs, &msg); if (ret == EOK) { is_posix = ldb_msg_find_attr_as_string(msg, SYSDB_POSIX, NULL); if (is_posix != NULL && strcmp(is_posix, "FALSE") == 0) { /* skip non-posix group */ continue; } /* we will update membership of this group */ name = ldb_msg_find_attr_as_string(msg, SYSDB_NAME, NULL); if (name == NULL) { DEBUG(SSSDBG_MINOR_FAILURE, "Could not retrieve group name from sysdb\n"); ret = EINVAL; goto done; } valid_groups[num_valid_groups] = sysdb_group_strdn(valid_groups, domain->name, name); if (valid_groups[num_valid_groups] == NULL) { ret = ENOMEM; goto done; } num_valid_groups++; } else if (ret == ENOENT) { if (_missing != NULL) { /* we need to download this group */ missing_sids[num_missing_sids] = talloc_steal(missing_sids, sid); num_missing_sids++; DEBUG(SSSDBG_TRACE_FUNC, "Missing SID %s will be downloaded\n", sid); } /* else: We have downloaded missing groups but some of them may * remained missing because they are outside of search base. We * will just ignore them and continue with the next group. */ } else { DEBUG(SSSDBG_MINOR_FAILURE, "Could not look up SID %s in sysdb: " "[%s]\n", sid, strerror(ret)); goto done; } } valid_groups[num_valid_groups] = NULL; missing_sids[num_missing_sids] = NULL; /* return list of missing groups */ if (_missing != NULL) { *_missing = talloc_steal(mem_ctx, missing_sids); *_num_missing = num_missing_sids; } /* return list of missing groups */ if (_valid_groups != NULL) { *_valid_groups = talloc_steal(mem_ctx, valid_groups); *_num_valid = num_valid_groups; } ret = EOK; done: talloc_free(tmp_ctx); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'AD: process non-posix nested groups using tokenGroups When initgr is performed for AD supporting tokenGroups, do not skip non-posix groups. Resolves: https://fedorahosted.org/sssd/ticket/2343 Reviewed-by: Michal Židek <mzidek@redhat.com> (cherry picked from commit 4932db6258ccfb612a3a28eb6a618c2f042b9d58)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: asn1_read_value_type (asn1_node root, const char *name, void *ivalue, int *len, unsigned int *etype) { asn1_node node, p, p2; int len2, len3, result; int value_size = *len; unsigned char *value = ivalue; unsigned type; node = asn1_find_node (root, name); if (node == NULL) return ASN1_ELEMENT_NOT_FOUND; type = type_field (node->type); if ((type != ASN1_ETYPE_NULL) && (type != ASN1_ETYPE_CHOICE) && !(node->type & CONST_DEFAULT) && !(node->type & CONST_ASSIGN) && (node->value == NULL)) return ASN1_VALUE_NOT_FOUND; if (etype) *etype = type; switch (type) { case ASN1_ETYPE_NULL: PUT_STR_VALUE (value, value_size, "NULL"); break; case ASN1_ETYPE_BOOLEAN: if ((node->type & CONST_DEFAULT) && (node->value == NULL)) { p = node->down; while (type_field (p->type) != ASN1_ETYPE_DEFAULT) p = p->right; if (p->type & CONST_TRUE) { PUT_STR_VALUE (value, value_size, "TRUE"); } else { PUT_STR_VALUE (value, value_size, "FALSE"); } } else if (node->value[0] == 'T') { PUT_STR_VALUE (value, value_size, "TRUE"); } else { PUT_STR_VALUE (value, value_size, "FALSE"); } break; case ASN1_ETYPE_INTEGER: case ASN1_ETYPE_ENUMERATED: if ((node->type & CONST_DEFAULT) && (node->value == NULL)) { p = node->down; while (type_field (p->type) != ASN1_ETYPE_DEFAULT) p = p->right; if ((isdigit (p->value[0])) || (p->value[0] == '-') || (p->value[0] == '+')) { result = _asn1_convert_integer (p->value, value, value_size, len); if (result != ASN1_SUCCESS) return result; } else { /* is an identifier like v1 */ p2 = node->down; while (p2) { if (type_field (p2->type) == ASN1_ETYPE_CONSTANT) { if (!_asn1_strcmp (p2->name, p->value)) { result = _asn1_convert_integer (p2->value, value, value_size, len); if (result != ASN1_SUCCESS) return result; break; } } p2 = p2->right; } } } else { len2 = -1; result = asn1_get_octet_der (node->value, node->value_len, &len2, value, value_size, len); if (result != ASN1_SUCCESS) return result; } break; case ASN1_ETYPE_OBJECT_ID: if (node->type & CONST_ASSIGN) { value[0] = 0; p = node->down; while (p) { if (type_field (p->type) == ASN1_ETYPE_CONSTANT) { ADD_STR_VALUE (value, value_size, p->value); if (p->right) { ADD_STR_VALUE (value, value_size, "."); } } p = p->right; } *len = _asn1_strlen (value) + 1; } else if ((node->type & CONST_DEFAULT) && (node->value == NULL)) { p = node->down; while (type_field (p->type) != ASN1_ETYPE_DEFAULT) p = p->right; PUT_STR_VALUE (value, value_size, p->value); } else { PUT_STR_VALUE (value, value_size, node->value); } break; case ASN1_ETYPE_GENERALIZED_TIME: case ASN1_ETYPE_UTC_TIME: PUT_AS_STR_VALUE (value, value_size, node->value, node->value_len); break; case ASN1_ETYPE_OCTET_STRING: case ASN1_ETYPE_GENERALSTRING: case ASN1_ETYPE_NUMERIC_STRING: case ASN1_ETYPE_IA5_STRING: case ASN1_ETYPE_TELETEX_STRING: case ASN1_ETYPE_PRINTABLE_STRING: case ASN1_ETYPE_UNIVERSAL_STRING: case ASN1_ETYPE_BMP_STRING: case ASN1_ETYPE_UTF8_STRING: case ASN1_ETYPE_VISIBLE_STRING: len2 = -1; result = asn1_get_octet_der (node->value, node->value_len, &len2, value, value_size, len); if (result != ASN1_SUCCESS) return result; break; case ASN1_ETYPE_BIT_STRING: len2 = -1; result = asn1_get_bit_der (node->value, node->value_len, &len2, value, value_size, len); if (result != ASN1_SUCCESS) return result; break; case ASN1_ETYPE_CHOICE: PUT_STR_VALUE (value, value_size, node->down->name); break; case ASN1_ETYPE_ANY: len3 = -1; len2 = asn1_get_length_der (node->value, node->value_len, &len3); if (len2 < 0) return ASN1_DER_ERROR; PUT_VALUE (value, value_size, node->value + len3, len2); break; default: return ASN1_ELEMENT_NOT_FOUND; break; } return ASN1_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'safer usage of memcpy().'</s>
<s>[INST] Given the following code containing errors, provide 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 futex_requeue(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2, int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; int drop_count = 0, task_count = 0, ret; struct futex_pi_state *pi_state = NULL; struct futex_hash_bucket *hb1, *hb2; struct futex_q *this, *next; if (requeue_pi) { /* * Requeue PI only works on two distinct uaddrs. This * check is only valid for private futexes. See below. */ if (uaddr1 == uaddr2) return -EINVAL; /* * requeue_pi requires a pi_state, try to allocate it now * without any locks in case it fails. */ if (refill_pi_state_cache()) return -ENOMEM; /* * requeue_pi must wake as many tasks as it can, up to nr_wake * + nr_requeue, since it acquires the rt_mutex prior to * returning to userspace, so as to not leave the rt_mutex with * waiters and no owner. However, second and third wake-ups * cannot be predicted as they involve race conditions with the * first wake and a fault while looking up the pi_state. Both * pthread_cond_signal() and pthread_cond_broadcast() should * use nr_wake=1. */ if (nr_wake != 1) return -EINVAL; } retry: if (pi_state != NULL) { /* * We will have to lookup the pi_state again, so free this one * to keep the accounting correct. */ free_pi_state(pi_state); pi_state = NULL; } ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, requeue_pi ? VERIFY_WRITE : VERIFY_READ); if (unlikely(ret != 0)) goto out_put_key1; /* * The check above which compares uaddrs is not sufficient for * shared futexes. We need to compare the keys: */ if (requeue_pi && match_futex(&key1, &key2)) { ret = -EINVAL; goto out_put_keys; } hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: hb_waiters_inc(hb2); double_lock_hb(hb1, hb2); if (likely(cmpval != NULL)) { u32 curval; ret = get_futex_value_locked(&curval, uaddr1); if (unlikely(ret)) { double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); ret = get_user(curval, uaddr1); if (ret) goto out_put_keys; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&key2); put_futex_key(&key1); goto retry; } if (curval != *cmpval) { ret = -EAGAIN; goto out_unlock; } } if (requeue_pi && (task_count - nr_wake < nr_requeue)) { /* * Attempt to acquire uaddr2 and wake the top waiter. If we * intend to requeue waiters, force setting the FUTEX_WAITERS * bit. We force this here where we are able to easily handle * faults rather in the requeue loop below. */ ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1, &key2, &pi_state, nr_requeue); /* * At this point the top_waiter has either taken uaddr2 or is * waiting on it. If the former, then the pi_state will not * exist yet, look it up one more time to ensure we have a * reference to it. If the lock was taken, ret contains the * vpid of the top waiter task. */ if (ret > 0) { WARN_ON(pi_state); drop_count++; task_count++; /* * If we acquired the lock, then the user * space value of uaddr2 should be vpid. It * cannot be changed by the top waiter as it * is blocked on hb2 lock if it tries to do * so. If something fiddled with it behind our * back the pi state lookup might unearth * it. So we rather use the known value than * rereading and handing potential crap to * lookup_pi_state. */ ret = lookup_pi_state(ret, hb2, &key2, &pi_state, NULL); } switch (ret) { case 0: break; case -EFAULT: double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); ret = fault_in_user_writeable(uaddr2); if (!ret) goto retry; goto out; case -EAGAIN: /* The owner was exiting, try again. */ double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); cond_resched(); goto retry; default: goto out_unlock; } } plist_for_each_entry_safe(this, next, &hb1->chain, list) { if (task_count - nr_wake >= nr_requeue) break; if (!match_futex(&this->key, &key1)) continue; /* * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always * be paired with each other and no other futex ops. * * We should never be requeueing a futex_q with a pi_state, * which is awaiting a futex_unlock_pi(). */ if ((requeue_pi && !this->rt_waiter) || (!requeue_pi && this->rt_waiter) || this->pi_state) { ret = -EINVAL; break; } /* * Wake nr_wake waiters. For requeue_pi, if we acquired the * lock, we already woke the top_waiter. If not, it will be * woken by futex_unlock_pi(). */ if (++task_count <= nr_wake && !requeue_pi) { wake_futex(this); continue; } /* Ensure we requeue to the expected futex for requeue_pi. */ if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) { ret = -EINVAL; break; } /* * Requeue nr_requeue waiters and possibly one more in the case * of requeue_pi if we couldn't acquire the lock atomically. */ if (requeue_pi) { /* Prepare the waiter to take the rt_mutex. */ atomic_inc(&pi_state->refcount); this->pi_state = pi_state; ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex, this->rt_waiter, this->task, 1); if (ret == 1) { /* We got the lock. */ requeue_pi_wake_futex(this, &key2, hb2); drop_count++; continue; } else if (ret) { /* -EDEADLK */ this->pi_state = NULL; free_pi_state(pi_state); goto out_unlock; } } requeue_futex(this, hb1, hb2, &key2); drop_count++; } out_unlock: double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); /* * drop_futex_key_refs() must be called outside the spinlocks. During * the requeue we moved futex_q's from the hash bucket at key1 to the * one at key2 and updated their key pointer. We no longer need to * hold the references to key1. */ while (--drop_count >= 0) drop_futex_key_refs(&key1); out_put_keys: put_futex_key(&key2); out_put_key1: put_futex_key(&key1); out: if (pi_state != NULL) free_pi_state(pi_state); return ret ? ret : task_count; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'futex: Make lookup_pi_state more robust The current implementation of lookup_pi_state has ambigous handling of the TID value 0 in the user space futex. We can get into the kernel even if the TID value is 0, because either there is a stale waiters bit or the owner died bit is set or we are called from the requeue_pi path or from user space just for fun. The current code avoids an explicit sanity check for pid = 0 in case that kernel internal state (waiters) are found for the user space address. This can lead to state leakage and worse under some circumstances. Handle the cases explicit: Waiter | pi_state | pi->owner | uTID | uODIED | ? [1] NULL | --- | --- | 0 | 0/1 | Valid [2] NULL | --- | --- | >0 | 0/1 | Valid [3] Found | NULL | -- | Any | 0/1 | Invalid [4] Found | Found | NULL | 0 | 1 | Valid [5] Found | Found | NULL | >0 | 1 | Invalid [6] Found | Found | task | 0 | 1 | Valid [7] Found | Found | NULL | Any | 0 | Invalid [8] Found | Found | task | ==taskTID | 0/1 | Valid [9] Found | Found | task | 0 | 0 | Invalid [10] Found | Found | task | !=taskTID | 0/1 | Invalid [1] Indicates that the kernel can acquire the futex atomically. We came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit. [2] Valid, if TID does not belong to a kernel thread. If no matching thread is found then it indicates that the owner TID has died. [3] Invalid. The waiter is queued on a non PI futex [4] Valid state after exit_robust_list(), which sets the user space value to FUTEX_WAITERS | FUTEX_OWNER_DIED. [5] The user space value got manipulated between exit_robust_list() and exit_pi_state_list() [6] Valid state after exit_pi_state_list() which sets the new owner in the pi_state but cannot access the user space value. [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set. [8] Owner and user space value match [9] There is no transient state which sets the user space TID to 0 except exit_robust_list(), but this is indicated by the FUTEX_OWNER_DIED bit. See [4] [10] There is no transient state which leaves owner and user space TID out of sync. Signed-off-by: Thomas Gleixner <tglx@linutronix.de> Cc: Kees Cook <keescook@chromium.org> Cc: Will Drewry <wad@chromium.org> Cc: Darren Hart <dvhart@linux.intel.com> Cc: stable@vger.kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void wsgi_setup_access(WSGIDaemonProcess *daemon) { /* Setup the umask for the effective user. */ if (daemon->group->umask != -1) umask(daemon->group->umask); /* Change to chroot environment. */ if (daemon->group->root) { if (chroot(daemon->group->root) == -1) { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Unable to change root " "directory to '%s'.", getpid(), daemon->group->root); } } /* Setup the working directory.*/ if (daemon->group->home) { if (chdir(daemon->group->home) == -1) { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Unable to change working " "directory to '%s'.", getpid(), daemon->group->home); } } else if (geteuid()) { struct passwd *pwent; pwent = getpwuid(geteuid()); if (pwent) { if (chdir(pwent->pw_dir) == -1) { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Unable to change working " "directory to '%s'.", getpid(), pwent->pw_dir); } } else { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Unable to determine home " "directory for uid=%ld.", getpid(), (long)geteuid()); } } else { struct passwd *pwent; pwent = getpwuid(daemon->group->uid); if (pwent) { if (chdir(pwent->pw_dir) == -1) { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Unable to change working " "directory to '%s'.", getpid(), pwent->pw_dir); } } else { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Unable to determine home " "directory for uid=%ld.", getpid(), (long)daemon->group->uid); } } /* Don't bother switch user/group if not root. */ if (geteuid()) return; /* Setup the daemon process real and effective group. */ if (setgid(daemon->group->gid) == -1) { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Unable to set group id to gid=%u.", getpid(), (unsigned)daemon->group->gid); } else { if (daemon->group->groups) { if (setgroups(daemon->group->groups_count, daemon->group->groups) == -1) { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Unable " "to set supplementary groups for uname=%s " "of '%s'.", getpid(), daemon->group->user, daemon->group->groups_list); } } else if (initgroups(daemon->group->user, daemon->group->gid) == -1) { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Unable " "to set groups for uname=%s and gid=%u.", getpid(), daemon->group->user, (unsigned)daemon->group->gid); } } /* Setup the daemon process real and effective user. */ if (setuid(daemon->group->uid) == -1) { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Unable to change to uid=%ld.", getpid(), (long)daemon->group->uid); /* * On true UNIX systems this should always succeed at * this point. With certain Linux kernel versions though * we can get back EAGAIN where the target user had * reached their process limit. In that case will be left * running as wrong user. Just exit on all failures to be * safe. Don't die immediately to avoid a fork bomb. */ sleep(20); exit(-1); } /* * Linux prevents generation of core dumps after setuid() * has been used. Attempt to reenable ability to dump core * so that the CoreDumpDirectory directive still works. */ #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE) /* This applies to Linux 2.4 and later. */ if (ap_coredumpdir_configured) { if (prctl(PR_SET_DUMPABLE, 1)) { ap_log_error(APLOG_MARK, APLOG_ALERT, errno, wsgi_server, "mod_wsgi (pid=%d): Set dumpable failed. This child " "will not coredump after software errors.", getpid()); } } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-254'], 'message': 'When there is any sort of error in setting up daemon process group, kill the process rather than risk running in an unexpected state.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: unsigned int FUZ_rand(unsigned int* src) { U32 rand32 = *src; rand32 *= PRIME1; rand32 += PRIME2; rand32 = FUZ_rotl32(rand32, 13); *src = rand32; return rand32; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fixed : issue 52 (reported by Ludwig Strigeus)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int __poke_user(struct task_struct *child, addr_t addr, addr_t data) { struct user *dummy = NULL; addr_t offset; if (addr < (addr_t) &dummy->regs.acrs) { /* * psw and gprs are stored on the stack */ if (addr == (addr_t) &dummy->regs.psw.mask) { unsigned long mask = PSW_MASK_USER; mask |= is_ri_task(child) ? PSW_MASK_RI : 0; if ((data & ~mask) != PSW_USER_BITS) return -EINVAL; if ((data & PSW_MASK_EA) && !(data & PSW_MASK_BA)) return -EINVAL; } *(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr) = data; } else if (addr < (addr_t) (&dummy->regs.orig_gpr2)) { /* * access registers are stored in the thread structure */ offset = addr - (addr_t) &dummy->regs.acrs; #ifdef CONFIG_64BIT /* * Very special case: old & broken 64 bit gdb writing * to acrs[15] with a 64 bit value. Ignore the lower * half of the value and write the upper 32 bit to * acrs[15]. Sick... */ if (addr == (addr_t) &dummy->regs.acrs[15]) child->thread.acrs[15] = (unsigned int) (data >> 32); else #endif *(addr_t *)((addr_t) &child->thread.acrs + offset) = data; } else if (addr == (addr_t) &dummy->regs.orig_gpr2) { /* * orig_gpr2 is stored on the kernel stack */ task_pt_regs(child)->orig_gpr2 = data; } else if (addr < (addr_t) &dummy->regs.fp_regs) { /* * prevent writes of padding hole between * orig_gpr2 and fp_regs on s390. */ return 0; } else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) { /* * floating point regs. are stored in the thread structure */ if (addr == (addr_t) &dummy->regs.fp_regs.fpc) if ((unsigned int) data != 0 || test_fp_ctl(data >> (BITS_PER_LONG - 32))) return -EINVAL; offset = addr - (addr_t) &dummy->regs.fp_regs; *(addr_t *)((addr_t) &child->thread.fp_regs + offset) = data; } else if (addr < (addr_t) (&dummy->regs.per_info + 1)) { /* * Handle access to the per_info structure. */ addr -= (addr_t) &dummy->regs.per_info; __poke_user_per(child, addr, data); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264', 'CWE-269'], 'message': 's390/ptrace: fix PSW mask check The PSW mask check of the PTRACE_POKEUSR_AREA command is incorrect. The PSW_MASK_USER define contains the PSW_MASK_ASC bits, the ptrace interface accepts all combinations for the address-space-control bits. To protect the kernel space the PSW mask check in ptrace needs to reject the address-space-control bit combination for home space. Fixes CVE-2014-3534 Cc: stable@vger.kernel.org Signed-off-by: Martin Schwidefsky <schwidefsky@de.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: acc_ctx_cont(OM_uint32 *minstat, gss_buffer_t buf, gss_ctx_id_t *ctx, gss_buffer_t *responseToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 ret, tmpmin; gss_OID supportedMech; spnego_gss_ctx_id_t sc; unsigned int len; unsigned char *ptr, *bufstart; sc = (spnego_gss_ctx_id_t)*ctx; ret = GSS_S_DEFECTIVE_TOKEN; *negState = REJECT; *minstat = 0; supportedMech = GSS_C_NO_OID; *return_token = ERROR_TOKEN_SEND; *responseToken = *mechListMIC = GSS_C_NO_BUFFER; ptr = bufstart = buf->value; #define REMAIN (buf->length - (ptr - bufstart)) if (REMAIN > INT_MAX) return GSS_S_DEFECTIVE_TOKEN; /* * Attempt to work with old Sun SPNEGO. */ if (*ptr == HEADER_ID) { ret = g_verify_token_header(gss_mech_spnego, &len, &ptr, 0, REMAIN); if (ret) { *minstat = ret; return GSS_S_DEFECTIVE_TOKEN; } } if (*ptr != (CONTEXT | 0x01)) { return GSS_S_DEFECTIVE_TOKEN; } ret = get_negTokenResp(minstat, ptr, REMAIN, negState, &supportedMech, responseToken, mechListMIC); if (ret != GSS_S_COMPLETE) goto cleanup; if (*responseToken == GSS_C_NO_BUFFER && *mechListMIC == GSS_C_NO_BUFFER) { ret = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } if (supportedMech != GSS_C_NO_OID) { ret = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } sc->firstpass = 0; *negState = ACCEPT_INCOMPLETE; *return_token = CONT_TOKEN_SEND; cleanup: if (supportedMech != GSS_C_NO_OID) { generic_gss_release_oid(&tmpmin, &supportedMech); } return ret; #undef REMAIN } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix null deref in SPNEGO acceptor [CVE-2014-4344] When processing a continuation token, acc_ctx_cont was dereferencing the initial byte of the token without checking the length. This could result in a null dereference. CVE-2014-4344: In MIT krb5 1.5 and newer, an unauthenticated or partially authenticated remote attacker can cause a NULL dereference and application crash during a SPNEGO negotiation by sending an empty token as the second or later context token from initiator to acceptor. The attacker must provide at least one valid context token in the security context negotiation before sending the empty token. This can be done by an unauthenticated attacker by forcing SPNEGO to renegotiate the underlying mechanism, or by using IAKERB to wrap an unauthenticated AS-REQ as the first token. CVSSv2 Vector: AV:N/AC:L/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [kaduk@mit.edu: CVE summary, CVSSv2 vector] ticket: 7970 (new) subject: NULL dereference in SPNEGO acceptor for continuation tokens [CVE-2014-4344] target_version: 1.12.2 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int change_mount_flags(struct vfsmount *mnt, int ms_flags) { int error = 0; int readonly_request = 0; if (ms_flags & MS_RDONLY) readonly_request = 1; if (readonly_request == __mnt_is_readonly(mnt)) return 0; if (mnt->mnt_flags & MNT_LOCK_READONLY) return -EPERM; if (readonly_request) error = mnt_make_readonly(real_mount(mnt)); else __mnt_unmake_readonly(real_mount(mnt)); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'mnt: Move the test for MNT_LOCK_READONLY from change_mount_flags into do_remount There are no races as locked mount flags are guaranteed to never change. Moving the test into do_remount makes it more visible, and ensures all filesystem remounts pass the MNT_LOCK_READONLY permission check. This second case is not an issue today as filesystem remounts are guarded by capable(CAP_DAC_ADMIN) and thus will always fail in less privileged mount namespaces, but it could become an issue in the future. Cc: stable@vger.kernel.org Acked-by: Serge E. Hallyn <serge.hallyn@ubuntu.com> Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void vbe_ioport_write_data(void *opaque, uint32_t addr, uint32_t val) { VGACommonState *s = opaque; if (s->vbe_index <= VBE_DISPI_INDEX_NB) { #ifdef DEBUG_BOCHS_VBE printf("VBE: write index=0x%x val=0x%x\n", s->vbe_index, val); #endif switch(s->vbe_index) { case VBE_DISPI_INDEX_ID: if (val == VBE_DISPI_ID0 || val == VBE_DISPI_ID1 || val == VBE_DISPI_ID2 || val == VBE_DISPI_ID3 || val == VBE_DISPI_ID4) { s->vbe_regs[s->vbe_index] = val; } break; case VBE_DISPI_INDEX_XRES: if ((val <= VBE_DISPI_MAX_XRES) && ((val & 7) == 0)) { s->vbe_regs[s->vbe_index] = val; } break; case VBE_DISPI_INDEX_YRES: if (val <= VBE_DISPI_MAX_YRES) { s->vbe_regs[s->vbe_index] = val; } break; case VBE_DISPI_INDEX_BPP: if (val == 0) val = 8; if (val == 4 || val == 8 || val == 15 || val == 16 || val == 24 || val == 32) { s->vbe_regs[s->vbe_index] = val; } break; case VBE_DISPI_INDEX_BANK: if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) { val &= (s->vbe_bank_mask >> 2); } else { val &= s->vbe_bank_mask; } s->vbe_regs[s->vbe_index] = val; s->bank_offset = (val << 16); vga_update_memory_access(s); break; case VBE_DISPI_INDEX_ENABLE: if ((val & VBE_DISPI_ENABLED) && !(s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) { int h, shift_control; s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] = s->vbe_regs[VBE_DISPI_INDEX_XRES]; s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] = s->vbe_regs[VBE_DISPI_INDEX_YRES]; s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET] = 0; s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET] = 0; if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) s->vbe_line_offset = s->vbe_regs[VBE_DISPI_INDEX_XRES] >> 1; else s->vbe_line_offset = s->vbe_regs[VBE_DISPI_INDEX_XRES] * ((s->vbe_regs[VBE_DISPI_INDEX_BPP] + 7) >> 3); s->vbe_start_addr = 0; /* clear the screen (should be done in BIOS) */ if (!(val & VBE_DISPI_NOCLEARMEM)) { memset(s->vram_ptr, 0, s->vbe_regs[VBE_DISPI_INDEX_YRES] * s->vbe_line_offset); } /* we initialize the VGA graphic mode (should be done in BIOS) */ /* graphic mode + memory map 1 */ s->gr[VGA_GFX_MISC] = (s->gr[VGA_GFX_MISC] & ~0x0c) | 0x04 | VGA_GR06_GRAPHICS_MODE; s->cr[VGA_CRTC_MODE] |= 3; /* no CGA modes */ s->cr[VGA_CRTC_OFFSET] = s->vbe_line_offset >> 3; /* width */ s->cr[VGA_CRTC_H_DISP] = (s->vbe_regs[VBE_DISPI_INDEX_XRES] >> 3) - 1; /* height (only meaningful if < 1024) */ h = s->vbe_regs[VBE_DISPI_INDEX_YRES] - 1; s->cr[VGA_CRTC_V_DISP_END] = h; s->cr[VGA_CRTC_OVERFLOW] = (s->cr[VGA_CRTC_OVERFLOW] & ~0x42) | ((h >> 7) & 0x02) | ((h >> 3) & 0x40); /* line compare to 1023 */ s->cr[VGA_CRTC_LINE_COMPARE] = 0xff; s->cr[VGA_CRTC_OVERFLOW] |= 0x10; s->cr[VGA_CRTC_MAX_SCAN] |= 0x40; if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) { shift_control = 0; s->sr[VGA_SEQ_CLOCK_MODE] &= ~8; /* no double line */ } else { shift_control = 2; /* set chain 4 mode */ s->sr[VGA_SEQ_MEMORY_MODE] |= VGA_SR04_CHN_4M; /* activate all planes */ s->sr[VGA_SEQ_PLANE_WRITE] |= VGA_SR02_ALL_PLANES; } s->gr[VGA_GFX_MODE] = (s->gr[VGA_GFX_MODE] & ~0x60) | (shift_control << 5); s->cr[VGA_CRTC_MAX_SCAN] &= ~0x9f; /* no double scan */ } else { /* XXX: the bios should do that */ s->bank_offset = 0; } s->dac_8bit = (val & VBE_DISPI_8BIT_DAC) > 0; s->vbe_regs[s->vbe_index] = val; vga_update_memory_access(s); break; case VBE_DISPI_INDEX_VIRT_WIDTH: { int w, h, line_offset; if (val < s->vbe_regs[VBE_DISPI_INDEX_XRES]) return; w = val; if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) line_offset = w >> 1; else line_offset = w * ((s->vbe_regs[VBE_DISPI_INDEX_BPP] + 7) >> 3); h = s->vbe_size / line_offset; /* XXX: support weird bochs semantics ? */ if (h < s->vbe_regs[VBE_DISPI_INDEX_YRES]) return; s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] = w; s->vbe_regs[VBE_DISPI_INDEX_VIRT_HEIGHT] = h; s->vbe_line_offset = line_offset; } break; case VBE_DISPI_INDEX_X_OFFSET: case VBE_DISPI_INDEX_Y_OFFSET: { int x; s->vbe_regs[s->vbe_index] = val; s->vbe_start_addr = s->vbe_line_offset * s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET]; x = s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET]; if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) s->vbe_start_addr += x >> 1; else s->vbe_start_addr += x * ((s->vbe_regs[VBE_DISPI_INDEX_BPP] + 7) >> 3); s->vbe_start_addr >>= 2; } break; default: break; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'vbe: rework sanity checks Plug a bunch of holes in the bochs dispi interface parameter checking. Add a function doing verification on all registers. Call that unconditionally on every register write. That way we should catch everything, even changing one register affecting the valid range of another register. Some of the holes have been added by commit e9c6149f6ae6873f14a12eea554925b6aa4c4dec. Before that commit the maximum possible framebuffer (VBE_DISPI_MAX_XRES * VBE_DISPI_MAX_YRES * 32 bpp) has been smaller than the qemu vga memory (8MB) and the checking for VBE_DISPI_MAX_XRES + VBE_DISPI_MAX_YRES + VBE_DISPI_MAX_BPP was ok. Some of the holes have been there forever, such as VBE_DISPI_INDEX_X_OFFSET and VBE_DISPI_INDEX_Y_OFFSET register writes lacking any verification. Security impact: (1) Guest can make the ui (gtk/vnc/...) use memory rages outside the vga frame buffer as source -> host memory leak. Memory isn't leaked to the guest but to the vnc client though. (2) Qemu will segfault in case the memory range happens to include unmapped areas -> Guest can DoS itself. The guest can not modify host memory, so I don't think this can be used by the guest to escape. CVE-2014-3615 Cc: qemu-stable@nongnu.org Cc: secalert@redhat.com Signed-off-by: Gerd Hoffmann <kraxel@redhat.com> Reviewed-by: Laszlo Ersek <lersek@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ceph_x_verify_authorizer_reply(struct ceph_auth_client *ac, struct ceph_authorizer *a, size_t len) { struct ceph_x_authorizer *au = (void *)a; struct ceph_x_ticket_handler *th; int ret = 0; struct ceph_x_authorize_reply reply; void *p = au->reply_buf; void *end = p + sizeof(au->reply_buf); th = get_ticket_handler(ac, au->service); if (IS_ERR(th)) return PTR_ERR(th); ret = ceph_x_decrypt(&th->session_key, &p, end, &reply, sizeof(reply)); if (ret < 0) return ret; if (ret != sizeof(reply)) return -EPERM; if (au->nonce + 1 != le64_to_cpu(reply.nonce_plus_one)) ret = -EPERM; else ret = 0; dout("verify_authorizer_reply nonce %llx got %llx ret %d\n", au->nonce, le64_to_cpu(reply.nonce_plus_one), ret); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'libceph: do not hard code max auth ticket len We hard code cephx auth ticket buffer size to 256 bytes. This isn't enough for any moderate setups and, in case tickets themselves are not encrypted, leads to buffer overflows (ceph_x_decrypt() errors out, but ceph_decode_copy() doesn't - it's just a memcpy() wrapper). Since the buffer is allocated dynamically anyway, allocated it a bit later, at the point where we know how much is going to be needed. Fixes: http://tracker.ceph.com/issues/8979 Cc: stable@vger.kernel.org Signed-off-by: Ilya Dryomov <ilya.dryomov@inktank.com> Reviewed-by: Sage Weil <sage@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: evbuffer_ptr_memcmp(const struct evbuffer *buf, const struct evbuffer_ptr *pos, const char *mem, size_t len) { struct evbuffer_chain *chain; size_t position; int r; ASSERT_EVBUFFER_LOCKED(buf); if (pos->pos + len > buf->total_len) return -1; chain = pos->_internal.chain; position = pos->_internal.pos_in_chain; while (len && chain) { size_t n_comparable; if (len + position > chain->off) n_comparable = chain->off - position; else n_comparable = len; r = memcmp(chain->buffer + chain->misalign + position, mem, n_comparable); if (r) return r; mem += n_comparable; len -= n_comparable; position = 0; chain = chain->next; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix CVE-2014-6272 in Libevent 2.0 For this fix, we need to make sure that passing too-large inputs to the evbuffer functions can't make us do bad things with the heap. Also, lower the maximum chunk size to the lower of off_t, size_t maximum. This is necessary since otherwise we could get into an infinite loop if we make a chunk that 'misalign' cannot index into.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: evbuffer_prepend(struct evbuffer *buf, const void *data, size_t datlen) { struct evbuffer_chain *chain, *tmp; int result = -1; EVBUFFER_LOCK(buf); if (buf->freeze_start) { goto done; } chain = buf->first; if (chain == NULL) { chain = evbuffer_chain_new(datlen); if (!chain) goto done; evbuffer_chain_insert(buf, chain); } /* we cannot touch immutable buffers */ if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) { /* If this chain is empty, we can treat it as * 'empty at the beginning' rather than 'empty at the end' */ if (chain->off == 0) chain->misalign = chain->buffer_len; if ((size_t)chain->misalign >= datlen) { /* we have enough space to fit everything */ memcpy(chain->buffer + chain->misalign - datlen, data, datlen); chain->off += datlen; chain->misalign -= datlen; buf->total_len += datlen; buf->n_add_for_cb += datlen; goto out; } else if (chain->misalign) { /* we can only fit some of the data. */ memcpy(chain->buffer, (char*)data + datlen - chain->misalign, (size_t)chain->misalign); chain->off += (size_t)chain->misalign; buf->total_len += (size_t)chain->misalign; buf->n_add_for_cb += (size_t)chain->misalign; datlen -= (size_t)chain->misalign; chain->misalign = 0; } } /* we need to add another chain */ if ((tmp = evbuffer_chain_new(datlen)) == NULL) goto done; buf->first = tmp; if (buf->last_with_datap == &buf->first) buf->last_with_datap = &tmp->next; tmp->next = chain; tmp->off = datlen; tmp->misalign = tmp->buffer_len - datlen; memcpy(tmp->buffer + tmp->misalign, data, datlen); buf->total_len += datlen; buf->n_add_for_cb += (size_t)chain->misalign; out: evbuffer_invoke_callbacks(buf); result = 0; done: EVBUFFER_UNLOCK(buf); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix CVE-2014-6272 in Libevent 2.0 For this fix, we need to make sure that passing too-large inputs to the evbuffer functions can't make us do bad things with the heap. Also, lower the maximum chunk size to the lower of off_t, size_t maximum. This is necessary since otherwise we could get into an infinite loop if we make a chunk that 'misalign' cannot index into.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: evbuffer_ptr_set(struct evbuffer *buf, struct evbuffer_ptr *pos, size_t position, enum evbuffer_ptr_how how) { size_t left = position; struct evbuffer_chain *chain = NULL; int result = 0; EVBUFFER_LOCK(buf); switch (how) { case EVBUFFER_PTR_SET: chain = buf->first; pos->pos = position; position = 0; break; case EVBUFFER_PTR_ADD: /* this avoids iterating over all previous chains if we just want to advance the position */ chain = pos->internal_.chain; pos->pos += position; position = pos->internal_.pos_in_chain; break; } while (chain && position + left >= chain->off) { left -= chain->off - position; chain = chain->next; position = 0; } if (chain) { pos->internal_.chain = chain; pos->internal_.pos_in_chain = position + left; } else if (left == 0) { /* The first byte in the (nonexistent) chain after the last chain */ pos->internal_.chain = NULL; pos->internal_.pos_in_chain = 0; } else { PTR_NOT_FOUND(pos); result = -1; } EVBUFFER_UNLOCK(buf); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Fix CVE-2014-6272 in Libevent 2.1 For this fix, we need to make sure that passing too-large inputs to the evbuffer functions can't make us do bad things with the heap. Also, lower the maximum chunk size to the lower of off_t, size_t maximum. This is necessary since otherwise we could get into an infinite loop if we make a chunk that 'misalign' cannot index into.'</s>
<s>[INST] Given the following code containing errors, provide 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_da3_fixhashpath( struct xfs_da_state *state, struct xfs_da_state_path *path) { struct xfs_da_state_blk *blk; struct xfs_da_intnode *node; struct xfs_da_node_entry *btree; xfs_dahash_t lasthash=0; int level; int count; struct xfs_inode *dp = state->args->dp; trace_xfs_da_fixhashpath(state->args); level = path->active-1; blk = &path->blk[ level ]; switch (blk->magic) { case XFS_ATTR_LEAF_MAGIC: lasthash = xfs_attr_leaf_lasthash(blk->bp, &count); if (count == 0) return; break; case XFS_DIR2_LEAFN_MAGIC: lasthash = xfs_dir2_leafn_lasthash(dp, blk->bp, &count); if (count == 0) return; break; case XFS_DA_NODE_MAGIC: lasthash = xfs_da3_node_lasthash(dp, blk->bp, &count); if (count == 0) return; break; } for (blk--, level--; level >= 0; blk--, level--) { struct xfs_da3_icnode_hdr nodehdr; node = blk->bp->b_addr; dp->d_ops->node_hdr_from_disk(&nodehdr, node); btree = dp->d_ops->node_tree_p(node); if (be32_to_cpu(btree->hashval) == lasthash) break; blk->hashval = lasthash; btree[blk->index].hashval = cpu_to_be32(lasthash); xfs_trans_log_buf(state->args->trans, blk->bp, XFS_DA_LOGRANGE(node, &btree[blk->index], sizeof(*btree))); lasthash = be32_to_cpu(btree[nodehdr.count - 1].hashval); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'xfs: fix directory hash ordering bug Commit f5ea1100 ("xfs: add CRCs to dir2/da node blocks") introduced in 3.10 incorrectly converted the btree hash index array pointer in xfs_da3_fixhashpath(). It resulted in the the current hash always being compared against the first entry in the btree rather than the current block index into the btree block's hash entry array. As a result, it was comparing the wrong hashes, and so could misorder the entries in the btree. For most cases, this doesn't cause any problems as it requires hash collisions to expose the ordering problem. However, when there are hash collisions within a directory there is a very good probability that the entries will be ordered incorrectly and that actually matters when duplicate hashes are placed into or removed from the btree block hash entry array. This bug results in an on-disk directory corruption and that results in directory verifier functions throwing corruption warnings into the logs. While no data or directory entries are lost, access to them may be compromised, and attempts to remove entries from a directory that has suffered from this corruption may result in a filesystem shutdown. xfs_repair will fix the directory hash ordering without data loss occuring. [dchinner: wrote useful a commit message] cc: <stable@vger.kernel.org> Reported-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: Mark Tinguely <tinguely@sgi.com> Reviewed-by: Ben Myers <bpm@sgi.com> Signed-off-by: Dave Chinner <david@fromorbit.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: copy_ciphersuites(gnutls_session_t session, gnutls_buffer_st * cdata, int add_scsv) { int ret; uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE + 2]; /* allow space for SCSV */ int cipher_suites_size; size_t init_length = cdata->length; ret = _gnutls_supported_ciphersuites(session, cipher_suites, sizeof(cipher_suites) - 2); if (ret < 0) return gnutls_assert_val(ret); /* Here we remove any ciphersuite that does not conform * the certificate requested, or to the * authentication requested (eg SRP). */ ret = _gnutls_remove_unwanted_ciphersuites(session, cipher_suites, ret, NULL, 0); if (ret < 0) return gnutls_assert_val(ret); /* If no cipher suites were enabled. */ if (ret == 0) return gnutls_assert_val(GNUTLS_E_INSUFFICIENT_CREDENTIALS); cipher_suites_size = ret; if (add_scsv) { cipher_suites[cipher_suites_size] = 0x00; cipher_suites[cipher_suites_size + 1] = 0xff; cipher_suites_size += 2; ret = _gnutls_ext_sr_send_cs(session); if (ret < 0) return gnutls_assert_val(ret); } ret = _gnutls_buffer_append_data_prefix(cdata, 16, cipher_suites, cipher_suites_size); if (ret < 0) return gnutls_assert_val(ret); ret = cdata->length - init_length; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'handshake: add FALLBACK_SCSV priority option This allows clients to enable the TLS_FALLBACK_SCSV mechanism during the handshake, as defined in RFC7507.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static char *memdup(const char *src, size_t buffer_length) { size_t length; bool add = FALSE; char *buffer; if(buffer_length) length = buffer_length; else if(src) { length = strlen(src); add = TRUE; } else /* no length and a NULL src pointer! */ return strdup(""); buffer = malloc(length+add); if(!buffer) return NULL; /* fail */ memcpy(buffer, src, length); /* if length unknown do null termination */ if(add) buffer[length] = '\0'; return buffer; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'curl_easy_duphandle: CURLOPT_COPYPOSTFIELDS read out of bounds When duplicating a handle, the data to post was duplicated using strdup() when it could be binary and contain zeroes and it was not even zero terminated! This caused read out of bounds crashes/segfaults. Since the lib/strdup.c file no longer is easily shared with the curl tool with this change, it now uses its own version instead. Bug: http://curl.haxx.se/docs/adv_20141105.html CVE: CVE-2014-3707 Reported-By: Symeon Paraschoudis'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction) { QCA::Initializer init; QByteArray temp = cipherText; //do padding ourselves if (direction) { while ((temp.length() % 8) != 0) temp.append('\0'); } else { temp = b64ToByte(temp); while ((temp.length() % 8) != 0) temp.append('\0'); } QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode; QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key); QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray(); temp2 += cipher.final().toByteArray(); if (!cipher.ok()) return cipherText; if (direction) temp2 = byteToB64(temp2); return temp2; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Check for invalid input in encrypted buffers The ECB Blowfish decryption function assumed that encrypted input would always come in blocks of 12 characters, as specified. However, buggy clients or annoying people may not adhere to that assumption, causing the core to crash while trying to process the invalid base64 input. With this commit we make sure that we're not overstepping the bounds of the input string while decoding it; instead we bail out early and display the original input. Fixes #1314. Thanks to Tucos for finding that one!'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ssl_parse_supported_elliptic_curves( ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_size, our_size; const unsigned char *p; const ecp_curve_info *curve_info, **curves; list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( list_size + 2 != len || list_size % 2 != 0 ) { SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( POLARSSL_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Don't allow our peer to make us allocate too much memory, * and leave room for a final 0 */ our_size = list_size / 2 + 1; if( our_size > POLARSSL_ECP_DP_MAX ) our_size = POLARSSL_ECP_DP_MAX; if( ( curves = polarssl_malloc( our_size * sizeof( *curves ) ) ) == NULL ) return( POLARSSL_ERR_SSL_MALLOC_FAILED ); /* explicit void pointer cast for buggy MS compiler */ memset( (void *) curves, 0, our_size * sizeof( *curves ) ); ssl->handshake->curves = curves; p = buf + 2; while( list_size > 0 && our_size > 1 ) { curve_info = ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] ); if( curve_info != NULL ) { *curves++ = curve_info; our_size--; } list_size -= 2; p += 2; } return( 0 ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix memory leak with crafted ClientHello'</s>
<s>[INST] Given the following code containing errors, provide 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 handle_emulation_failure(struct kvm_vcpu *vcpu) { int r = EMULATE_DONE; ++vcpu->stat.insn_emulation_fail; trace_kvm_emulate_insn_failed(vcpu); if (!is_guest_mode(vcpu)) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; r = EMULATE_FAIL; } kvm_queue_exception(vcpu, UD_VECTOR); return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'KVM: x86: Don't report guest userspace emulation error to userspace Commit fc3a9157d314 ("KVM: X86: Don't report L2 emulation failures to user-space") disabled the reporting of L2 (nested guest) emulation failures to userspace due to race-condition between a vmexit and the instruction emulator. The same rational applies also to userspace applications that are permitted by the guest OS to access MMIO area or perform PIO. This patch extends the current behavior - of injecting a #UD instead of reporting it to userspace - also for guest userspace code. Signed-off-by: Nadav Amit <namit@cs.technion.ac.il> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: yaml_parser_save_simple_key(yaml_parser_t *parser) { /* * A simple key is required at the current position if the scanner is in * the block context and the current column coincides with the indentation * level. */ int required = (!parser->flow_level && parser->indent == (ptrdiff_t)parser->mark.column); /* * A simple key is required only when it is the first token in the current * line. Therefore it is always allowed. But we add a check anyway. */ assert(parser->simple_key_allowed || !required); /* Impossible. */ /* * If the current position may start a simple key, save it. */ if (parser->simple_key_allowed) { yaml_simple_key_t simple_key; simple_key.possible = 1; simple_key.required = required; simple_key.token_number = parser->tokens_parsed + (parser->tokens.tail - parser->tokens.head); simple_key.mark = parser->mark; if (!yaml_parser_remove_simple_key(parser)) return 0; *(parser->simple_keys.top-1) = simple_key; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix for https://bitbucket.org/xi/libyaml/issue/10/ https://bitbucket.org/xi/libyaml/issue/10/wrapped-strings-cause-assert-failure Commenting out the assert makes the scanner do the right thing and results in just a simple parse 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: match(struct magic_set *ms, struct magic *magic, uint32_t nmagic, const unsigned char *s, size_t nbytes, size_t offset, int mode, int text, int flip, int recursion_level, int *printed_something, int *need_separator, int *returnval) { uint32_t magindex = 0; unsigned int cont_level = 0; int returnvalv = 0, e; /* if a match is found it is set to 1*/ int firstline = 1; /* a flag to print X\n X\n- X */ int print = (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) == 0; if (returnval == NULL) returnval = &returnvalv; if (file_check_mem(ms, cont_level) == -1) return -1; for (magindex = 0; magindex < nmagic; magindex++) { int flush = 0; struct magic *m = &magic[magindex]; if (m->type != FILE_NAME) if ((IS_STRING(m->type) && #define FLT (STRING_BINTEST | STRING_TEXTTEST) ((text && (m->str_flags & FLT) == STRING_BINTEST) || (!text && (m->str_flags & FLT) == STRING_TEXTTEST))) || (m->flag & mode) != mode) { /* Skip sub-tests */ while (magindex + 1 < nmagic && magic[magindex + 1].cont_level != 0 && ++magindex) continue; continue; /* Skip to next top-level test*/ } ms->offset = m->offset; ms->line = m->lineno; /* if main entry matches, print it... */ switch (mget(ms, s, m, nbytes, offset, cont_level, mode, text, flip, recursion_level + 1, printed_something, need_separator, returnval)) { case -1: return -1; case 0: flush = m->reln != '!'; break; default: if (m->type == FILE_INDIRECT) *returnval = 1; switch (magiccheck(ms, m)) { case -1: return -1; case 0: flush++; break; default: flush = 0; break; } break; } if (flush) { /* * main entry didn't match, * flush its continuations */ while (magindex < nmagic - 1 && magic[magindex + 1].cont_level != 0) magindex++; continue; } if ((e = handle_annotation(ms, m)) != 0) { *need_separator = 1; *printed_something = 1; *returnval = 1; return e; } /* * If we are going to print something, we'll need to print * a blank before we print something else. */ if (*m->desc) { *need_separator = 1; *printed_something = 1; if (print_sep(ms, firstline) == -1) return -1; } if (print && mprint(ms, m) == -1) return -1; ms->c.li[cont_level].off = moffset(ms, m); /* and any continuations that match */ if (file_check_mem(ms, ++cont_level) == -1) return -1; while (magindex + 1 < nmagic && magic[magindex + 1].cont_level != 0) { m = &magic[++magindex]; ms->line = m->lineno; /* for messages */ if (cont_level < m->cont_level) continue; if (cont_level > m->cont_level) { /* * We're at the end of the level * "cont_level" continuations. */ cont_level = m->cont_level; } ms->offset = m->offset; if (m->flag & OFFADD) { ms->offset += ms->c.li[cont_level - 1].off; } #ifdef ENABLE_CONDITIONALS if (m->cond == COND_ELSE || m->cond == COND_ELIF) { if (ms->c.li[cont_level].last_match == 1) continue; } #endif switch (mget(ms, s, m, nbytes, offset, cont_level, mode, text, flip, recursion_level + 1, printed_something, need_separator, returnval)) { case -1: return -1; case 0: if (m->reln != '!') continue; flush = 1; break; default: if (m->type == FILE_INDIRECT) *returnval = 1; flush = 0; break; } switch (flush ? 1 : magiccheck(ms, m)) { case -1: return -1; case 0: #ifdef ENABLE_CONDITIONALS ms->c.li[cont_level].last_match = 0; #endif break; default: #ifdef ENABLE_CONDITIONALS ms->c.li[cont_level].last_match = 1; #endif if (m->type == FILE_CLEAR) ms->c.li[cont_level].got_match = 0; else if (ms->c.li[cont_level].got_match) { if (m->type == FILE_DEFAULT) break; } else ms->c.li[cont_level].got_match = 1; if ((e = handle_annotation(ms, m)) != 0) { *need_separator = 1; *printed_something = 1; *returnval = 1; return e; } /* * If we are going to print something, * make sure that we have a separator first. */ if (*m->desc) { if (!*printed_something) { *printed_something = 1; if (print_sep(ms, firstline) == -1) return -1; } } /* * This continuation matched. Print * its message, with a blank before it * if the previous item printed and * this item isn't empty. */ /* space if previous printed */ if (*need_separator && ((m->flag & NOSPACE) == 0) && *m->desc) { if (print && file_printf(ms, " ") == -1) return -1; *need_separator = 0; } if (print && mprint(ms, m) == -1) return -1; ms->c.li[cont_level].off = moffset(ms, m); if (*m->desc) *need_separator = 1; /* * If we see any continuations * at a higher level, * process them. */ if (file_check_mem(ms, ++cont_level) == -1) return -1; break; } } if (*printed_something) { firstline = 0; if (print) *returnval = 1; } if ((ms->flags & MAGIC_CONTINUE) == 0 && *printed_something) { return *returnval; /* don't keep searching */ } } return *returnval; /* This is hit if -k is set or there is no match */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'bump recursion to 15, and allow it to be set from the command line.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: toomany(struct magic_set *ms, const char *name, uint16_t num) { if (file_printf(ms, ", too many %s header sections (%u)", name, num ) == -1) return -1; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': '- Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); #if !defined(HAVE_VLA) jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE]; #else jpc_fix_t joinbuf[bufsize * JPC_QMFB_COLGRPSIZE]; #endif jpc_fix_t *buf = joinbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int hstartcol; #if !defined(HAVE_VLA) /* Allocate memory for the join buffer from the heap. */ if (bufsize > QMFB_JOINBUFSIZE) { if (!(buf = jas_malloc(bufsize * JPC_QMFB_COLGRPSIZE * sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide. */ abort(); } } #endif hstartcol = (numrows + 1 - parity) >> 1; /* Save the samples from the lowpass channel. */ n = hstartcol; srcptr = &a[0]; dstptr = buf; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } srcptr += stride; dstptr += JPC_QMFB_COLGRPSIZE; } /* Copy the samples from the highpass channel into place. */ srcptr = &a[hstartcol * stride]; dstptr = &a[(1 - parity) * stride]; n = numrows - hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += stride; } /* Copy the samples from the lowpass channel into place. */ srcptr = buf; dstptr = &a[parity * stride]; n = hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += JPC_QMFB_COLGRPSIZE; } #if !defined(HAVE_VLA) /* If the join buffer was allocated on the heap, free this memory. */ if (buf != joinbuf) { jas_free(buf); } #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'CVE-2014-8158'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: krb5_gss_inquire_sec_context_by_oid (OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { krb5_gss_ctx_id_rec *ctx; size_t i; if (minor_status == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; *minor_status = 0; if (desired_object == GSS_C_NO_OID) return GSS_S_CALL_INACCESSIBLE_READ; if (data_set == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; *data_set = GSS_C_NO_BUFFER_SET; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (!ctx->established) return GSS_S_NO_CONTEXT; for (i = 0; i < sizeof(krb5_gss_inquire_sec_context_by_oid_ops)/ sizeof(krb5_gss_inquire_sec_context_by_oid_ops[0]); i++) { if (g_OID_prefix_equal(desired_object, &krb5_gss_inquire_sec_context_by_oid_ops[i].oid)) { return (*krb5_gss_inquire_sec_context_by_oid_ops[i].func)(minor_status, context_handle, desired_object, data_set); } } *minor_status = EINVAL; return GSS_S_UNAVAILABLE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: krb5_gss_inquire_context(minor_status, context_handle, initiator_name, acceptor_name, lifetime_rec, mech_type, ret_flags, locally_initiated, opened) OM_uint32 *minor_status; gss_ctx_id_t context_handle; gss_name_t *initiator_name; gss_name_t *acceptor_name; OM_uint32 *lifetime_rec; gss_OID *mech_type; OM_uint32 *ret_flags; int *locally_initiated; int *opened; { krb5_context context; krb5_error_code code; krb5_gss_ctx_id_rec *ctx; krb5_gss_name_t initiator, acceptor; krb5_timestamp now; krb5_deltat lifetime; if (initiator_name) *initiator_name = (gss_name_t) NULL; if (acceptor_name) *acceptor_name = (gss_name_t) NULL; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } initiator = NULL; acceptor = NULL; context = ctx->k5_context; if ((code = krb5_timeofday(context, &now))) { *minor_status = code; save_error_info(*minor_status, context); return(GSS_S_FAILURE); } if ((lifetime = ctx->krb_times.endtime - now) < 0) lifetime = 0; if (initiator_name) { if ((code = kg_duplicate_name(context, ctx->initiate ? ctx->here : ctx->there, &initiator))) { *minor_status = code; save_error_info(*minor_status, context); return(GSS_S_FAILURE); } } if (acceptor_name) { if ((code = kg_duplicate_name(context, ctx->initiate ? ctx->there : ctx->here, &acceptor))) { if (initiator) kg_release_name(context, &initiator); *minor_status = code; save_error_info(*minor_status, context); return(GSS_S_FAILURE); } } if (initiator_name) *initiator_name = (gss_name_t) initiator; if (acceptor_name) *acceptor_name = (gss_name_t) acceptor; if (lifetime_rec) *lifetime_rec = lifetime; if (mech_type) *mech_type = (gss_OID) ctx->mech_used; if (ret_flags) *ret_flags = ctx->gss_flags; if (locally_initiated) *locally_initiated = ctx->initiate; if (opened) *opened = ctx->established; *minor_status = 0; return((lifetime == 0)?GSS_S_CONTEXT_EXPIRED:GSS_S_COMPLETE); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check_exclusion_constraint(Relation heap, Relation index, IndexInfo *indexInfo, ItemPointer tupleid, Datum *values, bool *isnull, EState *estate, bool newIndex, bool errorOK) { Oid *constr_procs = indexInfo->ii_ExclusionProcs; uint16 *constr_strats = indexInfo->ii_ExclusionStrats; Oid *index_collations = index->rd_indcollation; int index_natts = index->rd_index->indnatts; IndexScanDesc index_scan; HeapTuple tup; ScanKeyData scankeys[INDEX_MAX_KEYS]; SnapshotData DirtySnapshot; int i; bool conflict; bool found_self; ExprContext *econtext; TupleTableSlot *existing_slot; TupleTableSlot *save_scantuple; /* * If any of the input values are NULL, the constraint check is assumed to * pass (i.e., we assume the operators are strict). */ for (i = 0; i < index_natts; i++) { if (isnull[i]) return true; } /* * Search the tuples that are in the index for any violations, including * tuples that aren't visible yet. */ InitDirtySnapshot(DirtySnapshot); for (i = 0; i < index_natts; i++) { ScanKeyEntryInitialize(&scankeys[i], 0, i + 1, constr_strats[i], InvalidOid, index_collations[i], constr_procs[i], values[i]); } /* * Need a TupleTableSlot to put existing tuples in. * * To use FormIndexDatum, we have to make the econtext's scantuple point * to this slot. Be sure to save and restore caller's value for * scantuple. */ existing_slot = MakeSingleTupleTableSlot(RelationGetDescr(heap)); econtext = GetPerTupleExprContext(estate); save_scantuple = econtext->ecxt_scantuple; econtext->ecxt_scantuple = existing_slot; /* * May have to restart scan from this point if a potential conflict is * found. */ retry: conflict = false; found_self = false; index_scan = index_beginscan(heap, index, &DirtySnapshot, index_natts, 0); index_rescan(index_scan, scankeys, index_natts, NULL, 0); while ((tup = index_getnext(index_scan, ForwardScanDirection)) != NULL) { TransactionId xwait; Datum existing_values[INDEX_MAX_KEYS]; bool existing_isnull[INDEX_MAX_KEYS]; char *error_new; char *error_existing; /* * Ignore the entry for the tuple we're trying to check. */ if (ItemPointerEquals(tupleid, &tup->t_self)) { if (found_self) /* should not happen */ elog(ERROR, "found self tuple multiple times in index \"%s\"", RelationGetRelationName(index)); found_self = true; continue; } /* * Extract the index column values and isnull flags from the existing * tuple. */ ExecStoreTuple(tup, existing_slot, InvalidBuffer, false); FormIndexDatum(indexInfo, existing_slot, estate, existing_values, existing_isnull); /* If lossy indexscan, must recheck the condition */ if (index_scan->xs_recheck) { if (!index_recheck_constraint(index, constr_procs, existing_values, existing_isnull, values)) continue; /* tuple doesn't actually match, so no * conflict */ } /* * At this point we have either a conflict or a potential conflict. If * we're not supposed to raise error, just return the fact of the * potential conflict without waiting to see if it's real. */ if (errorOK) { conflict = true; break; } /* * If an in-progress transaction is affecting the visibility of this * tuple, we need to wait for it to complete and then recheck. For * simplicity we do rechecking by just restarting the whole scan --- * this case probably doesn't happen often enough to be worth trying * harder, and anyway we don't want to hold any index internal locks * while waiting. */ xwait = TransactionIdIsValid(DirtySnapshot.xmin) ? DirtySnapshot.xmin : DirtySnapshot.xmax; if (TransactionIdIsValid(xwait)) { index_endscan(index_scan); XactLockTableWait(xwait, heap, &tup->t_data->t_ctid, XLTW_RecheckExclusionConstr); goto retry; } /* * We have a definite conflict. Report it. */ error_new = BuildIndexValueDescription(index, values, isnull); error_existing = BuildIndexValueDescription(index, existing_values, existing_isnull); if (newIndex) ereport(ERROR, (errcode(ERRCODE_EXCLUSION_VIOLATION), errmsg("could not create exclusion constraint \"%s\"", RelationGetRelationName(index)), errdetail("Key %s conflicts with key %s.", error_new, error_existing), errtableconstraint(heap, RelationGetRelationName(index)))); else ereport(ERROR, (errcode(ERRCODE_EXCLUSION_VIOLATION), errmsg("conflicting key value violates exclusion constraint \"%s\"", RelationGetRelationName(index)), errdetail("Key %s conflicts with existing key %s.", error_new, error_existing), errtableconstraint(heap, RelationGetRelationName(index)))); } index_endscan(index_scan); /* * Ordinarily, at this point the search should have found the originally * inserted tuple, unless we exited the loop early because of conflict. * However, it is possible to define exclusion constraints for which that * wouldn't be true --- for instance, if the operator is <>. So we no * longer complain if found_self is still false. */ econtext->ecxt_scantuple = save_scantuple; ExecDropSingleTupleTableSlot(existing_slot); return !conflict; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-209'], 'message': 'Fix column-privilege leak in error-message paths While building error messages to return to the user, BuildIndexValueDescription, ExecBuildSlotValueDescription and ri_ReportViolation would happily include the entire key or entire row in the result returned to the user, even if the user didn't have access to view all of the columns being included. Instead, include only those columns which the user is providing or which the user has select rights on. If the user does not have any rights to view the table or any of the columns involved then no detail is provided and a NULL value is returned from BuildIndexValueDescription and ExecBuildSlotValueDescription. Note that, for key cases, the user must have access to all of the columns for the key to be shown; a partial key will not be returned. Further, in master only, do not return any data for cases where row security is enabled on the relation and row security should be applied for the user. This required a bit of refactoring and moving of things around related to RLS- note the addition of utils/misc/rls.c. Back-patch all the way, as column-level privileges are now in all supported versions. This has been assigned CVE-2014-8161, but since the issue and the patch have already been publicized on pgsql-hackers, there's no point in trying to hide this commit.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ExecWithCheckOptions(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate) { ExprContext *econtext; ListCell *l1, *l2; /* * We will use the EState's per-tuple context for evaluating constraint * expressions (creating it if it's not already there). */ econtext = GetPerTupleExprContext(estate); /* Arrange for econtext's scan tuple to be the tuple under test */ econtext->ecxt_scantuple = slot; /* Check each of the constraints */ forboth(l1, resultRelInfo->ri_WithCheckOptions, l2, resultRelInfo->ri_WithCheckOptionExprs) { WithCheckOption *wco = (WithCheckOption *) lfirst(l1); ExprState *wcoExpr = (ExprState *) lfirst(l2); /* * WITH CHECK OPTION checks are intended to ensure that the new tuple * is visible (in the case of a view) or that it passes the * 'with-check' policy (in the case of row security). * If the qual evaluates to NULL or FALSE, then the new tuple won't be * included in the view or doesn't pass the 'with-check' policy for the * table. We need ExecQual to return FALSE for NULL to handle the view * case (the opposite of what we do above for CHECK constraints). */ if (!ExecQual((List *) wcoExpr, econtext, false)) ereport(ERROR, (errcode(ERRCODE_WITH_CHECK_OPTION_VIOLATION), errmsg("new row violates WITH CHECK OPTION for \"%s\"", wco->viewname), errdetail("Failing row contains %s.", ExecBuildSlotValueDescription(slot, RelationGetDescr(resultRelInfo->ri_RelationDesc), 64)))); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-209'], 'message': 'Fix column-privilege leak in error-message paths While building error messages to return to the user, BuildIndexValueDescription, ExecBuildSlotValueDescription and ri_ReportViolation would happily include the entire key or entire row in the result returned to the user, even if the user didn't have access to view all of the columns being included. Instead, include only those columns which the user is providing or which the user has select rights on. If the user does not have any rights to view the table or any of the columns involved then no detail is provided and a NULL value is returned from BuildIndexValueDescription and ExecBuildSlotValueDescription. Note that, for key cases, the user must have access to all of the columns for the key to be shown; a partial key will not be returned. Further, in master only, do not return any data for cases where row security is enabled on the relation and row security should be applied for the user. This required a bit of refactoring and moving of things around related to RLS- note the addition of utils/misc/rls.c. Back-patch all the way, as column-level privileges are now in all supported versions. This has been assigned CVE-2014-8161, but since the issue and the patch have already been publicized on pgsql-hackers, there's no point in trying to hide this commit.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: open_patch_file (char const *filename) { file_offset file_pos = 0; file_offset pos; struct stat st; if (!filename || !*filename || strEQ (filename, "-")) pfp = stdin; else { pfp = fopen (filename, binary_transput ? "rb" : "r"); if (!pfp) pfatal ("Can't open patch file %s", quotearg (filename)); } #if HAVE_SETMODE_DOS if (binary_transput) { if (isatty (fileno (pfp))) fatal ("cannot read binary data from tty on this platform"); setmode (fileno (pfp), O_BINARY); } #endif if (fstat (fileno (pfp), &st) != 0) pfatal ("fstat"); if (S_ISREG (st.st_mode) && (pos = file_tell (pfp)) != -1) file_pos = pos; else { size_t charsread; int fd = make_tempfile (&TMPPATNAME, 'p', NULL, O_RDWR | O_BINARY, 0); FILE *read_pfp = pfp; TMPPATNAME_needs_removal = true; pfp = fdopen (fd, "w+b"); if (! pfp) pfatal ("Can't open stream for file %s", quotearg (TMPPATNAME)); for (st.st_size = 0; (charsread = fread (buf, 1, bufsize, read_pfp)) != 0; st.st_size += charsread) if (fwrite (buf, 1, charsread, pfp) != charsread) write_fatal (); if (ferror (read_pfp) || fclose (read_pfp) != 0) read_fatal (); if (fflush (pfp) != 0 || file_seek (pfp, (file_offset) 0, SEEK_SET) != 0) write_fatal (); } p_filesize = st.st_size; if (p_filesize != (file_offset) p_filesize) fatal ("patch file is too long"); next_intuit_at (file_pos, 1); set_hunkmax(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Fail when out of memory in set_hunkmax() src/pch.c (another_hunk): Call set_hunkmax() from here to make sure it is called even when falling back from plan A to plan B. (open_patch_file): No need to call set_hunkmax() anymore. src/pch.c (set_hunkmax): Fail when out of memory. Make static. src/pch.h: Remove set_hunkmax() prototype.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: NUM_numpart_to_char(NUMProc *Np, int id) { int end; if (IS_ROMAN(Np->Num)) return; /* Note: in this elog() output not set '\0' in 'inout' */ #ifdef DEBUG_TO_FROM_CHAR /* * Np->num_curr is number of current item in format-picture, it is not * current position in inout! */ elog(DEBUG_elog_output, "SIGN_WROTE: %d, CURRENT: %d, NUMBER_P: \"%s\", INOUT: \"%s\"", Np->sign_wrote, Np->num_curr, Np->number_p, Np->inout); #endif Np->num_in = FALSE; /* * Write sign if real number will write to output Note: IS_PREDEC_SPACE() * handle "9.9" --> " .1" */ if (Np->sign_wrote == FALSE && (Np->num_curr >= Np->out_pre_spaces || (IS_ZERO(Np->Num) && Np->Num->zero_start == Np->num_curr)) && (IS_PREDEC_SPACE(Np) == FALSE || (Np->last_relevant && *Np->last_relevant == '.'))) { if (IS_LSIGN(Np->Num)) { if (Np->Num->lsign == NUM_LSIGN_PRE) { if (Np->sign == '-') strcpy(Np->inout_p, Np->L_negative_sign); else strcpy(Np->inout_p, Np->L_positive_sign); Np->inout_p += strlen(Np->inout_p); Np->sign_wrote = TRUE; } } else if (IS_BRACKET(Np->Num)) { *Np->inout_p = Np->sign == '+' ? ' ' : '<'; ++Np->inout_p; Np->sign_wrote = TRUE; } else if (Np->sign == '+') { if (!IS_FILLMODE(Np->Num)) { *Np->inout_p = ' '; /* Write + */ ++Np->inout_p; } Np->sign_wrote = TRUE; } else if (Np->sign == '-') { /* Write - */ *Np->inout_p = '-'; ++Np->inout_p; Np->sign_wrote = TRUE; } } /* * digits / FM / Zero / Dec. point */ if (id == NUM_9 || id == NUM_0 || id == NUM_D || id == NUM_DEC) { if (Np->num_curr < Np->out_pre_spaces && (Np->Num->zero_start > Np->num_curr || !IS_ZERO(Np->Num))) { /* * Write blank space */ if (!IS_FILLMODE(Np->Num)) { *Np->inout_p = ' '; /* Write ' ' */ ++Np->inout_p; } } else if (IS_ZERO(Np->Num) && Np->num_curr < Np->out_pre_spaces && Np->Num->zero_start <= Np->num_curr) { /* * Write ZERO */ *Np->inout_p = '0'; /* Write '0' */ ++Np->inout_p; Np->num_in = TRUE; } else { /* * Write Decimal point */ if (*Np->number_p == '.') { if (!Np->last_relevant || *Np->last_relevant != '.') { strcpy(Np->inout_p, Np->decimal); /* Write DEC/D */ Np->inout_p += strlen(Np->inout_p); } /* * Ora 'n' -- FM9.9 --> 'n.' */ else if (IS_FILLMODE(Np->Num) && Np->last_relevant && *Np->last_relevant == '.') { strcpy(Np->inout_p, Np->decimal); /* Write DEC/D */ Np->inout_p += strlen(Np->inout_p); } } else { /* * Write Digits */ if (Np->last_relevant && Np->number_p > Np->last_relevant && id != NUM_0) ; /* * '0.1' -- 9.9 --> ' .1' */ else if (IS_PREDEC_SPACE(Np)) { if (!IS_FILLMODE(Np->Num)) { *Np->inout_p = ' '; ++Np->inout_p; } /* * '0' -- FM9.9 --> '0.' */ else if (Np->last_relevant && *Np->last_relevant == '.') { *Np->inout_p = '0'; ++Np->inout_p; } } else { *Np->inout_p = *Np->number_p; /* Write DIGIT */ ++Np->inout_p; Np->num_in = TRUE; } } ++Np->number_p; } end = Np->num_count + (Np->out_pre_spaces ? 1 : 0) + (IS_DECIMAL(Np->Num) ? 1 : 0); if (Np->last_relevant && Np->last_relevant == Np->number_p) end = Np->num_curr; if (Np->num_curr + 1 == end) { if (Np->sign_wrote == TRUE && IS_BRACKET(Np->Num)) { *Np->inout_p = Np->sign == '+' ? ' ' : '>'; ++Np->inout_p; } else if (IS_LSIGN(Np->Num) && Np->Num->lsign == NUM_LSIGN_POST) { if (Np->sign == '-') strcpy(Np->inout_p, Np->L_negative_sign); else strcpy(Np->inout_p, Np->L_positive_sign); Np->inout_p += strlen(Np->inout_p); } } } ++Np->num_curr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'to_char(): prevent accesses beyond the allocated buffer Previously very long field masks for floats could access memory beyond the existing buffer allocated to hold the result. Reported by Andres Freund and Peter Geoghegan. Backpatch to all supported versions. Security: CVE-2015-0241'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pq_getstring(StringInfo s) { int i; resetStringInfo(s); /* Read until we get the terminating '\0' */ for (;;) { while (PqRecvPointer >= PqRecvLength) { if (pq_recvbuf()) /* If nothing in buffer, then recv some */ return EOF; /* Failed to recv data */ } for (i = PqRecvPointer; i < PqRecvLength; i++) { if (PqRecvBuffer[i] == '\0') { /* include the '\0' in the copy */ appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer, i - PqRecvPointer + 1); PqRecvPointer = i + 1; /* advance past \0 */ return 0; } } /* If we're here we haven't got the \0 in the buffer yet. */ appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer, PqRecvLength - PqRecvPointer); PqRecvPointer = PqRecvLength; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-89'], 'message': 'Be more careful to not lose sync in the FE/BE protocol. If any error occurred while we were in the middle of reading a protocol message from the client, we could lose sync, and incorrectly try to interpret a part of another message as a new protocol message. That will usually lead to an "invalid frontend message" error that terminates the connection. However, this is a security issue because an attacker might be able to deliberately cause an error, inject a Query message in what's supposed to be just user data, and have the server execute it. We were quite careful to not have CHECK_FOR_INTERRUPTS() calls or other operations that could ereport(ERROR) in the middle of processing a message, but a query cancel interrupt or statement timeout could nevertheless cause it to happen. Also, the V2 fastpath and COPY handling were not so careful. It's very difficult to recover in the V2 COPY protocol, so we will just terminate the connection on error. In practice, that's what happened previously anyway, as we lost protocol sync. To fix, add a new variable in pqcomm.c, PqCommReadingMsg, that is set whenever we're in the middle of reading a message. When it's set, we cannot safely ERROR out and continue running, because we might've read only part of a message. PqCommReadingMsg acts somewhat similarly to critical sections in that if an error occurs while it's set, the error handler will force the connection to be terminated, as if the error was FATAL. It's not implemented by promoting ERROR to FATAL in elog.c, like ERROR is promoted to PANIC in critical sections, because we want to be able to use PG_TRY/CATCH to recover and regain protocol sync. pq_getmessage() takes advantage of that to prevent an OOM error from terminating the connection. To prevent unnecessary connection terminations, add a holdoff mechanism similar to HOLD/RESUME_INTERRUPTS() that can be used hold off query cancel interrupts, but still allow die interrupts. The rules on which interrupts are processed when are now a bit more complicated, so refactor ProcessInterrupts() and the calls to it in signal handlers so that the signal handlers always call it if ImmediateInterruptOK is set, and ProcessInterrupts() can decide to not do anything if the other conditions are not met. Reported by Emil Lenngren. Patch reviewed by Noah Misch and Andres Freund. Backpatch to all supported versions. Security: CVE-2015-0244'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pq_getbyte_if_available(unsigned char *c) { int r; if (PqRecvPointer < PqRecvLength) { *c = PqRecvBuffer[PqRecvPointer++]; return 1; } /* Put the socket into non-blocking mode */ socket_set_nonblocking(true); r = secure_read(MyProcPort, c, 1); if (r < 0) { /* * Ok if no data available without blocking or interrupted (though * EINTR really shouldn't happen with a non-blocking socket). Report * other errors. */ if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) r = 0; else { /* * Careful: an ereport() that tries to write to the client would * cause recursion to here, leading to stack overflow and core * dump! This message must go *only* to the postmaster log. */ ereport(COMMERROR, (errcode_for_socket_access(), errmsg("could not receive data from client: %m"))); r = EOF; } } else if (r == 0) { /* EOF detected */ r = EOF; } return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-89'], 'message': 'Be more careful to not lose sync in the FE/BE protocol. If any error occurred while we were in the middle of reading a protocol message from the client, we could lose sync, and incorrectly try to interpret a part of another message as a new protocol message. That will usually lead to an "invalid frontend message" error that terminates the connection. However, this is a security issue because an attacker might be able to deliberately cause an error, inject a Query message in what's supposed to be just user data, and have the server execute it. We were quite careful to not have CHECK_FOR_INTERRUPTS() calls or other operations that could ereport(ERROR) in the middle of processing a message, but a query cancel interrupt or statement timeout could nevertheless cause it to happen. Also, the V2 fastpath and COPY handling were not so careful. It's very difficult to recover in the V2 COPY protocol, so we will just terminate the connection on error. In practice, that's what happened previously anyway, as we lost protocol sync. To fix, add a new variable in pqcomm.c, PqCommReadingMsg, that is set whenever we're in the middle of reading a message. When it's set, we cannot safely ERROR out and continue running, because we might've read only part of a message. PqCommReadingMsg acts somewhat similarly to critical sections in that if an error occurs while it's set, the error handler will force the connection to be terminated, as if the error was FATAL. It's not implemented by promoting ERROR to FATAL in elog.c, like ERROR is promoted to PANIC in critical sections, because we want to be able to use PG_TRY/CATCH to recover and regain protocol sync. pq_getmessage() takes advantage of that to prevent an OOM error from terminating the connection. To prevent unnecessary connection terminations, add a holdoff mechanism similar to HOLD/RESUME_INTERRUPTS() that can be used hold off query cancel interrupts, but still allow die interrupts. The rules on which interrupts are processed when are now a bit more complicated, so refactor ProcessInterrupts() and the calls to it in signal handlers so that the signal handlers always call it if ImmediateInterruptOK is set, and ProcessInterrupts() can decide to not do anything if the other conditions are not met. Reported by Emil Lenngren. Patch reviewed by Noah Misch and Andres Freund. Backpatch to all supported versions. Security: CVE-2015-0244'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags) { Elf32_Phdr ph32; Elf64_Phdr ph64; size_t offset, len; unsigned char nbuf[BUFSIZ]; ssize_t bufsize; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } /* * Loop through all the program headers. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) == -1) { file_badread(ms); return -1; } off += size; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (xph_type != PT_NOTE) continue; /* * This is a PT_NOTE section; loop through all the notes * in the section. */ len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) { file_badread(ms); return -1; } offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, 4, flags); if (offset == 0) break; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-703'], 'message': 'Bail out on partial reads, from Alexander Cherepanov'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: keyid_from_fingerprint( const byte *fprint, size_t fprint_len, u32 *keyid ) { u32 dummy_keyid[2]; if( !keyid ) keyid = dummy_keyid; if (fprint_len != 20) { /* This is special as we have to lookup the key first. */ PKT_public_key pk; int rc; memset (&pk, 0, sizeof pk); rc = get_pubkey_byfprint (&pk, fprint, fprint_len); if( rc ) { log_error("Oops: keyid_from_fingerprint: no pubkey\n"); keyid[0] = 0; keyid[1] = 0; } else keyid_from_pk (&pk, keyid); } else { const byte *dp = fprint; keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ; keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ; } return keyid[1]; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars. * common/host2net.h (buf16_to_ulong, buf16_to_uint): New. (buf16_to_ushort, buf16_to_u16): New. (buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New. -- Commit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to avoid all sign extension on shift problems. Hanno Böck found a case with an invalid read due to this problem. To fix that once and for all almost all uses of "<< 24" and "<< 8" are changed by this patch to use an inline function from host2net.h. Signed-off-by: Werner Koch <wk@gnupg.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: keyid_from_pk (PKT_public_key *pk, u32 *keyid) { u32 lowbits; u32 dummy_keyid[2]; if (!keyid) keyid = dummy_keyid; if( pk->keyid[0] || pk->keyid[1] ) { keyid[0] = pk->keyid[0]; keyid[1] = pk->keyid[1]; lowbits = keyid[1]; } else { const byte *dp; gcry_md_hd_t md; md = do_fingerprint_md(pk); if(md) { dp = gcry_md_read ( md, 0 ); keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ; keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ; lowbits = keyid[1]; gcry_md_close (md); pk->keyid[0] = keyid[0]; pk->keyid[1] = keyid[1]; } else pk->keyid[0]=pk->keyid[1]=keyid[0]=keyid[1]=lowbits=0xFFFFFFFF; } return lowbits; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars. * common/host2net.h (buf16_to_ulong, buf16_to_uint): New. (buf16_to_ushort, buf16_to_u16): New. (buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New. -- Commit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to avoid all sign extension on shift problems. Hanno Böck found a case with an invalid read due to this problem. To fix that once and for all almost all uses of "<< 24" and "<< 8" are changed by this patch to use an inline function from host2net.h. Signed-off-by: Werner Koch <wk@gnupg.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_signature (IOBUF inp, int pkttype, unsigned long pktlen, PKT_signature * sig) { int md5_len = 0; unsigned n; int is_v4 = 0; int rc = 0; int i, ndata; if (pktlen < 16) { log_error ("packet(%d) too short\n", pkttype); if (list_mode) es_fputs (":signature packet: [too short]\n", listfp); goto leave; } sig->version = iobuf_get_noeof (inp); pktlen--; if (sig->version == 4) is_v4 = 1; else if (sig->version != 2 && sig->version != 3) { log_error ("packet(%d) with unknown version %d\n", pkttype, sig->version); if (list_mode) es_fputs (":signature packet: [unknown version]\n", listfp); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } if (!is_v4) { md5_len = iobuf_get_noeof (inp); pktlen--; } sig->sig_class = iobuf_get_noeof (inp); pktlen--; if (!is_v4) { sig->timestamp = read_32 (inp); pktlen -= 4; sig->keyid[0] = read_32 (inp); pktlen -= 4; sig->keyid[1] = read_32 (inp); pktlen -= 4; } sig->pubkey_algo = iobuf_get_noeof (inp); pktlen--; sig->digest_algo = iobuf_get_noeof (inp); pktlen--; sig->flags.exportable = 1; sig->flags.revocable = 1; if (is_v4) /* Read subpackets. */ { n = read_16 (inp); pktlen -= 2; /* Length of hashed data. */ if (n > 10000) { log_error ("signature packet: hashed data too long\n"); if (list_mode) es_fputs (":signature packet: [hashed data too long]\n", listfp); rc = GPG_ERR_INV_PACKET; goto leave; } if (n) { sig->hashed = xmalloc (sizeof (*sig->hashed) + n - 1); sig->hashed->size = n; sig->hashed->len = n; if (iobuf_read (inp, sig->hashed->data, n) != n) { log_error ("premature eof while reading " "hashed signature data\n"); if (list_mode) es_fputs (":signature packet: [premature eof]\n", listfp); rc = -1; goto leave; } pktlen -= n; } n = read_16 (inp); pktlen -= 2; /* Length of unhashed data. */ if (n > 10000) { log_error ("signature packet: unhashed data too long\n"); if (list_mode) es_fputs (":signature packet: [unhashed data too long]\n", listfp); rc = GPG_ERR_INV_PACKET; goto leave; } if (n) { sig->unhashed = xmalloc (sizeof (*sig->unhashed) + n - 1); sig->unhashed->size = n; sig->unhashed->len = n; if (iobuf_read (inp, sig->unhashed->data, n) != n) { log_error ("premature eof while reading " "unhashed signature data\n"); if (list_mode) es_fputs (":signature packet: [premature eof]\n", listfp); rc = -1; goto leave; } pktlen -= n; } } if (pktlen < 5) /* Sanity check. */ { log_error ("packet(%d) too short\n", pkttype); if (list_mode) es_fputs (":signature packet: [too short]\n", listfp); rc = GPG_ERR_INV_PACKET; goto leave; } sig->digest_start[0] = iobuf_get_noeof (inp); pktlen--; sig->digest_start[1] = iobuf_get_noeof (inp); pktlen--; if (is_v4 && sig->pubkey_algo) /* Extract required information. */ { const byte *p; size_t len; /* Set sig->flags.unknown_critical if there is a critical bit * set for packets which we do not understand. */ if (!parse_sig_subpkt (sig->hashed, SIGSUBPKT_TEST_CRITICAL, NULL) || !parse_sig_subpkt (sig->unhashed, SIGSUBPKT_TEST_CRITICAL, NULL)) sig->flags.unknown_critical = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_CREATED, NULL); if (p) sig->timestamp = buffer_to_u32 (p); else if (!(sig->pubkey_algo >= 100 && sig->pubkey_algo <= 110) && opt.verbose) log_info ("signature packet without timestamp\n"); p = parse_sig_subpkt2 (sig, SIGSUBPKT_ISSUER, NULL); if (p) { sig->keyid[0] = buffer_to_u32 (p); sig->keyid[1] = buffer_to_u32 (p + 4); } else if (!(sig->pubkey_algo >= 100 && sig->pubkey_algo <= 110) && opt.verbose) log_info ("signature packet without keyid\n"); p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_SIG_EXPIRE, NULL); if (p && buffer_to_u32 (p)) sig->expiredate = sig->timestamp + buffer_to_u32 (p); if (sig->expiredate && sig->expiredate <= make_timestamp ()) sig->flags.expired = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_POLICY, NULL); if (p) sig->flags.policy_url = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_KS, NULL); if (p) sig->flags.pref_ks = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_NOTATION, NULL); if (p) sig->flags.notation = 1; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_REVOCABLE, NULL); if (p && *p == 0) sig->flags.revocable = 0; p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_TRUST, &len); if (p && len == 2) { sig->trust_depth = p[0]; sig->trust_value = p[1]; /* Only look for a regexp if there is also a trust subpacket. */ sig->trust_regexp = parse_sig_subpkt (sig->hashed, SIGSUBPKT_REGEXP, &len); /* If the regular expression is of 0 length, there is no regular expression. */ if (len == 0) sig->trust_regexp = NULL; } /* We accept the exportable subpacket from either the hashed or unhashed areas as older versions of gpg put it in the unhashed area. In theory, anyway, we should never see this packet off of a local keyring. */ p = parse_sig_subpkt2 (sig, SIGSUBPKT_EXPORTABLE, NULL); if (p && *p == 0) sig->flags.exportable = 0; /* Find all revocation keys. */ if (sig->sig_class == 0x1F) parse_revkeys (sig); } if (list_mode) { es_fprintf (listfp, ":signature packet: algo %d, keyid %08lX%08lX\n" "\tversion %d, created %lu, md5len %d, sigclass 0x%02x\n" "\tdigest algo %d, begin of digest %02x %02x\n", sig->pubkey_algo, (ulong) sig->keyid[0], (ulong) sig->keyid[1], sig->version, (ulong) sig->timestamp, md5_len, sig->sig_class, sig->digest_algo, sig->digest_start[0], sig->digest_start[1]); if (is_v4) { parse_sig_subpkt (sig->hashed, SIGSUBPKT_LIST_HASHED, NULL); parse_sig_subpkt (sig->unhashed, SIGSUBPKT_LIST_UNHASHED, NULL); } } ndata = pubkey_get_nsig (sig->pubkey_algo); if (!ndata) { if (list_mode) es_fprintf (listfp, "\tunknown algorithm %d\n", sig->pubkey_algo); unknown_pubkey_warning (sig->pubkey_algo); /* We store the plain material in data[0], so that we are able * to write it back with build_packet(). */ if (pktlen > (5 * MAX_EXTERN_MPI_BITS / 8)) { /* We include a limit to avoid too trivial DoS attacks by having gpg allocate too much memory. */ log_error ("signature packet: too much data\n"); rc = GPG_ERR_INV_PACKET; } else { sig->data[0] = gcry_mpi_set_opaque (NULL, read_rest (inp, pktlen), pktlen * 8); pktlen = 0; } } else { for (i = 0; i < ndata; i++) { n = pktlen; sig->data[i] = mpi_read (inp, &n, 0); pktlen -= n; if (list_mode) { es_fprintf (listfp, "\tdata: "); mpi_print (listfp, sig->data[i], mpi_print_mode); es_putc ('\n', listfp); } if (!sig->data[i]) rc = GPG_ERR_INV_PACKET; } } leave: iobuf_skip_rest (inp, pktlen, 0); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars. * common/host2net.h (buf16_to_ulong, buf16_to_uint): New. (buf16_to_ushort, buf16_to_u16): New. (buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New. -- Commit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to avoid all sign extension on shift problems. Hanno Böck found a case with an invalid read due to this problem. To fix that once and for all almost all uses of "<< 24" and "<< 8" are changed by this patch to use an inline function from host2net.h. Signed-off-by: Werner Koch <wk@gnupg.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: getsrv (const char *name,struct srventry **list) { int srvcount=0; u16 count; int i, rc; *list = NULL; #ifdef USE_ADNS { adns_state state; adns_answer *answer = NULL; rc = adns_init (&state, adns_if_noerrprint, NULL); if (rc) { log_error ("error initializing adns: %s\n", strerror (errno)); return -1; } rc = adns_synchronous (state, name, adns_r_srv, adns_qf_quoteok_query, &answer); if (rc) { log_error ("DNS query failed: %s\n", strerror (errno)); adns_finish (state); return -1; } if (answer->status != adns_s_ok || answer->type != adns_r_srv || !answer->nrrs) { log_error ("DNS query returned an error or no records: %s (%s)\n", adns_strerror (answer->status), adns_errabbrev (answer->status)); adns_free (answer); adns_finish (state); return 0; } for (count = 0; count < answer->nrrs; count++) { struct srventry *srv = NULL; struct srventry *newlist; if (strlen (answer->rrs.srvha[count].ha.host) >= MAXDNAME) { log_info ("hostname in SRV record too long - skipped\n"); continue; } newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry)); if (!newlist) goto fail; *list = newlist; memset (&(*list)[srvcount], 0, sizeof(struct srventry)); srv = &(*list)[srvcount]; srvcount++; srv->priority = answer->rrs.srvha[count].priority; srv->weight = answer->rrs.srvha[count].weight; srv->port = answer->rrs.srvha[count].port; strcpy (srv->target, answer->rrs.srvha[count].ha.host); } adns_free (answer); adns_finish (state); } #else /*!USE_ADNS*/ { unsigned char answer[2048]; HEADER *header = (HEADER *)answer; unsigned char *pt, *emsg; int r; u16 dlen; r = res_query (name, C_IN, T_SRV, answer, sizeof answer); if (r < sizeof (HEADER) || r > sizeof answer) return -1; if (header->rcode != NOERROR || !(count=ntohs (header->ancount))) return 0; /* Error or no record found. */ emsg = &answer[r]; pt = &answer[sizeof(HEADER)]; /* Skip over the query */ rc = dn_skipname (pt, emsg); if (rc == -1) goto fail; pt += rc + QFIXEDSZ; while (count-- > 0 && pt < emsg) { struct srventry *srv=NULL; u16 type,class; struct srventry *newlist; newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry)); if (!newlist) goto fail; *list = newlist; memset(&(*list)[srvcount],0,sizeof(struct srventry)); srv=&(*list)[srvcount]; srvcount++; rc = dn_skipname(pt,emsg); /* the name we just queried for */ if (rc == -1) goto fail; pt+=rc; /* Truncated message? */ if((emsg-pt)<16) goto fail; type=*pt++ << 8; type|=*pt++; /* We asked for SRV and got something else !? */ if(type!=T_SRV) goto fail; class=*pt++ << 8; class|=*pt++; /* We asked for IN and got something else !? */ if(class!=C_IN) goto fail; pt+=4; /* ttl */ dlen=*pt++ << 8; dlen|=*pt++; srv->priority=*pt++ << 8; srv->priority|=*pt++; srv->weight=*pt++ << 8; srv->weight|=*pt++; srv->port=*pt++ << 8; srv->port|=*pt++; /* Get the name. 2782 doesn't allow name compression, but dn_expand still works to pull the name out of the packet. */ rc = dn_expand(answer,emsg,pt,srv->target,MAXDNAME); if (rc == 1 && srv->target[0] == 0) /* "." */ { xfree(*list); *list = NULL; return 0; } if (rc == -1) goto fail; pt += rc; /* Corrupt packet? */ if (dlen != rc+6) goto fail; } } #endif /*!USE_ADNS*/ /* Now we have an array of all the srv records. */ /* Order by priority */ qsort(*list,srvcount,sizeof(struct srventry),priosort); /* For each priority, move the zero-weighted items first. */ for (i=0; i < srvcount; i++) { int j; for (j=i;j < srvcount && (*list)[i].priority == (*list)[j].priority; j++) { if((*list)[j].weight==0) { /* Swap j with i */ if(j!=i) { struct srventry temp; memcpy (&temp,&(*list)[j],sizeof(struct srventry)); memcpy (&(*list)[j],&(*list)[i],sizeof(struct srventry)); memcpy (&(*list)[i],&temp,sizeof(struct srventry)); } break; } } } /* Run the RFC-2782 weighting algorithm. We don't need very high quality randomness for this, so regular libc srand/rand is sufficient. Fixme: It is a bit questionaly to reinitalize srand - better use a gnupg fucntion for this. */ srand(time(NULL)*getpid()); for (i=0; i < srvcount; i++) { int j; float prio_count=0,chose; for (j=i; j < srvcount && (*list)[i].priority == (*list)[j].priority; j++) { prio_count+=(*list)[j].weight; (*list)[j].run_count=prio_count; } chose=prio_count*rand()/RAND_MAX; for (j=i;j<srvcount && (*list)[i].priority==(*list)[j].priority;j++) { if (chose<=(*list)[j].run_count) { /* Swap j with i */ if(j!=i) { struct srventry temp; memcpy(&temp,&(*list)[j],sizeof(struct srventry)); memcpy(&(*list)[j],&(*list)[i],sizeof(struct srventry)); memcpy(&(*list)[i],&temp,sizeof(struct srventry)); } break; } } } return srvcount; fail: xfree(*list); *list=NULL; return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars. * common/host2net.h (buf16_to_ulong, buf16_to_uint): New. (buf16_to_ushort, buf16_to_u16): New. (buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New. -- Commit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to avoid all sign extension on shift problems. Hanno Böck found a case with an invalid read due to this problem. To fix that once and for all almost all uses of "<< 24" and "<< 8" are changed by this patch to use an inline function from host2net.h. Signed-off-by: Werner Koch <wk@gnupg.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: next_packet (unsigned char const **bufptr, size_t *buflen, unsigned char const **r_data, size_t *r_datalen, int *r_pkttype, size_t *r_ntotal) { const unsigned char *buf = *bufptr; size_t len = *buflen; int c, ctb, pkttype; unsigned long pktlen; if (!len) return gpg_error (GPG_ERR_NO_DATA); ctb = *buf++; len--; if ( !(ctb & 0x80) ) return gpg_error (GPG_ERR_INV_PACKET); /* Invalid CTB. */ pktlen = 0; if ((ctb & 0x40)) /* New style (OpenPGP) CTB. */ { pkttype = (ctb & 0x3f); if (!len) return gpg_error (GPG_ERR_INV_PACKET); /* No 1st length byte. */ c = *buf++; len--; if (pkttype == PKT_COMPRESSED) return gpg_error (GPG_ERR_UNEXPECTED); /* ... packet in a keyblock. */ if ( c < 192 ) pktlen = c; else if ( c < 224 ) { pktlen = (c - 192) * 256; if (!len) return gpg_error (GPG_ERR_INV_PACKET); /* No 2nd length byte. */ c = *buf++; len--; pktlen += c + 192; } else if (c == 255) { if (len <4 ) return gpg_error (GPG_ERR_INV_PACKET); /* No length bytes. */ pktlen = (*buf++) << 24; pktlen |= (*buf++) << 16; pktlen |= (*buf++) << 8; pktlen |= (*buf++); len -= 4; } else /* Partial length encoding is not allowed for key packets. */ return gpg_error (GPG_ERR_UNEXPECTED); } else /* Old style CTB. */ { int lenbytes; pktlen = 0; pkttype = (ctb>>2)&0xf; lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3)); if (!lenbytes) /* Not allowed in key packets. */ return gpg_error (GPG_ERR_UNEXPECTED); if (len < lenbytes) return gpg_error (GPG_ERR_INV_PACKET); /* Not enough length bytes. */ for (; lenbytes; lenbytes--) { pktlen <<= 8; pktlen |= *buf++; len--; } } /* Do some basic sanity check. */ switch (pkttype) { case PKT_SIGNATURE: case PKT_SECRET_KEY: case PKT_PUBLIC_KEY: case PKT_SECRET_SUBKEY: case PKT_MARKER: case PKT_RING_TRUST: case PKT_USER_ID: case PKT_PUBLIC_SUBKEY: case PKT_OLD_COMMENT: case PKT_ATTRIBUTE: case PKT_COMMENT: case PKT_GPG_CONTROL: break; /* Okay these are allowed packets. */ default: return gpg_error (GPG_ERR_UNEXPECTED); } if (pktlen == (unsigned long)(-1)) return gpg_error (GPG_ERR_INV_PACKET); if (pktlen > len) return gpg_error (GPG_ERR_INV_PACKET); /* Packet length header too long. */ *r_data = buf; *r_datalen = pktlen; *r_pkttype = pkttype; *r_ntotal = (buf - *bufptr) + pktlen; *bufptr = buf + pktlen; *buflen = len - pktlen; if (!*buflen) *bufptr = NULL; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Use inline functions to convert buffer data to scalars. * common/host2net.h (buf16_to_ulong, buf16_to_uint): New. (buf16_to_ushort, buf16_to_u16): New. (buf32_to_size_t, buf32_to_ulong, buf32_to_uint, buf32_to_u32): New. -- Commit 91b826a38880fd8a989318585eb502582636ddd8 was not enough to avoid all sign extension on shift problems. Hanno Böck found a case with an invalid read due to this problem. To fix that once and for all almost all uses of "<< 24" and "<< 8" are changed by this patch to use an inline function from host2net.h. Signed-off-by: Werner Koch <wk@gnupg.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xfs_attr_rmtval_set( struct xfs_da_args *args) { struct xfs_inode *dp = args->dp; struct xfs_mount *mp = dp->i_mount; struct xfs_bmbt_irec map; xfs_dablk_t lblkno; xfs_fileoff_t lfileoff = 0; __uint8_t *src = args->value; int blkcnt; int valuelen; int nmap; int error; int offset = 0; trace_xfs_attr_rmtval_set(args); /* * Find a "hole" in the attribute address space large enough for * us to drop the new attribute's value into. Because CRC enable * attributes have headers, we can't just do a straight byte to FSB * conversion and have to take the header space into account. */ blkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen); error = xfs_bmap_first_unused(args->trans, args->dp, blkcnt, &lfileoff, XFS_ATTR_FORK); if (error) return error; args->rmtblkno = lblkno = (xfs_dablk_t)lfileoff; args->rmtblkcnt = blkcnt; /* * Roll through the "value", allocating blocks on disk as required. */ while (blkcnt > 0) { int committed; /* * Allocate a single extent, up to the size of the value. */ xfs_bmap_init(args->flist, args->firstblock); nmap = 1; error = xfs_bmapi_write(args->trans, dp, (xfs_fileoff_t)lblkno, blkcnt, XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA, args->firstblock, args->total, &map, &nmap, args->flist); if (!error) { error = xfs_bmap_finish(&args->trans, args->flist, &committed); } if (error) { ASSERT(committed); args->trans = NULL; xfs_bmap_cancel(args->flist); return(error); } /* * bmap_finish() may have committed the last trans and started * a new one. We need the inode to be in all transactions. */ if (committed) xfs_trans_ijoin(args->trans, dp, 0); ASSERT(nmap == 1); ASSERT((map.br_startblock != DELAYSTARTBLOCK) && (map.br_startblock != HOLESTARTBLOCK)); lblkno += map.br_blockcount; blkcnt -= map.br_blockcount; /* * Start the next trans in the chain. */ error = xfs_trans_roll(&args->trans, dp); if (error) return (error); } /* * Roll through the "value", copying the attribute value to the * already-allocated blocks. Blocks are written synchronously * so that we can know they are all on disk before we turn off * the INCOMPLETE flag. */ lblkno = args->rmtblkno; blkcnt = args->rmtblkcnt; valuelen = args->valuelen; while (valuelen > 0) { struct xfs_buf *bp; xfs_daddr_t dblkno; int dblkcnt; ASSERT(blkcnt > 0); xfs_bmap_init(args->flist, args->firstblock); nmap = 1; error = xfs_bmapi_read(dp, (xfs_fileoff_t)lblkno, blkcnt, &map, &nmap, XFS_BMAPI_ATTRFORK); if (error) return(error); ASSERT(nmap == 1); ASSERT((map.br_startblock != DELAYSTARTBLOCK) && (map.br_startblock != HOLESTARTBLOCK)); dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock), dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount); bp = xfs_buf_get(mp->m_ddev_targp, dblkno, dblkcnt, 0); if (!bp) return ENOMEM; bp->b_ops = &xfs_attr3_rmt_buf_ops; xfs_attr_rmtval_copyin(mp, bp, args->dp->i_ino, &offset, &valuelen, &src); error = xfs_bwrite(bp); /* GROT: NOTE: synchronous write */ xfs_buf_relse(bp); if (error) return error; /* roll attribute extent map forwards */ lblkno += map.br_blockcount; blkcnt -= map.br_blockcount; } ASSERT(valuelen == 0); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <dchinner@redhat.com> Reviewed-by: Brian Foster <bfoster@redhat.com> Signed-off-by: Dave Chinner <david@fromorbit.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xfs_attr_calc_size( struct xfs_inode *ip, int namelen, int valuelen, int *local) { struct xfs_mount *mp = ip->i_mount; int size; int nblks; /* * Determine space new attribute will use, and if it would be * "local" or "remote" (note: local != inline). */ size = xfs_attr_leaf_newentsize(namelen, valuelen, mp->m_sb.sb_blocksize, local); nblks = XFS_DAENTER_SPACE_RES(mp, XFS_ATTR_FORK); if (*local) { if (size > (mp->m_sb.sb_blocksize >> 1)) { /* Double split possible */ nblks *= 2; } } else { /* * Out of line attribute, cannot double split, but * make room for the attribute value itself. */ uint dblocks = XFS_B_TO_FSB(mp, valuelen); nblks += dblocks; nblks += XFS_NEXTENTADD_SPACE_RES(mp, dblocks, XFS_ATTR_FORK); } return nblks; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <dchinner@redhat.com> Reviewed-by: Brian Foster <bfoster@redhat.com> Signed-off-by: Dave Chinner <david@fromorbit.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void mark_files_ro(struct super_block *sb) { struct file *f; lg_global_lock(&files_lglock); do_file_list_for_each_entry(sb, f) { if (!file_count(f)) continue; if (!(f->f_mode & FMODE_WRITE)) continue; spin_lock(&f->f_lock); f->f_mode &= ~FMODE_WRITE; spin_unlock(&f->f_lock); if (file_check_writeable(f) != 0) continue; __mnt_drop_write(f->f_path.mnt); file_release_write(f); } while_file_list_for_each_entry; lg_global_unlock(&files_lglock); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len) { while (!iov->iov_len) iov++; while (len > 0) { unsigned long this_len; this_len = min_t(unsigned long, len, iov->iov_len); fault_in_pages_readable(iov->iov_base, this_len); len -= this_len; iov++; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'new helper: copy_page_from_iter() parallel to copy_page_to_iter(). pipe_write() switched to it (and became ->write_iter()). Signed-off-by: Al Viro <viro@zeniv.linux.org.uk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline int xrstor_state_booting(struct xsave_struct *fx, u64 mask) { u32 lmask = mask; u32 hmask = mask >> 32; int err = 0; WARN_ON(system_state != SYSTEM_BOOTING); if (boot_cpu_has(X86_FEATURE_XSAVES)) asm volatile("1:"XRSTORS"\n\t" "2:\n\t" : : "D" (fx), "m" (*fx), "a" (lmask), "d" (hmask) : "memory"); else asm volatile("1:"XRSTOR"\n\t" "2:\n\t" : : "D" (fx), "m" (*fx), "a" (lmask), "d" (hmask) : "memory"); asm volatile(xstate_fault : "0" (0) : "memory"); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'x86/fpu/xsaves: Fix improper uses of __ex_table Commit: f31a9f7c7169 ("x86/xsaves: Use xsaves/xrstors to save and restore xsave area") introduced alternative instructions for XSAVES/XRSTORS and commit: adb9d526e982 ("x86/xsaves: Add xsaves and xrstors support for booting time") added support for the XSAVES/XRSTORS instructions at boot time. Unfortunately both failed to properly protect them against faulting: The 'xstate_fault' macro will use the closest label named '1' backward and that ends up in the .altinstr_replacement section rather than in .text. This means that the kernel will never find in the __ex_table the .text address where this instruction might fault, leading to serious problems if userspace manages to trigger the fault. Signed-off-by: Quentin Casasnovas <quentin.casasnovas@oracle.com> Signed-off-by: Jamie Iles <jamie.iles@oracle.com> [ Improved the changelog, fixed some whitespace noise. ] Acked-by: Borislav Petkov <bp@alien8.de> Acked-by: Linus Torvalds <torvalds@linux-foundation.org> Cc: <stable@vger.kernel.org> Cc: Allan Xavier <mr.a.xavier@gmail.com> Cc: H. Peter Anvin <hpa@zytor.com> Cc: Thomas Gleixner <tglx@linutronix.de> Fixes: adb9d526e982 ("x86/xsaves: Add xsaves and xrstors support for booting time") Fixes: f31a9f7c7169 ("x86/xsaves: Use xsaves/xrstors to save and restore xsave area") Signed-off-by: Ingo Molnar <mingo@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int basic_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC) { zval **login, **password; if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login"), (void **)&login) == SUCCESS && !zend_hash_exists(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest"))) { unsigned char* buf; int len; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login)); smart_str_appendc(&auth, ':'); if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password"), (void **)&password) == SUCCESS) { smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password)); } smart_str_0(&auth); buf = php_base64_encode((unsigned char*)auth.c, auth.len, &len); smart_str_append_const(soap_headers, "Authorization: Basic "); smart_str_appendl(soap_headers, (char*)buf, len); smart_str_append_const(soap_headers, "\r\n"); efree(buf); smart_str_free(&auth); return 1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'Added type checks'</s>
<s>[INST] Given the following code containing errors, provide 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 handle_sid_request(enum request_types request_type, const char *sid, struct berval **berval) { int ret; struct passwd pwd; struct passwd *pwd_result = NULL; struct group grp; struct group *grp_result = NULL; char *domain_name = NULL; char *fq_name = NULL; char *object_name = NULL; char *sep; size_t buf_len; char *buf = NULL; enum sss_id_type id_type; struct sss_nss_kv *kv_list = NULL; ret = sss_nss_getnamebysid(sid, &fq_name, &id_type); if (ret != 0) { if (ret == ENOENT) { ret = LDAP_NO_SUCH_OBJECT; } else { ret = LDAP_OPERATIONS_ERROR; } goto done; } sep = strchr(fq_name, SSSD_DOMAIN_SEPARATOR); if (sep == NULL) { ret = LDAP_OPERATIONS_ERROR; goto done; } object_name = strndup(fq_name, (sep - fq_name)); domain_name = strdup(sep + 1); if (object_name == NULL || domain_name == NULL) { ret = LDAP_OPERATIONS_ERROR; goto done; } if (request_type == REQ_SIMPLE) { ret = pack_ber_name(domain_name, object_name, berval); goto done; } ret = get_buffer(&buf_len, &buf); if (ret != LDAP_SUCCESS) { goto done; } switch(id_type) { case SSS_ID_TYPE_UID: case SSS_ID_TYPE_BOTH: ret = getpwnam_r(fq_name, &pwd, buf, buf_len, &pwd_result); if (ret != 0) { ret = LDAP_NO_SUCH_OBJECT; goto done; } if (pwd_result == NULL) { ret = LDAP_NO_SUCH_OBJECT; goto done; } if (request_type == REQ_FULL_WITH_GROUPS) { ret = sss_nss_getorigbyname(pwd.pw_name, &kv_list, &id_type); if (ret != 0 || !(id_type == SSS_ID_TYPE_UID || id_type == SSS_ID_TYPE_BOTH)) { if (ret == ENOENT) { ret = LDAP_NO_SUCH_OBJECT; } else { ret = LDAP_OPERATIONS_ERROR; } goto done; } } ret = pack_ber_user((request_type == REQ_FULL ? RESP_USER : RESP_USER_GROUPLIST), domain_name, pwd.pw_name, pwd.pw_uid, pwd.pw_gid, pwd.pw_gecos, pwd.pw_dir, pwd.pw_shell, kv_list, berval); break; case SSS_ID_TYPE_GID: ret = getgrnam_r(fq_name, &grp, buf, buf_len, &grp_result); if (ret != 0) { ret = LDAP_NO_SUCH_OBJECT; goto done; } if (grp_result == NULL) { ret = LDAP_NO_SUCH_OBJECT; goto done; } if (request_type == REQ_FULL_WITH_GROUPS) { ret = sss_nss_getorigbyname(grp.gr_name, &kv_list, &id_type); if (ret != 0 || !(id_type == SSS_ID_TYPE_GID || id_type == SSS_ID_TYPE_BOTH)) { if (ret == ENOENT) { ret = LDAP_NO_SUCH_OBJECT; } else { ret = LDAP_OPERATIONS_ERROR; } goto done; } } ret = pack_ber_group((request_type == REQ_FULL ? RESP_GROUP : RESP_GROUP_MEMBERS), domain_name, grp.gr_name, grp.gr_gid, grp.gr_mem, kv_list, berval); break; default: ret = LDAP_OPERATIONS_ERROR; goto done; } done: sss_nss_free_kv(kv_list); free(fq_name); free(object_name); free(domain_name); free(buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'extdom: handle ERANGE return code for getXXYYY_r() calls The getXXYYY_r() calls require a buffer to store the variable data of the passwd and group structs. If the provided buffer is too small ERANGE is returned and the caller can try with a larger buffer again. Cmocka/cwrap based unit-tests for get*_r_wrapper() are added. Resolves https://fedorahosted.org/freeipa/ticket/4908 Reviewed-By: Alexander Bokovoy <abokovoy@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ipa_extdom_init_ctx(Slapi_PBlock *pb, struct ipa_extdom_ctx **_ctx) { struct ipa_extdom_ctx *ctx; Slapi_Entry *e; int ret; ctx = calloc(1, sizeof(struct ipa_extdom_ctx)); if (!ctx) { return LDAP_OPERATIONS_ERROR; } ret = slapi_pblock_get(pb, SLAPI_PLUGIN_IDENTITY, &ctx->plugin_id); if ((ret != 0) || (NULL == ctx->plugin_id)) { LOG_FATAL("Could not get identity or identity was NULL\n"); if (ret == 0) { ret = -1; } goto done; } slapi_pblock_get(pb, SLAPI_PLUGIN_CONFIG_ENTRY, &e); if (!e) { LOG_FATAL("Plugin configuration not found!\n"); ret = -1; goto done; } ctx->base_dn = slapi_entry_attr_get_charptr(e, "nsslapd-basedn"); if (!ctx->base_dn) { LOG_FATAL("Base DN not found in plugin configuration not found!\n"); ret = -1; goto done; } done: if (ret) { free(ctx); } else { *_ctx = ctx; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'extdom: make nss buffer configurable The get*_r_wrapper() calls expect a maximum buffer size to avoid memory shortage if too many threads try to allocate buffers e.g. for large groups. With this patch this size can be configured by setting ipaExtdomMaxNssBufSize in the plugin config object cn=ipa_extdom_extop,cn=plugins,cn=config. Related to https://fedorahosted.org/freeipa/ticket/4908 Reviewed-By: Alexander Bokovoy <abokovoy@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlBufAdd(xmlBufPtr buf, const xmlChar *str, int len) { unsigned int needSize; if ((str == NULL) || (buf == NULL) || (buf->error)) return -1; CHECK_COMPAT(buf) if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return -1; if (len < -1) { #ifdef DEBUG_BUFFER xmlGenericError(xmlGenericErrorContext, "xmlBufAdd: len < 0\n"); #endif return -1; } if (len == 0) return 0; if (len < 0) len = xmlStrlen(str); if (len < 0) return -1; if (len == 0) return 0; needSize = buf->use + len + 2; if (needSize > buf->size){ if (!xmlBufResize(buf, needSize)){ xmlBufMemoryError(buf, "growing buffer"); return XML_ERR_NO_MEMORY; } } memmove(&buf->content[buf->use], str, len*sizeof(xmlChar)); buf->use += len; buf->content[buf->use] = 0; UPDATE_COMPAT(buf) return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2015-1819 Enforce the reader to run in constant memory One of the operation on the reader could resolve entities leading to the classic expansion issue. Make sure the buffer used for xmlreader operation is bounded. Introduce a new allocation type for the buffers for this effect.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, "/") != 0) ? rootdir : NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } #endif /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'ccpp: do not read data from root directories Users are allowed to modify /proc/[pid]/root to any directory by running their own MOUNT namespace. Related: #1211835 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen("/dev/null", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die("Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = "SIGNO CORE_SIZE_LIMIT PID ..." * argv[2] = "CORE_SIZE_LIMIT PID ..." * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file("CCpp.conf", settings); const char *value; value = get_map_string_item_or_NULL(settings, "MakeCompatCore"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "SaveBinaryImage"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, "VerboseLog"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die("PID '%s' or limit '%s' is bogus", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN"/abrt/saved_core_pattern"); /* If we have a saved pattern and it's not a "|PROG ARGS" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, "/abrt-hook-ccpp")) { error_msg_and_die("PID %lu is '%s', not dumping it to avoid recursion", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice("user_pwd:'%s'", user_pwd); sprintf(path, "/proc/%lu/status", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks "user_pwd == NULL" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg("Can't read /proc/%lu/exe link", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = "ILL" ; break; case SIGFPE : signame = "FPE" ; break; case SIGSEGV: signame = "SEGV"; break; case SIGBUS : signame = "BUS" ; break; //Bus error (bad memory access) case SIGABRT: signame = "ABRT"; break; //usually when abort() was called // We have real-world reports from users who see buggy programs // dying with SIGTRAP, uncommented it too: case SIGTRAP: signame = "TRAP"; break; //Trace/breakpoint trap // These usually aren't caused by bugs: //case SIGQUIT: signame = "QUIT"; break; //Quit from keyboard //case SIGSYS : signame = "SYS" ; break; //Bad argument to routine (SVr4) //case SIGXCPU: signame = "XCPU"; break; //CPU time limit exceeded (4.2BSD) //case SIGXFSZ: signame = "XFSZ"; break; //File size limit exceeded (4.2BSD) default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log("abrtd is not running. If it crashed, " "/proc/sys/kernel/core_pattern contains a stale value, " "consider resetting it to 'core'" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), "%s/last-ccpp", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, "abrt", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), "%s/%s-coredump", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error saving '%s'", path); } log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), "%s/ccpp-%s-%lu.new", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof("/"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt * * dd_create_skeleton() creates a new directory and leaves ownership to * the current user, hence, we have to call dd_reset_ownership() after the * directory is populated. */ dd = dd_create_skeleton(path, fsuid, DEFAULT_DUMP_DIR_MODE, /*no flags*/0); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, NULL); char source_filename[sizeof("/proc/%lu/somewhat_long_name") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, "/proc/%lu/smaps", (long)pid); source_base_ofs -= strlen("smaps"); char *dest_filename = concat_path_file(dd->dd_dirname, "also_somewhat_longish_name"); char *dest_base = strrchr(dest_filename, '/') + 1; // Disabled for now: /proc/PID/smaps tends to be BIG, // and not much more informative than /proc/PID/maps: //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "maps"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "limits"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, "cgroup"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, "CCpp"); dd_save_text(dd, FILENAME_TYPE, "CCpp"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, "/") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf("%s killed by SIG%s", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : ""); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : ""); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); if (fips_enabled) { if (strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, "/"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd_binary); } strcpy(path + path_len, "/"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include<signal.h>\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die("Error writing '%s'", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf("%s/hs_err_pid%lu.log", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, "/hs_err.log"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die("Error saving '%s'", path); } close(src_fd); } } #endif /* And finally set the right uid and gid */ dd_reset_ownership(dd); /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(".new")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log("Saved core dump of pid %lu (%s) to %s (%llu bytes)", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: "abrt going crazy when crashing process is respawned" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't "fight" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg("Error writing '%s'", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log("Saved core dump of pid %lu to %s (%llu bytes)", (long)pid, full_core_basename, (long long)core_size); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'ccpp: do not override existing files by compat cores Implement all checks used in kernel's do_coredump() and require non-relative path if suid_dumpable is 2. Related: #1212818 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>