text
stringlengths
481
107k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int credssp_server_authenticate(rdpCredssp* credssp) { UINT32 cbMaxToken; ULONG fContextReq; ULONG pfContextAttr; SECURITY_STATUS status; CredHandle credentials; TimeStamp expiration; PSecPkgInfo pPackageInfo; SecBuffer input_buffer; SecBuffer output_buffer; SecBufferDesc input_buffer_desc; SecBufferDesc output_buffer_desc; BOOL have_context; BOOL have_input_buffer; BOOL have_pub_key_auth; sspi_GlobalInit(); if (credssp_ntlm_server_init(credssp) == 0) return 0; #ifdef WITH_NATIVE_SSPI if (!credssp->SspiModule) credssp->SspiModule = _tcsdup(_T("secur32.dll")); #endif if (credssp->SspiModule) { HMODULE hSSPI; INIT_SECURITY_INTERFACE pInitSecurityInterface; hSSPI = LoadLibrary(credssp->SspiModule); if (!hSSPI) { _tprintf(_T("Failed to load SSPI module: %s\n"), credssp->SspiModule); return 0; } #ifdef UNICODE pInitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceW"); #else pInitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress(hSSPI, "InitSecurityInterfaceA"); #endif credssp->table = (*pInitSecurityInterface)(); } #ifndef WITH_NATIVE_SSPI else { credssp->table = InitSecurityInterface(); } #endif status = credssp->table->QuerySecurityPackageInfo(NLA_PKG_NAME, &pPackageInfo); if (status != SEC_E_OK) { fprintf(stderr, "QuerySecurityPackageInfo status: 0x%08X\n", status); return 0; } cbMaxToken = pPackageInfo->cbMaxToken; status = credssp->table->AcquireCredentialsHandle(NULL, NLA_PKG_NAME, SECPKG_CRED_INBOUND, NULL, NULL, NULL, NULL, &credentials, &expiration); if (status != SEC_E_OK) { fprintf(stderr, "AcquireCredentialsHandle status: 0x%08X\n", status); return 0; } have_context = FALSE; have_input_buffer = FALSE; have_pub_key_auth = FALSE; ZeroMemory(&input_buffer, sizeof(SecBuffer)); ZeroMemory(&output_buffer, sizeof(SecBuffer)); ZeroMemory(&input_buffer_desc, sizeof(SecBufferDesc)); ZeroMemory(&output_buffer_desc, sizeof(SecBufferDesc)); ZeroMemory(&credssp->ContextSizes, sizeof(SecPkgContext_Sizes)); /* * from tspkg.dll: 0x00000112 * ASC_REQ_MUTUAL_AUTH * ASC_REQ_CONFIDENTIALITY * ASC_REQ_ALLOCATE_MEMORY */ fContextReq = 0; fContextReq |= ASC_REQ_MUTUAL_AUTH; fContextReq |= ASC_REQ_CONFIDENTIALITY; fContextReq |= ASC_REQ_CONNECTION; fContextReq |= ASC_REQ_USE_SESSION_KEY; fContextReq |= ASC_REQ_REPLAY_DETECT; fContextReq |= ASC_REQ_SEQUENCE_DETECT; fContextReq |= ASC_REQ_EXTENDED_ERROR; while (TRUE) { input_buffer_desc.ulVersion = SECBUFFER_VERSION; input_buffer_desc.cBuffers = 1; input_buffer_desc.pBuffers = &input_buffer; input_buffer.BufferType = SECBUFFER_TOKEN; /* receive authentication token */ input_buffer_desc.ulVersion = SECBUFFER_VERSION; input_buffer_desc.cBuffers = 1; input_buffer_desc.pBuffers = &input_buffer; input_buffer.BufferType = SECBUFFER_TOKEN; if (credssp_recv(credssp) < 0) return -1; #ifdef WITH_DEBUG_CREDSSP fprintf(stderr, "Receiving Authentication Token\n"); credssp_buffer_print(credssp); #endif input_buffer.pvBuffer = credssp->negoToken.pvBuffer; input_buffer.cbBuffer = credssp->negoToken.cbBuffer; if (credssp->negoToken.cbBuffer < 1) { fprintf(stderr, "CredSSP: invalid negoToken!\n"); return -1; } output_buffer_desc.ulVersion = SECBUFFER_VERSION; output_buffer_desc.cBuffers = 1; output_buffer_desc.pBuffers = &output_buffer; output_buffer.BufferType = SECBUFFER_TOKEN; output_buffer.cbBuffer = cbMaxToken; output_buffer.pvBuffer = malloc(output_buffer.cbBuffer); status = credssp->table->AcceptSecurityContext(&credentials, have_context? &credssp->context: NULL, &input_buffer_desc, fContextReq, SECURITY_NATIVE_DREP, &credssp->context, &output_buffer_desc, &pfContextAttr, &expiration); credssp->negoToken.pvBuffer = output_buffer.pvBuffer; credssp->negoToken.cbBuffer = output_buffer.cbBuffer; if ((status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED)) { if (credssp->table->CompleteAuthToken != NULL) credssp->table->CompleteAuthToken(&credssp->context, &output_buffer_desc); if (status == SEC_I_COMPLETE_NEEDED) status = SEC_E_OK; else if (status == SEC_I_COMPLETE_AND_CONTINUE) status = SEC_I_CONTINUE_NEEDED; } if (status == SEC_E_OK) { have_pub_key_auth = TRUE; if (credssp->table->QueryContextAttributes(&credssp->context, SECPKG_ATTR_SIZES, &credssp->ContextSizes) != SEC_E_OK) { fprintf(stderr, "QueryContextAttributes SECPKG_ATTR_SIZES failure\n"); return 0; } if (credssp_decrypt_public_key_echo(credssp) != SEC_E_OK) { fprintf(stderr, "Error: could not verify client's public key echo\n"); return -1; } sspi_SecBufferFree(&credssp->negoToken); credssp->negoToken.pvBuffer = NULL; credssp->negoToken.cbBuffer = 0; credssp_encrypt_public_key_echo(credssp); } if ((status != SEC_E_OK) && (status != SEC_I_CONTINUE_NEEDED)) { fprintf(stderr, "AcceptSecurityContext status: 0x%08X\n", status); return -1; } /* send authentication token */ #ifdef WITH_DEBUG_CREDSSP fprintf(stderr, "Sending Authentication Token\n"); credssp_buffer_print(credssp); #endif credssp_send(credssp); credssp_buffer_free(credssp); if (status != SEC_I_CONTINUE_NEEDED) break; have_context = TRUE; } /* Receive encrypted credentials */ if (credssp_recv(credssp) < 0) return -1; if (credssp_decrypt_ts_credentials(credssp) != SEC_E_OK) { fprintf(stderr, "Could not decrypt TSCredentials status: 0x%08X\n", status); return 0; } if (status != SEC_E_OK) { fprintf(stderr, "AcceptSecurityContext status: 0x%08X\n", status); return 0; } status = credssp->table->ImpersonateSecurityContext(&credssp->context); if (status != SEC_E_OK) { fprintf(stderr, "ImpersonateSecurityContext status: 0x%08X\n", status); return 0; } else { status = credssp->table->RevertSecurityContext(&credssp->context); if (status != SEC_E_OK) { fprintf(stderr, "RevertSecurityContext status: 0x%08X\n", status); return 0; } } credssp->table->FreeContextBuffer(pPackageInfo); return 1; } ; 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: BOOL ber_read_enumerated(wStream* s, BYTE* enumerated, BYTE count) { int length; if(!ber_read_universal_tag(s, BER_TAG_ENUMERATED, FALSE) || !ber_read_length(s, &length)) return FALSE; if (length != 1 || Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, *enumerated); /* check that enumerated value falls within expected range */ if (*enumerated + 1 > count) return FALSE; return TRUE; } ; 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: int ber_write_integer(wStream* s, UINT32 value) { ber_write_universal_tag(s, BER_TAG_INTEGER, FALSE); if (value < 0x80) { ber_write_length(s, 1); Stream_Write_UINT8(s, value); return 3; } else if (value < 0x8000) { ber_write_length(s, 2); Stream_Write_UINT16_BE(s, value); return 4; } else if (value < 0x800000) { ber_write_length(s, 3); Stream_Write_UINT8(s, (value >> 16)); Stream_Write_UINT16_BE(s, (value & 0xFFFF)); return 5; } else if (value < 0x80000000) { ber_write_length(s, 4); Stream_Write_UINT32_BE(s, value); return 6; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Finished merging missing changes from pull request #1257 (https://github.com/FreeRDP/FreeRDP/pull/1257 - commit 0dc22d5). Correctly report the length of ts_password_creds.'</s>
<s>[INST] Given the following code containing errors, provide 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* sspi_SecureHandleGetUpperPointer(SecHandle* handle) { void* pointer; if (!handle) return NULL; pointer = (void*) ~((size_t) handle->dwUpper); return pointer; } ; 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: xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, int terminate) { int end_in_lf = 0; int remain = 0; size_t old_avail = 0; size_t avail = 0; if (ctxt == NULL) return(XML_ERR_INTERNAL_ERROR); if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(ctxt->errNo); if (ctxt->instate == XML_PARSER_EOF) return(-1); if (ctxt->instate == XML_PARSER_START) xmlDetectSAX2(ctxt); if ((size > 0) && (chunk != NULL) && (!terminate) && (chunk[size - 1] == '\r')) { end_in_lf = 1; size--; } xmldecl_done: if ((size > 0) && (chunk != NULL) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->instate != XML_PARSER_EOF)) { size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input); size_t cur = ctxt->input->cur - ctxt->input->base; int res; old_avail = xmlBufUse(ctxt->input->buf->buffer); /* * Specific handling if we autodetected an encoding, we should not * push more than the first line ... which depend on the encoding * And only push the rest once the final encoding was detected */ if ((ctxt->instate == XML_PARSER_START) && (ctxt->input != NULL) && (ctxt->input->buf != NULL) && (ctxt->input->buf->encoder != NULL)) { unsigned int len = 45; if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UTF-16")) || (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UTF16"))) len = 90; else if ((xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UCS-4")) || (xmlStrcasestr(BAD_CAST ctxt->input->buf->encoder->name, BAD_CAST "UCS4"))) len = 180; if (ctxt->input->buf->rawconsumed < len) len -= ctxt->input->buf->rawconsumed; /* * Change size for reading the initial declaration only * if size is greater than len. Otherwise, memmove in xmlBufferAdd * will blindly copy extra bytes from memory. */ if ((unsigned int) size > len) { remain = size - len; size = len; } else { remain = 0; } } res = xmlParserInputBufferPush(ctxt->input->buf, size, chunk); if (res < 0) { ctxt->errNo = XML_PARSER_EOF; ctxt->disableSAX = 1; return (XML_PARSER_EOF); } xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, cur); #ifdef DEBUG_PUSH xmlGenericError(xmlGenericErrorContext, "PP: pushed %d\n", size); #endif } else if (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->input != NULL) && ctxt->input->buf != NULL) { xmlParserInputBufferPtr in = ctxt->input->buf; if ((in->encoder != NULL) && (in->buffer != NULL) && (in->raw != NULL)) { int nbchars; size_t base = xmlBufGetInputBase(in->buffer, ctxt->input); size_t current = ctxt->input->cur - ctxt->input->base; nbchars = xmlCharEncInput(in, terminate); if (nbchars < 0) { /* TODO 2.6.0 */ xmlGenericError(xmlGenericErrorContext, "xmlParseChunk: encoder error\n"); return(XML_ERR_INVALID_ENCODING); } xmlBufSetInputBaseCur(in->buffer, ctxt->input, base, current); } } } if (remain != 0) { xmlParseTryOrFinish(ctxt, 0); } else { if ((ctxt->input != NULL) && (ctxt->input->buf != NULL)) avail = xmlBufUse(ctxt->input->buf->buffer); /* * Depending on the current state it may not be such * a good idea to try parsing if there is nothing in the chunk * which would be worth doing a parser state transition and we * need to wait for more data */ if ((terminate) || (avail > XML_MAX_TEXT_LENGTH) || (old_avail == 0) || (avail == 0) || (xmlParseCheckTransition(ctxt, (const char *)&ctxt->input->base[old_avail], avail - old_avail))) xmlParseTryOrFinish(ctxt, terminate); } if ((ctxt->input != NULL) && (((ctxt->input->end - ctxt->input->cur) > XML_MAX_LOOKUP_LIMIT) || ((ctxt->input->cur - ctxt->input->base) > XML_MAX_LOOKUP_LIMIT)) && ((ctxt->options & XML_PARSE_HUGE) == 0)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "Huge input lookup"); ctxt->instate = XML_PARSER_EOF; } if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) return(ctxt->errNo); if (remain != 0) { chunk += size; size = remain; remain = 0; goto xmldecl_done; } if ((end_in_lf == 1) && (ctxt->input != NULL) && (ctxt->input->buf != NULL)) { size_t base = xmlBufGetInputBase(ctxt->input->buf->buffer, ctxt->input); size_t current = ctxt->input->cur - ctxt->input->base; xmlParserInputBufferPush(ctxt->input->buf, 1, "\r"); xmlBufSetInputBaseCur(ctxt->input->buf->buffer, ctxt->input, base, current); } if (terminate) { /* * Check for termination */ int cur_avail = 0; if (ctxt->input != NULL) { if (ctxt->input->buf == NULL) cur_avail = ctxt->input->length - (ctxt->input->cur - ctxt->input->base); else cur_avail = xmlBufUse(ctxt->input->buf->buffer) - (ctxt->input->cur - ctxt->input->base); } if ((ctxt->instate != XML_PARSER_EOF) && (ctxt->instate != XML_PARSER_EPILOG)) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } if ((ctxt->instate == XML_PARSER_EPILOG) && (cur_avail > 0)) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } if (ctxt->instate != XML_PARSER_EOF) { if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); } ctxt->instate = XML_PARSER_EOF; } if (ctxt->wellFormed == 0) return((xmlParserErrors) ctxt->errNo); else return(0); } ; 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: void _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes) { xml_parser *parser = (xml_parser *)userData; const char **attrs = (const char **) attributes; char *tag_name; char *att, *val; int val_len; zval *retval, *args[3]; if (parser) { parser->level++; tag_name = _xml_decode_tag(parser, name); if (parser->startElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); MAKE_STD_ZVAL(args[2]); array_init(args[2]); while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(args[2], att, val, val_len, 0); attributes += 2; efree(att); } if ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { zval *tag, *atr; int atcnt = 0; MAKE_STD_ZVAL(tag); MAKE_STD_ZVAL(atr); array_init(tag); array_init(atr); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","open",1); add_assoc_long(tag,"level",parser->level); parser->ltags[parser->level-1] = estrdup(tag_name); parser->lastwasopen = 1; attributes = (const XML_Char **) attrs; while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(atr,att,val,val_len,0); atcnt++; attributes += 2; efree(att); } if (atcnt) { zend_hash_add(Z_ARRVAL_P(tag),"attributes",sizeof("attributes"),&atr,sizeof(zval*),NULL); } else { zval_ptr_dtor(&atr); } zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag); } efree(tag_name); } } ; 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 int __br_mdb_del(struct net_bridge *br, struct br_mdb_entry *entry) { 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; struct br_ip ip; int err = -EINVAL; if (!netif_running(br->dev) || br->multicast_disabled) return -EINVAL; if (timer_pending(&br->multicast_querier_timer)) return -EBUSY; ip.proto = entry->addr.proto; if (ip.proto == htons(ETH_P_IP)) ip.u.ip4 = entry->addr.u.ip4; #if IS_ENABLED(CONFIG_IPV6) else ip.u.ip6 = entry->addr.u.ip6; #endif spin_lock_bh(&br->multicast_lock); mdb = mlock_dereference(br->mdb, br); mp = br_mdb_ip_get(mdb, &ip); if (!mp) goto unlock; for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (!p->port || p->port->dev->ifindex != entry->ifindex) continue; if (p->port->state == BR_STATE_DISABLED) goto unlock; rcu_assign_pointer(*pp, p->next); hlist_del_init(&p->mglist); del_timer(&p->timer); call_rcu_bh(&p->rcu, br_multicast_free_pg); err = 0; if (!mp->ports && !mp->mglist && netif_running(br->dev)) mod_timer(&mp->timer, jiffies); break; } unlock: spin_unlock_bh(&br->multicast_lock); return err; } ; 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: FileDescriptor connectToHelperAgent() { TRACE_POINT(); FileDescriptor conn; try { conn = connectToUnixServer(agentsStarter.getRequestSocketFilename()); writeExact(conn, agentsStarter.getRequestSocketPassword()); } catch (const SystemException &e) { if (e.code() == EPIPE || e.code() == ECONNREFUSED || e.code() == ENOENT) { UPDATE_TRACE_POINT(); bool connected = false; // Maybe the helper agent crashed. First wait 50 ms. usleep(50000); // Then try to reconnect to the helper agent for the // next 5 seconds. time_t deadline = time(NULL) + 5; while (!connected && time(NULL) < deadline) { try { conn = connectToUnixServer(agentsStarter.getRequestSocketFilename()); writeExact(conn, agentsStarter.getRequestSocketPassword()); connected = true; } catch (const SystemException &e) { if (e.code() == EPIPE || e.code() == ECONNREFUSED || e.code() == ENOENT) { // Looks like the helper agent hasn't been // restarted yet. Wait between 20 and 100 ms. usleep(20000 + rand() % 80000); // Don't care about thread-safety of rand() } else { throw; } } } if (!connected) { UPDATE_TRACE_POINT(); throw IOException("Cannot connect to the helper agent"); } } else { throw; } } return conn; } ; 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 php_session_reset_id(TSRMLS_D) /* {{{ */ { int module_number = PS(module_number); if (PS(use_cookies) && PS(send_cookie)) { php_session_send_cookie(TSRMLS_C); PS(send_cookie) = 0; } /* if the SID constant exists, destroy it. */ zend_hash_del(EG(zend_constants), "sid", sizeof("sid")); if (PS(define_sid)) { smart_str var = {0}; smart_str_appends(&var, PS(session_name)); smart_str_appendc(&var, '='); smart_str_appends(&var, PS(id)); smart_str_0(&var); REGISTER_STRINGL_CONSTANT("SID", var.c, var.len, 0); } else { REGISTER_STRINGL_CONSTANT("SID", STR_EMPTY_ALLOC(), 0, 0); } if (PS(apply_trans_sid)) { php_url_scanner_reset_vars(TSRMLS_C); php_url_scanner_add_var(PS(session_name), strlen(PS(session_name)), PS(id), strlen(PS(id)), 1 TSRMLS_CC); } } ; 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: int CLASS parse_tiff_ifd (int base) { unsigned entries, tag, type, len, plen=16, save; int ifd, use_cm=0, cfa, i, j, c, ima_len=0; int blrr=1, blrc=1, dblack[] = { 0,0,0,0 }; char software[64], *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256]; double cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 }; unsigned sony_curve[] = { 0,0,0,0,0,4095 }; unsigned *buf, sony_offset=0, sony_length=0, sony_key=0; struct jhead jh; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j=0; j < 4; j++) for (i=0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; while (entries--) { tiff_get (base, &tag, &type, &len, &save); switch (tag) { case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: filters = get2(); break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag-17)*2] = get2() / 256.0; break; case 23: if (type == 3) iso_speed = get2(); break; case 36: case 37: case 38: cam_mul[tag-0x24] = get2(); break; case 39: if (len < 50 || cam_mul[0]) break; fseek (ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ parse_tiff_ifd (base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); break; case 61446: raw_height = 0; load_raw = &CLASS packed_load_raw; load_flags = get4() && (filters=0x16161616) ? 24:80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread (desc, 512, 1, ifp); break; case 271: /* Make */ fgets (make, 64, ifp); break; case 272: /* Model */ fgets (model, 64, ifp); break; case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4()+base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; i = order; parse_tiff (tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: FORC3 cam_mul[(4-c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets (software, 64, ifp); if (!strncmp(software,"Adobe",5) || !strncmp(software,"dcraw",5) || !strncmp(software,"UFRaw",5) || !strncmp(software,"Bibble",6) || !strncmp(software,"Nikon Scan",10) || !strcmp (software,"Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread (artist, 64, 1, ifp); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; #ifdef LIBRAW_LIBRARY_BUILD case 325: /* TileByteCount */ tiff_ifd[ifd].tile_maxbytes = 0; for(int jj=0;jj<len;jj++) { int s = get4(); if(s > tiff_ifd[ifd].tile_maxbytes) tiff_ifd[ifd].tile_maxbytes=s; } break; #endif case 330: /* SubIFDs */ if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4()+base; ifd++; break; } while (len--) { i = ftell(ifp); fseek (ifp, get4()+base, SEEK_SET); if (parse_tiff_ifd (base)) break; fseek (ifp, i+4, SEEK_SET); } break; case 400: strcpy (make, "Sarnoff"); maximum = 0xfff; break; case 28688: FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff; for (i=0; i < 5; i++) for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta (ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP (cam_mul[i],cam_mul[i+1]) break; case 33405: /* Model2 */ fgets (model2, 64, ifp); break; case 33422: /* CFAPattern */ case 64777: /* Kodak P-series */ if ((plen=len) > 16) plen = 16; fread (cfa_pat, 1, plen, ifp); for (colors=cfa=i=0; i < plen; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */ if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */ goto guess_cfa_pc; case 33424: case 65024: fseek (ifp, get4()+base, SEEK_SET); parse_kodak_ifd (base); break; case 33434: /* ExposureTime */ shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread (software, 1, 7, ifp); if (strncmp(software,"MATRIX",6)) break; colors = 4; for (raw_color = i=0; i < 3; i++) { FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= num; } break; case 34310: /* Leaf metadata */ parse_mos (ftell(ifp)); case 34303: strcpy (make, "Leaf"); break; case 34665: /* EXIF tag */ fseek (ifp, get4()+base, SEEK_SET); parse_exif (base); break; case 34853: /* GPSInfo tag */ fseek (ifp, get4()+base, SEEK_SET); parse_gps (base); break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i=0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 46275: /* Imacon tags */ strcpy (make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek (ifp, 38, SEEK_CUR); case 46274: fseek (ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952 ) { height = 5412; width = 7216; left_margin = 7; filters=0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek (ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek (ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width,height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf (model, "Ixpress %d-Mp", height*width/1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (!(cbuf = (char *) malloc(len))) break; fread (cbuf, 1, len, ifp); for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n')) if (!strncmp (++cp,"Neutral ",8)) sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2); free (cbuf); break; case 50458: if (!make[0]) strcpy (make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek (ifp, j+(get2(),get4()), SEEK_SET); parse_tiff_ifd (j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy (make, "DNG"); is_raw = 1; break; case 50710: /* CFAPlaneColor */ if (len > 4) len = 4; colors = len; fread (cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i=16; i--; ) filters = filters << 2 | tab[cfa_pat[i % plen]]; break; case 50711: /* CFALayout */ if (get2() == 2) { fuji_width = 1; filters = 0x49494949; } break; case 291: case 50712: /* LinearizationTable */ linear_table (len); break; case 50713: /* BlackLevelRepeatDim */ blrr = get2(); blrc = get2(); break; case 61450: blrr = blrc = 2; case 50714: /* BlackLevel */ black = getreal(type); if (!filters || !~filters) break; dblack[0] = black; dblack[1] = (blrc == 2) ? getreal(type):dblack[0]; dblack[2] = (blrr == 2) ? getreal(type):dblack[0]; dblack[3] = (blrc == 2 && blrr == 2) ? getreal(type):dblack[1]; if (colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; FORC4 cblack[filters >> (c << 1) & 3] = dblack[c]; black = 0; break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num=i=0; i < len; i++) num += getreal(type); black += num/len + 0.5; break; case 50717: /* WhiteLevel */ maximum = getint(type); break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); break; case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ FORCC for (j=0; j < 3; j++) cm[c][j] = getreal(type); use_cm = 1; break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ for (i=0; i < colors; i++) FORCC cc[i][c] = getreal(type); break; case 50727: /* AnalogBalance */ FORCC ab[c] = getreal(type); break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; case 50740: /* DNGPrivateData */ if (dng_version) break; parse_minolta (j = get4()+base); fseek (ifp, j, SEEK_SET); parse_tiff_ifd (base); break; case 50752: read_shorts (cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i=0; i < len && i < 32; i++) mask[0][i] = getint(type); black = 0; break; case 51009: /* OpcodeList2 */ meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek (ifp, 16, SEEK_CUR); data_offset = get4(); fseek (ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets (model2, 64, ifp); } fseek (ifp, save, SEEK_SET); } if (sony_length && (buf = (unsigned *) malloc(sony_length))) { fseek (ifp, sony_offset, SEEK_SET); fread (buf, sony_length, 1, ifp); sony_decrypt (buf, sony_length/4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite (buf, sony_length, 1, ifp); fseek (ifp, 0, SEEK_SET); parse_tiff_ifd (-sony_offset); fclose (ifp); } ifp = sfp; #else if( !ifp->tempbuffer_open(buf,sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free (buf); } for (i=0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i=0; i < 3; i++) for (cam_xyz[c][i]=j=0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff (cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } ; 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: static int read_exceptions(struct pstore *ps, int (*callback)(void *callback_context, chunk_t old, chunk_t new), void *callback_context) { int r, full = 1; /* * Keeping reading chunks and inserting exceptions until * we find a partially full area. */ for (ps->current_area = 0; full; ps->current_area++) { r = area_io(ps, READ); if (r) return r; r = insert_exceptions(ps, callback, callback_context, &full); if (r) return r; } ps->current_area--; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-264'], 'message': 'dm snapshot: fix data corruption This patch fixes a particular type of data corruption that has been encountered when loading a snapshot's metadata from disk. When we allocate a new chunk in persistent_prepare, we increment ps->next_free and we make sure that it doesn't point to a metadata area by further incrementing it if necessary. When we load metadata from disk on device activation, ps->next_free is positioned after the last used data chunk. However, if this last used data chunk is followed by a metadata area, ps->next_free is positioned erroneously to the metadata area. A newly-allocated chunk is placed at the same location as the metadata area, resulting in data or metadata corruption. This patch changes the code so that ps->next_free skips the metadata area when metadata are loaded in function read_exceptions. The patch also moves a piece of code from persistent_prepare_exception to a separate function skip_metadata to avoid code duplication. CVE-2013-4299 Signed-off-by: Mikulas Patocka <mpatocka@redhat.com> Cc: stable@vger.kernel.org Cc: Mike Snitzer <snitzer@redhat.com> Signed-off-by: Alasdair G Kergon <agk@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[] ) { int keysize; unsigned long i, j, tsc; unsigned char tmp[64]; #if defined(POLARSSL_ARC4_C) arc4_context arc4; #endif #if defined(POLARSSL_DES_C) des3_context des3; des_context des; #endif #if defined(POLARSSL_AES_C) aes_context aes; #if defined(POLARSSL_GCM_C) gcm_context gcm; #endif #endif #if defined(POLARSSL_BLOWFISH_C) blowfish_context blowfish; #endif #if defined(POLARSSL_CAMELLIA_C) camellia_context camellia; #endif #if defined(POLARSSL_RSA_C) && defined(POLARSSL_BIGNUM_C) && \ defined(POLARSSL_GENPRIME) rsa_context rsa; #endif #if defined(POLARSSL_HAVEGE_C) havege_state hs; #endif #if defined(POLARSSL_CTR_DRBG_C) ctr_drbg_context ctr_drbg; #endif ((void) argc); ((void) argv); memset( buf, 0xAA, sizeof( buf ) ); printf( "\n" ); #if defined(POLARSSL_MD4_C) printf( HEADER_FORMAT, "MD4" ); fflush( stdout ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) md4( buf, BUFSIZE, tmp ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) md4( buf, BUFSIZE, tmp ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_MD5_C) printf( HEADER_FORMAT, "MD5" ); fflush( stdout ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) md5( buf, BUFSIZE, tmp ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) md5( buf, BUFSIZE, tmp ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_SHA1_C) printf( HEADER_FORMAT, "SHA-1" ); fflush( stdout ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) sha1( buf, BUFSIZE, tmp ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) sha1( buf, BUFSIZE, tmp ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_SHA2_C) printf( HEADER_FORMAT, "SHA-256" ); fflush( stdout ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) sha2( buf, BUFSIZE, tmp, 0 ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) sha2( buf, BUFSIZE, tmp, 0 ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_SHA4_C) printf( HEADER_FORMAT, "SHA-512" ); fflush( stdout ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) sha4( buf, BUFSIZE, tmp, 0 ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) sha4( buf, BUFSIZE, tmp, 0 ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_ARC4_C) printf( HEADER_FORMAT, "ARC4" ); fflush( stdout ); arc4_setup( &arc4, tmp, 32 ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) arc4_crypt( &arc4, BUFSIZE, buf, buf ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) arc4_crypt( &arc4, BUFSIZE, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_DES_C) printf( HEADER_FORMAT, "3DES" ); fflush( stdout ); des3_set3key_enc( &des3, tmp ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) des3_crypt_cbc( &des3, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) des3_crypt_cbc( &des3, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); printf( HEADER_FORMAT, "DES" ); fflush( stdout ); des_setkey_enc( &des, tmp ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) des_crypt_cbc( &des, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ); tsc = hardclock(); for( j = 0; j < 1024; j++ ) des_crypt_cbc( &des, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_AES_C) for( keysize = 128; keysize <= 256; keysize += 64 ) { printf( " AES-CBC-%d : ", keysize ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); memset( tmp, 0, sizeof( tmp ) ); aes_setkey_enc( &aes, tmp, keysize ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) aes_crypt_cbc( &aes, AES_ENCRYPT, BUFSIZE, tmp, buf, buf ); tsc = hardclock(); for( j = 0; j < 4096; j++ ) aes_crypt_cbc( &aes, AES_ENCRYPT, BUFSIZE, tmp, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); } #if defined(POLARSSL_GCM_C) for( keysize = 128; keysize <= 256; keysize += 64 ) { printf( " AES-GCM-%d : ", keysize ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); memset( tmp, 0, sizeof( tmp ) ); gcm_init( &gcm, tmp, keysize ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) gcm_crypt_and_tag( &gcm, GCM_ENCRYPT, BUFSIZE, tmp, 12, NULL, 0, buf, buf, 16, tmp ); tsc = hardclock(); for( j = 0; j < 4096; j++ ) gcm_crypt_and_tag( &gcm, GCM_ENCRYPT, BUFSIZE, tmp, 12, NULL, 0, buf, buf, 16, tmp ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); } #endif #endif #if defined(POLARSSL_CAMELLIA_C) for( keysize = 128; keysize <= 256; keysize += 64 ) { printf( " CAMELLIA-CBC-%d: ", keysize ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); memset( tmp, 0, sizeof( tmp ) ); camellia_setkey_enc( &camellia, tmp, keysize ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) camellia_crypt_cbc( &camellia, CAMELLIA_ENCRYPT, BUFSIZE, tmp, buf, buf ); tsc = hardclock(); for( j = 0; j < 4096; j++ ) camellia_crypt_cbc( &camellia, CAMELLIA_ENCRYPT, BUFSIZE, tmp, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); } #endif #if defined(POLARSSL_BLOWFISH_C) for( keysize = 128; keysize <= 256; keysize += 64 ) { printf( " BLOWFISH-CBC-%d: ", keysize ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); memset( tmp, 0, sizeof( tmp ) ); blowfish_setkey( &blowfish, tmp, keysize ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) blowfish_crypt_cbc( &blowfish, BLOWFISH_ENCRYPT, BUFSIZE, tmp, buf, buf ); tsc = hardclock(); for( j = 0; j < 4096; j++ ) blowfish_crypt_cbc( &blowfish, BLOWFISH_ENCRYPT, BUFSIZE, tmp, buf, buf ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); } #endif #if defined(POLARSSL_HAVEGE_C) printf( HEADER_FORMAT, "HAVEGE" ); fflush( stdout ); havege_init( &hs ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) havege_random( &hs, buf, BUFSIZE ); tsc = hardclock(); for( j = 1; j < 1024; j++ ) havege_random( &hs, buf, BUFSIZE ); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_CTR_DRBG_C) printf( HEADER_FORMAT, "CTR_DRBG (NOPR)" ); fflush( stdout ); if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 ) exit(1); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 ) exit(1); tsc = hardclock(); for( j = 1; j < 1024; j++ ) if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 ) exit(1); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); printf( HEADER_FORMAT, "CTR_DRBG (PR)" ); fflush( stdout ); if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 ) exit(1); ctr_drbg_set_prediction_resistance( &ctr_drbg, CTR_DRBG_PR_ON ); set_alarm( 1 ); for( i = 1; ! alarmed; i++ ) if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 ) exit(1); tsc = hardclock(); for( j = 1; j < 1024; j++ ) if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 ) exit(1); printf( "%9lu Kb/s, %9lu cycles/byte\n", i * BUFSIZE / 1024, ( hardclock() - tsc ) / ( j * BUFSIZE ) ); #endif #if defined(POLARSSL_RSA_C) && defined(POLARSSL_BIGNUM_C) && \ defined(POLARSSL_GENPRIME) rsa_init( &rsa, RSA_PKCS_V15, 0 ); rsa_gen_key( &rsa, myrand, NULL, 1024, 65537 ); printf( HEADER_FORMAT, "RSA-1024" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_public( &rsa, buf, buf ); } printf( "%9lu public/s\n", i / 3 ); printf( HEADER_FORMAT, "RSA-1024" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_private( &rsa, buf, buf ); } printf( "%9lu private/s\n", i / 3 ); rsa_free( &rsa ); rsa_init( &rsa, RSA_PKCS_V15, 0 ); rsa_gen_key( &rsa, myrand, NULL, 2048, 65537 ); printf( HEADER_FORMAT, "RSA-2048" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_public( &rsa, buf, buf ); } printf( "%9lu public/s\n", i / 3 ); printf( HEADER_FORMAT, "RSA-2048" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_private( &rsa, buf, buf ); } printf( "%9lu private/s\n", i / 3 ); rsa_free( &rsa ); rsa_init( &rsa, RSA_PKCS_V15, 0 ); rsa_gen_key( &rsa, myrand, NULL, 4096, 65537 ); printf( HEADER_FORMAT, "RSA-4096" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_public( &rsa, buf, buf ); } printf( "%9lu public/s\n", i / 3 ); printf( HEADER_FORMAT, "RSA-4096" ); fflush( stdout ); set_alarm( 3 ); for( i = 1; ! alarmed; i++ ) { buf[0] = 0; rsa_private( &rsa, buf, buf ); } printf( "%9lu private/s\n", i / 3 ); rsa_free( &rsa ); #endif printf( "\n" ); #if defined(_WIN32) printf( " Press Enter to exit this program.\n" ); fflush( stdout ); getchar(); #endif 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: int rsa_rsassa_pkcs1_v15_sign( rsa_context *ctx, int mode, int hash_id, unsigned int hashlen, const unsigned char *hash, unsigned char *sig ) { size_t nb_pad, olen; unsigned char *p = sig; if( ctx->padding != RSA_PKCS_V15 ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); olen = ctx->len; switch( hash_id ) { case SIG_RSA_RAW: nb_pad = olen - 3 - hashlen; break; case SIG_RSA_MD2: case SIG_RSA_MD4: case SIG_RSA_MD5: nb_pad = olen - 3 - 34; break; case SIG_RSA_SHA1: nb_pad = olen - 3 - 35; break; case SIG_RSA_SHA224: nb_pad = olen - 3 - 47; break; case SIG_RSA_SHA256: nb_pad = olen - 3 - 51; break; case SIG_RSA_SHA384: nb_pad = olen - 3 - 67; break; case SIG_RSA_SHA512: nb_pad = olen - 3 - 83; break; default: return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); } if( ( nb_pad < 8 ) || ( nb_pad > olen ) ) return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); *p++ = 0; *p++ = RSA_SIGN; memset( p, 0xFF, nb_pad ); p += nb_pad; *p++ = 0; switch( hash_id ) { case SIG_RSA_RAW: memcpy( p, hash, hashlen ); break; case SIG_RSA_MD2: memcpy( p, ASN1_HASH_MDX, 18 ); memcpy( p + 18, hash, 16 ); p[13] = 2; break; case SIG_RSA_MD4: memcpy( p, ASN1_HASH_MDX, 18 ); memcpy( p + 18, hash, 16 ); p[13] = 4; break; case SIG_RSA_MD5: memcpy( p, ASN1_HASH_MDX, 18 ); memcpy( p + 18, hash, 16 ); p[13] = 5; break; case SIG_RSA_SHA1: memcpy( p, ASN1_HASH_SHA1, 15 ); memcpy( p + 15, hash, 20 ); break; case SIG_RSA_SHA224: memcpy( p, ASN1_HASH_SHA2X, 19 ); memcpy( p + 19, hash, 28 ); p[1] += 28; p[14] = 4; p[18] += 28; break; case SIG_RSA_SHA256: memcpy( p, ASN1_HASH_SHA2X, 19 ); memcpy( p + 19, hash, 32 ); p[1] += 32; p[14] = 1; p[18] += 32; break; case SIG_RSA_SHA384: memcpy( p, ASN1_HASH_SHA2X, 19 ); memcpy( p + 19, hash, 48 ); p[1] += 48; p[14] = 2; p[18] += 48; break; case SIG_RSA_SHA512: memcpy( p, ASN1_HASH_SHA2X, 19 ); memcpy( p + 19, hash, 64 ); p[1] += 64; p[14] = 3; p[18] += 64; break; default: return( POLARSSL_ERR_RSA_BAD_INPUT_DATA ); } return( ( mode == RSA_PUBLIC ) ? rsa_public( ctx, sig, sig ) : rsa_private( ctx, sig, sig ) ); } ; 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: int rsa_self_test( int verbose ) { size_t len; rsa_context rsa; unsigned char rsa_plaintext[PT_LEN]; unsigned char rsa_decrypted[PT_LEN]; unsigned char rsa_ciphertext[KEY_LEN]; #if defined(POLARSSL_SHA1_C) unsigned char sha1sum[20]; #endif rsa_init( &rsa, RSA_PKCS_V15, 0 ); rsa.len = KEY_LEN; mpi_read_string( &rsa.N , 16, RSA_N ); mpi_read_string( &rsa.E , 16, RSA_E ); mpi_read_string( &rsa.D , 16, RSA_D ); mpi_read_string( &rsa.P , 16, RSA_P ); mpi_read_string( &rsa.Q , 16, RSA_Q ); mpi_read_string( &rsa.DP, 16, RSA_DP ); mpi_read_string( &rsa.DQ, 16, RSA_DQ ); mpi_read_string( &rsa.QP, 16, RSA_QP ); if( verbose != 0 ) printf( " RSA key validation: " ); if( rsa_check_pubkey( &rsa ) != 0 || rsa_check_privkey( &rsa ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) printf( "passed\n PKCS#1 encryption : " ); memcpy( rsa_plaintext, RSA_PT, PT_LEN ); if( rsa_pkcs1_encrypt( &rsa, &myrand, NULL, RSA_PUBLIC, PT_LEN, rsa_plaintext, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) printf( "passed\n PKCS#1 decryption : " ); if( rsa_pkcs1_decrypt( &rsa, RSA_PRIVATE, &len, rsa_ciphertext, rsa_decrypted, sizeof(rsa_decrypted) ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } #if defined(POLARSSL_SHA1_C) if( verbose != 0 ) printf( "passed\n PKCS#1 data sign : " ); sha1( rsa_plaintext, PT_LEN, sha1sum ); if( rsa_pkcs1_sign( &rsa, NULL, NULL, RSA_PRIVATE, SIG_RSA_SHA1, 20, sha1sum, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) printf( "passed\n PKCS#1 sig. verify: " ); if( rsa_pkcs1_verify( &rsa, RSA_PUBLIC, SIG_RSA_SHA1, 20, sha1sum, rsa_ciphertext ) != 0 ) { if( verbose != 0 ) printf( "failed\n" ); return( 1 ); } if( verbose != 0 ) printf( "passed\n\n" ); #endif /* POLARSSL_SHA1_C */ rsa_free( &rsa ); 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: int main( int argc, char *argv[] ) { ((void) argc); ((void) argv); printf("POLARSSL_AES_C and/or POLARSSL_DHM_C and/or POLARSSL_ENTROPY_C " "and/or POLARSSL_NET_C and/or POLARSSL_RSA_C and/or " "POLARSSL_SHA1_C and/or POLARSSL_FS_IO and/or " "POLARSSL_CTR_DBRG_C not defined.\n"); 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: int dane_verify_session_crt ( dane_state_t s, gnutls_session_t session, const char * hostname, const char* proto, unsigned int port, unsigned int sflags, unsigned int vflags, unsigned int *verify) { const gnutls_datum_t *cert_list; unsigned int cert_list_size = 0; unsigned int type; cert_list = gnutls_certificate_get_peers(session, &cert_list_size); if (cert_list_size == 0) { return gnutls_assert_val(DANE_E_NO_CERT); } type = gnutls_certificate_type_get(session); return dane_verify_crt(s, cert_list, cert_list_size, type, hostname, proto, port, sflags, vflags, verify); } ; 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: long do_msgsnd(int msqid, long mtype, void __user *mtext, size_t msgsz, int msgflg) { struct msg_queue *msq; struct msg_msg *msg; int err; struct ipc_namespace *ns; ns = current->nsproxy->ipc_ns; if (msgsz > ns->msg_ctlmax || (long) msgsz < 0 || msqid < 0) return -EINVAL; if (mtype < 1) return -EINVAL; msg = load_msg(mtext, msgsz); if (IS_ERR(msg)) return PTR_ERR(msg); msg->m_type = mtype; msg->m_ts = msgsz; msq = msg_lock_check(ns, msqid); if (IS_ERR(msq)) { err = PTR_ERR(msq); goto out_free; } for (;;) { struct msg_sender s; err = -EACCES; if (ipcperms(ns, &msq->q_perm, S_IWUGO)) goto out_unlock_free; err = security_msg_queue_msgsnd(msq, msg, msgflg); if (err) goto out_unlock_free; if (msgsz + msq->q_cbytes <= msq->q_qbytes && 1 + msq->q_qnum <= msq->q_qbytes) { break; } /* queue full, wait: */ if (msgflg & IPC_NOWAIT) { err = -EAGAIN; goto out_unlock_free; } ss_add(msq, &s); ipc_rcu_getref(msq); msg_unlock(msq); schedule(); ipc_lock_by_ptr(&msq->q_perm); ipc_rcu_putref(msq); if (msq->q_perm.deleted) { err = -EIDRM; goto out_unlock_free; } ss_del(&s); if (signal_pending(current)) { err = -ERESTARTNOHAND; goto out_unlock_free; } } msq->q_lspid = task_tgid_vnr(current); msq->q_stime = get_seconds(); if (!pipelined_send(msq, msg)) { /* no one is waiting for this message, enqueue it */ list_add_tail(&msg->m_list, &msq->q_messages); msq->q_cbytes += msgsz; msq->q_qnum++; atomic_add(msgsz, &ns->msg_bytes); atomic_inc(&ns->msg_hdrs); } err = 0; msg = NULL; out_unlock_free: msg_unlock(msq); out_free: if (msg != NULL) free_msg(msg); return err; } ; 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 inline void sem_lock_and_putref(struct sem_array *sma) { ipc_lock_by_ptr(&sma->sem_perm); ipc_rcu_putref(sma); } ; 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 gg_action_t gg_handle_tls_negotiation(struct gg_session *sess, struct gg_event *e, enum gg_state_t next_state, enum gg_state_t alt_state, enum gg_state_t alt2_state) { int valid_hostname = 0; #ifdef GG_CONFIG_HAVE_GNUTLS unsigned int status; int res; gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() GG_STATE_TLS_NEGOTIATION\n"); for (;;) { res = gnutls_handshake(GG_SESSION_GNUTLS(sess)); if (res == GNUTLS_E_AGAIN) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake GNUTLS_E_AGAIN\n"); if (gnutls_record_get_direction(GG_SESSION_GNUTLS(sess)) == 0) sess->check = GG_CHECK_READ; else sess->check = GG_CHECK_WRITE; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } if (res == GNUTLS_E_INTERRUPTED) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake GNUTLS_E_INTERRUPTED\n"); continue; } if (res != GNUTLS_E_SUCCESS) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS handshake error: %d, %s\n", res, gnutls_strerror(res)); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } break; } gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS negotiation succeded:\n"); gg_debug_session(sess, GG_DEBUG_MISC, "// cipher: VERS-%s:%s:%s:%s:COMP-%s\n", gnutls_protocol_get_name(gnutls_protocol_get_version(GG_SESSION_GNUTLS(sess))), gnutls_cipher_get_name(gnutls_cipher_get(GG_SESSION_GNUTLS(sess))), gnutls_kx_get_name(gnutls_kx_get(GG_SESSION_GNUTLS(sess))), gnutls_mac_get_name(gnutls_mac_get(GG_SESSION_GNUTLS(sess))), gnutls_compression_get_name(gnutls_compression_get(GG_SESSION_GNUTLS(sess)))); if (gnutls_certificate_type_get(GG_SESSION_GNUTLS(sess)) == GNUTLS_CRT_X509) { unsigned int peer_count; const gnutls_datum_t *peers; gnutls_x509_crt_t cert; if (gnutls_x509_crt_init(&cert) == 0) { peers = gnutls_certificate_get_peers(GG_SESSION_GNUTLS(sess), &peer_count); if (peers != NULL) { char buf[256]; size_t size; if (gnutls_x509_crt_import(cert, &peers[0], GNUTLS_X509_FMT_DER) == 0) { size = sizeof(buf); gnutls_x509_crt_get_dn(cert, buf, &size); gg_debug_session(sess, GG_DEBUG_MISC, "// cert subject: %s\n", buf); size = sizeof(buf); gnutls_x509_crt_get_issuer_dn(cert, buf, &size); gg_debug_session(sess, GG_DEBUG_MISC, "// cert issuer: %s\n", buf); if (gnutls_x509_crt_check_hostname(cert, sess->connect_host) != 0) valid_hostname = 1; } } gnutls_x509_crt_deinit(cert); } } res = gnutls_certificate_verify_peers2(GG_SESSION_GNUTLS(sess), &status); if (res != 0) { gg_debug_session(sess, GG_DEBUG_MISC, "//   WARNING! unable to verify peer certificate: %d, %s\n", res, gnutls_strerror(res)); if (sess->ssl_flag == GG_SSL_REQUIRED) { e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } else { gg_debug_session(sess, GG_DEBUG_MISC, "// verified peer certificate\n"); } #elif defined GG_CONFIG_HAVE_OPENSSL X509 *peer; int res; gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() %s\n", gg_debug_state(sess->state)); res = SSL_connect(GG_SESSION_OPENSSL(sess)); if (res <= 0) { int err; err = SSL_get_error(GG_SESSION_OPENSSL(sess), res); if (res == 0) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() disconnected during TLS negotiation\n"); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } if (err == SSL_ERROR_WANT_READ) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() wants to read\n"); sess->check = GG_CHECK_READ; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } else if (err == SSL_ERROR_WANT_WRITE) { gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() wants to write\n"); sess->check = GG_CHECK_WRITE; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } else { char buf[256]; ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() SSL_connect() bailed out: %s\n", buf); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() TLS negotiation succeded:\n// cipher: %s\n", SSL_get_cipher_name(GG_SESSION_OPENSSL(sess))); peer = SSL_get_peer_certificate(GG_SESSION_OPENSSL(sess)); if (peer == NULL) { gg_debug_session(sess, GG_DEBUG_MISC, "// WARNING! unable to get peer certificate!\n"); if (sess->ssl_flag == GG_SSL_REQUIRED) { e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } else { char buf[256]; long res; X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// cert subject: %s\n", buf); X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof(buf)); gg_debug_session(sess, GG_DEBUG_MISC, "// cert issuer: %s\n", buf); res = SSL_get_verify_result(GG_SESSION_OPENSSL(sess)); if (res != X509_V_OK) { gg_debug_session(sess, GG_DEBUG_MISC, "//   WARNING! unable to verify peer certificate! res=%ld\n", res); if (sess->ssl_flag == GG_SSL_REQUIRED) { e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } else { gg_debug_session(sess, GG_DEBUG_MISC, "// verified peer certificate\n"); } if (X509_NAME_get_text_by_NID(X509_get_subject_name(peer), NID_commonName, buf, sizeof(buf)) == -1) buf[0] = 0; /* Obsługa certyfikatów z wieloznacznikiem */ if (strchr(buf, '*') == buf && strchr(buf + 1, '*') == NULL) { char *tmp; tmp = strchr(sess->connect_host, '.'); if (tmp != NULL) valid_hostname = (strcasecmp(tmp, buf + 1) == 0); } else { valid_hostname = (strcasecmp(sess->connect_host, buf) == 0); } } #else gg_debug_session(sess, GG_DEBUG_MISC, "// gg_watch_fd() no SSL support\n"); e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; #endif if (!valid_hostname) { gg_debug_session(sess, GG_DEBUG_MISC, "//   WARNING! unable to verify hostname\n"); if (sess->ssl_flag == GG_SSL_REQUIRED) { e->event.failure = GG_FAILURE_TLS; return GG_ACTION_FAIL; } } sess->state = next_state; sess->check = GG_CHECK_READ; sess->timeout = GG_DEFAULT_TIMEOUT; return GG_ACTION_WAIT; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Poprawna weryfikacja certyfikatu za pomocą GnuTLS.'</s>
<s>[INST] Given the following code containing errors, provide 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 Bfree(Bigint *v) { if (v) { ACQUIRE_DTOA_LOCK(0); v->next = freelist[v->k]; freelist[v->k] = v; FREE_DTOA_LOCK(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'util.c: ignore too long fraction part * util.c (ruby_strtod): ignore too long fraction part, which does not affect the result. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@43775 b2dd03c8-39d4-4d8f-98ff-823fe69b080e'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static JSON_INLINE size_t num_buckets(hashtable_t *hashtable) { return primes[hashtable->num_buckets]; } ; 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 test_simple() { json_set_alloc_funcs(my_malloc, my_free); create_and_free_complex_object(); if(malloc_called != 20 || free_called != 20) fail("Custom allocation failed"); } ; 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 int pn_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct sk_buff *skb = NULL; struct sockaddr_pn sa; int rval = -EOPNOTSUPP; int copylen; if (flags & ~(MSG_PEEK|MSG_TRUNC|MSG_DONTWAIT|MSG_NOSIGNAL| MSG_CMSG_COMPAT)) goto out_nofree; if (addr_len) *addr_len = sizeof(sa); skb = skb_recv_datagram(sk, flags, noblock, &rval); if (skb == NULL) goto out_nofree; pn_skb_get_src_sockaddr(skb, &sa); copylen = skb->len; if (len < copylen) { msg->msg_flags |= MSG_TRUNC; copylen = len; } rval = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copylen); if (rval) { rval = -EFAULT; goto out; } rval = (flags & MSG_TRUNC) ? skb->len : copylen; if (msg->msg_name != NULL) memcpy(msg->msg_name, &sa, sizeof(struct sockaddr_pn)); out: skb_free_datagram(sk, skb); out_nofree: return rval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'inet: prevent leakage of uninitialized memory to user in recv syscalls Only update *addr_len when we actually fill in sockaddr, otherwise we can return uninitialized memory from the stack to the caller in the recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL) checks because we only get called with a valid addr_len pointer either from sock_common_recvmsg or inet_recvmsg. If a blocking read waits on a socket which is concurrently shut down we now return zero and set msg_msgnamelen to 0. Reported-by: mpb <mpb.mail@gmail.com> Suggested-by: 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: int ipv6_recv_rxpmtu(struct sock *sk, struct msghdr *msg, int len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct sockaddr_in6 *sin; struct ip6_mtuinfo mtu_info; int err; int copied; err = -EAGAIN; skb = xchg(&np->rxpmtu, NULL); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto out_free_skb; sock_recv_timestamp(msg, sk, skb); memcpy(&mtu_info, IP6CBMTU(skb), sizeof(mtu_info)); sin = (struct sockaddr_in6 *)msg->msg_name; if (sin) { sin->sin6_family = AF_INET6; sin->sin6_flowinfo = 0; sin->sin6_port = 0; sin->sin6_scope_id = mtu_info.ip6m_addr.sin6_scope_id; sin->sin6_addr = mtu_info.ip6m_addr.sin6_addr; } put_cmsg(msg, SOL_IPV6, IPV6_PATHMTU, sizeof(mtu_info), &mtu_info); err = copied; out_free_skb: kfree_skb(skb); out: return err; } ; 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: int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield) { char **atimes, **aranges = NULL; int numtimes=0,i=0,numranges=0; size_t buffer_size = 512; char buffer[512], bufferTmp[512]; buffer[0] = '\0'; bufferTmp[0] = '\0'; if (!lp || !timestring || !timefield) return MS_FALSE; /* discrete time */ if (strstr(timestring, ",") == NULL && strstr(timestring, "/") == NULL) { /* discrete time */ createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size); } else { /* multiple times, or ranges */ atimes = msStringSplit (timestring, ',', &numtimes); if (atimes == NULL || numtimes < 1) return MS_FALSE; strlcat(buffer, "(", buffer_size); for(i=0; i<numtimes; i++) { if(i!=0) { strlcat(buffer, " OR ", buffer_size); } strlcat(buffer, "(", buffer_size); aranges = msStringSplit(atimes[i], '/', &numranges); if(!aranges) return MS_FALSE; if(numranges == 1) { /* we don't have range, just a simple time */ createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size); strlcat(buffer, bufferTmp, buffer_size); } else if(numranges == 2) { /* we have a range */ createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size); strlcat(buffer, bufferTmp, buffer_size); } else { return MS_FALSE; } msFreeCharArray(aranges, numranges); strlcat(buffer, ")", buffer_size); } strlcat(buffer, ")", buffer_size); msFreeCharArray(atimes, numtimes); } if(!*buffer) { return MS_FALSE; } if(lp->filteritem) free(lp->filteritem); lp->filteritem = msStrdup(timefield); if (&lp->filter) { /* if the filter is set and it's a string type, concatenate it with the time. If not just free it */ if (lp->filter.type == MS_EXPRESSION) { snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer); loadExpressionString(&lp->filter, bufferTmp); } else { freeExpression(&lp->filter); loadExpressionString(&lp->filter, buffer); } } return MS_TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-89'], 'message': 'Fix potential SQL Injection with postgis TIME filters (#4834)'</s>
<s>[INST] Given the following code containing errors, provide 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 BSONTool::run() { _objcheck = hasParam( "objcheck" ); if ( hasParam( "filter" ) ) _matcher.reset( new Matcher( fromjson( getParam( "filter" ) ) ) ); return doRun(); } ; 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: void UrlParser::parse(char ch) { switch(_state) { case state_0: if (ch == '=') _state = state_value; else if (ch == '&') ; else if (ch == '%') _state = state_keyesc; else { _key = ch; _state = state_key; } break; case state_key: if (ch == '=') _state = state_value; else if (ch == '&') { _q.add(_key); _key.clear(); _state = state_0; } else if (ch == '%') _state = state_keyesc; else _key += ch; break; case state_value: if (ch == '%') _state = state_valueesc; else if (ch == '&') { _q.add(_key, _value); _key.clear(); _value.clear(); _state = state_0; } else if (ch == '+') _value += ' '; else _value += ch; break; case state_keyesc: case state_valueesc: if (ch >= '0' && ch <= '9') { ++_cnt; _v = (_v << 4) + (ch - '0'); } else if (ch >= 'a' && ch <= 'f') { ++_cnt; _v = (_v << 4) + (ch - 'a' + 10); } else if (ch >= 'A' && ch <= 'F') { ++_cnt; _v = (_v << 4) + (ch - 'A' + 10); } else { if (_cnt == 0) { if (_state == state_keyesc) _state = state_key; else _state = state_value; parse('%'); } else { if (_state == state_keyesc) { _key += static_cast<char>(_v); _state = state_key; } else { _value += static_cast<char>(_v); _state = state_value; } _cnt = 0; _v = 0; } parse(ch); break; } if (_cnt >= 2) { if (_state == state_keyesc) { _key += static_cast<char>(_v); _state = state_key; } else { _value += static_cast<char>(_v); _state = state_value; } _cnt = 0; _v = 0; } break; } } ; 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: void verifyDirectoryPermissions(const string &path) { TRACE_POINT(); struct stat buf; if (stat(path.c_str(), &buf) == -1) { int e = errno; throw FileSystemException("Cannot stat() " + path, e, path); } else if (buf.st_mode != (S_IFDIR | parseModeString("u=rwx,g=rx,o=rx"))) { throw RuntimeException("Tried to reuse existing server instance directory " + path + ", but it has wrong permissions"); } else if (buf.st_uid != geteuid() || buf.st_gid != getegid()) { /* The server instance directory is always created by the Watchdog. Its UID/GID never * changes because: * 1. Disabling user switching only lowers the privilege of the HelperAgent. * 2. For the UID/GID to change, the web server must be completely restarted * (not just graceful reload) so that the control process can change its UID/GID. * This causes the PID to change, so that an entirely new server instance * directory is created. */ throw RuntimeException("Tried to reuse existing server instance directory " + path + ", but it has wrong owner and group"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'Fix a symlink-related security vulnerability. The fix in commit 34b10878 and contained a small attack time window in between two filesystem operations. This has been fixed.'</s>
<s>[INST] Given the following code containing errors, provide 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(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m1[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m2[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[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: fmgr_sql_validator(PG_FUNCTION_ARGS) { Oid funcoid = PG_GETARG_OID(0); HeapTuple tuple; Form_pg_proc proc; List *raw_parsetree_list; List *querytree_list; ListCell *lc; bool isnull; Datum tmp; char *prosrc; parse_error_callback_arg callback_arg; ErrorContextCallback sqlerrcontext; bool haspolyarg; int i; tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid)); if (!HeapTupleIsValid(tuple)) elog(ERROR, "cache lookup failed for function %u", funcoid); proc = (Form_pg_proc) GETSTRUCT(tuple); /* Disallow pseudotype result */ /* except for RECORD, VOID, or polymorphic */ if (get_typtype(proc->prorettype) == TYPTYPE_PSEUDO && proc->prorettype != RECORDOID && proc->prorettype != VOIDOID && !IsPolymorphicType(proc->prorettype)) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), errmsg("SQL functions cannot return type %s", format_type_be(proc->prorettype)))); /* Disallow pseudotypes in arguments */ /* except for polymorphic */ haspolyarg = false; for (i = 0; i < proc->pronargs; i++) { if (get_typtype(proc->proargtypes.values[i]) == TYPTYPE_PSEUDO) { if (IsPolymorphicType(proc->proargtypes.values[i])) haspolyarg = true; else ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), errmsg("SQL functions cannot have arguments of type %s", format_type_be(proc->proargtypes.values[i])))); } } /* Postpone body checks if !check_function_bodies */ if (check_function_bodies) { tmp = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_prosrc, &isnull); if (isnull) elog(ERROR, "null prosrc"); prosrc = TextDatumGetCString(tmp); /* * Setup error traceback support for ereport(). */ callback_arg.proname = NameStr(proc->proname); callback_arg.prosrc = prosrc; sqlerrcontext.callback = sql_function_parse_error_callback; sqlerrcontext.arg = (void *) &callback_arg; sqlerrcontext.previous = error_context_stack; error_context_stack = &sqlerrcontext; /* * We can't do full prechecking of the function definition if there * are any polymorphic input types, because actual datatypes of * expression results will be unresolvable. The check will be done at * runtime instead. * * We can run the text through the raw parser though; this will at * least catch silly syntactic errors. */ raw_parsetree_list = pg_parse_query(prosrc); if (!haspolyarg) { /* * OK to do full precheck: analyze and rewrite the queries, then * verify the result type. */ SQLFunctionParseInfoPtr pinfo; /* But first, set up parameter information */ pinfo = prepare_sql_fn_parse_info(tuple, NULL, InvalidOid); querytree_list = NIL; foreach(lc, raw_parsetree_list) { Node *parsetree = (Node *) lfirst(lc); List *querytree_sublist; querytree_sublist = pg_analyze_and_rewrite_params(parsetree, prosrc, (ParserSetupHook) sql_fn_parser_setup, pinfo); querytree_list = list_concat(querytree_list, querytree_sublist); } (void) check_sql_fn_retval(funcoid, proc->prorettype, querytree_list, NULL, NULL); } error_context_stack = sqlerrcontext.previous; } ReleaseSysCache(tuple); PG_RETURN_VOID(); } ; 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: transformAlterTableStmt(AlterTableStmt *stmt, const char *queryString) { Relation rel; ParseState *pstate; CreateStmtContext cxt; List *result; List *save_alist; ListCell *lcmd, *l; List *newcmds = NIL; bool skipValidation = true; AlterTableCmd *newcmd; LOCKMODE lockmode; /* * We must not scribble on the passed-in AlterTableStmt, so copy it. (This * is overkill, but easy.) */ stmt = (AlterTableStmt *) copyObject(stmt); /* * Determine the appropriate lock level for this list of subcommands. */ lockmode = AlterTableGetLockLevel(stmt->cmds); /* * Acquire appropriate lock on the target relation, which will be held * until end of transaction. This ensures any decisions we make here * based on the state of the relation will still be good at execution. We * must get lock now because execution will later require it; taking a * lower grade lock now and trying to upgrade later risks deadlock. Any * new commands we add after this must not upgrade the lock level * requested here. */ rel = relation_openrv_extended(stmt->relation, lockmode, stmt->missing_ok); if (rel == NULL) { /* this message is consistent with relation_openrv */ ereport(NOTICE, (errmsg("relation \"%s\" does not exist, skipping", stmt->relation->relname))); return NIL; } /* Set up pstate and CreateStmtContext */ pstate = make_parsestate(NULL); pstate->p_sourcetext = queryString; cxt.pstate = pstate; if (stmt->relkind == OBJECT_FOREIGN_TABLE) { cxt.stmtType = "ALTER FOREIGN TABLE"; cxt.isforeign = true; } else { cxt.stmtType = "ALTER TABLE"; cxt.isforeign = false; } cxt.relation = stmt->relation; cxt.rel = rel; cxt.inhRelations = NIL; cxt.isalter = true; cxt.hasoids = false; /* need not be right */ cxt.columns = NIL; cxt.ckconstraints = NIL; cxt.fkconstraints = NIL; cxt.ixconstraints = NIL; cxt.inh_indexes = NIL; cxt.blist = NIL; cxt.alist = NIL; cxt.pkey = NULL; /* * The only subtypes that currently require parse transformation handling * are ADD COLUMN and ADD CONSTRAINT. These largely re-use code from * CREATE TABLE. */ foreach(lcmd, stmt->cmds) { AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd); switch (cmd->subtype) { case AT_AddColumn: case AT_AddColumnToView: { ColumnDef *def = (ColumnDef *) cmd->def; Assert(IsA(def, ColumnDef)); transformColumnDefinition(&cxt, def); /* * If the column has a non-null default, we can't skip * validation of foreign keys. */ if (def->raw_default != NULL) skipValidation = false; /* * All constraints are processed in other ways. Remove the * original list */ def->constraints = NIL; newcmds = lappend(newcmds, cmd); break; } case AT_AddConstraint: /* * The original AddConstraint cmd node doesn't go to newcmds */ if (IsA(cmd->def, Constraint)) { transformTableConstraint(&cxt, (Constraint *) cmd->def); if (((Constraint *) cmd->def)->contype == CONSTR_FOREIGN) skipValidation = false; } else elog(ERROR, "unrecognized node type: %d", (int) nodeTag(cmd->def)); break; case AT_ProcessedConstraint: /* * Already-transformed ADD CONSTRAINT, so just make it look * like the standard case. */ cmd->subtype = AT_AddConstraint; newcmds = lappend(newcmds, cmd); break; default: newcmds = lappend(newcmds, cmd); break; } } /* * transformIndexConstraints wants cxt.alist to contain only index * statements, so transfer anything we already have into save_alist * immediately. */ save_alist = cxt.alist; cxt.alist = NIL; /* Postprocess index and FK constraints */ transformIndexConstraints(&cxt); transformFKConstraints(&cxt, skipValidation, true); /* * Push any index-creation commands into the ALTER, so that they can be * scheduled nicely by tablecmds.c. Note that tablecmds.c assumes that * the IndexStmt attached to an AT_AddIndex or AT_AddIndexConstraint * subcommand has already been through transformIndexStmt. */ foreach(l, cxt.alist) { IndexStmt *idxstmt = (IndexStmt *) lfirst(l); Assert(IsA(idxstmt, IndexStmt)); idxstmt = transformIndexStmt(idxstmt, queryString); newcmd = makeNode(AlterTableCmd); newcmd->subtype = OidIsValid(idxstmt->indexOid) ? AT_AddIndexConstraint : AT_AddIndex; newcmd->def = (Node *) idxstmt; newcmds = lappend(newcmds, newcmd); } cxt.alist = NIL; /* Append any CHECK or FK constraints to the commands list */ foreach(l, cxt.ckconstraints) { newcmd = makeNode(AlterTableCmd); newcmd->subtype = AT_AddConstraint; newcmd->def = (Node *) lfirst(l); newcmds = lappend(newcmds, newcmd); } foreach(l, cxt.fkconstraints) { newcmd = makeNode(AlterTableCmd); newcmd->subtype = AT_AddConstraint; newcmd->def = (Node *) lfirst(l); newcmds = lappend(newcmds, newcmd); } /* Close rel but keep lock */ relation_close(rel, NoLock); /* * Output results. */ stmt->cmds = newcmds; result = lappend(cxt.blist, stmt); result = list_concat(result, cxt.alist); result = list_concat(result, save_alist); return result; } ; 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: _copyConstraint(const Constraint *from) { Constraint *newnode = makeNode(Constraint); COPY_SCALAR_FIELD(contype); COPY_STRING_FIELD(conname); COPY_SCALAR_FIELD(deferrable); COPY_SCALAR_FIELD(initdeferred); COPY_LOCATION_FIELD(location); COPY_SCALAR_FIELD(is_no_inherit); COPY_NODE_FIELD(raw_expr); COPY_STRING_FIELD(cooked_expr); COPY_NODE_FIELD(keys); COPY_NODE_FIELD(exclusions); COPY_NODE_FIELD(options); COPY_STRING_FIELD(indexname); COPY_STRING_FIELD(indexspace); COPY_STRING_FIELD(access_method); COPY_NODE_FIELD(where_clause); COPY_NODE_FIELD(pktable); COPY_NODE_FIELD(fk_attrs); COPY_NODE_FIELD(pk_attrs); COPY_SCALAR_FIELD(fk_matchtype); COPY_SCALAR_FIELD(fk_upd_action); COPY_SCALAR_FIELD(fk_del_action); COPY_NODE_FIELD(old_conpfeqop); COPY_SCALAR_FIELD(skip_validation); COPY_SCALAR_FIELD(initially_valid); return newnode; } ; 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: makepol(QPRS_STATE *state) { int32 val = 0, type; int32 lenval = 0; char *strval = NULL; int32 stack[STACKDEPTH]; int32 lenstack = 0; uint16 flag = 0; while ((type = gettoken_query(state, &val, &lenval, &strval, &flag)) != END) { switch (type) { case VAL: pushval_asis(state, VAL, strval, lenval, flag); while (lenstack && (stack[lenstack - 1] == (int32) '&' || stack[lenstack - 1] == (int32) '!')) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); } break; case OPR: if (lenstack && val == (int32) '|') pushquery(state, OPR, val, 0, 0, 0); else { if (lenstack == STACKDEPTH) /* internal error */ elog(ERROR, "stack too short"); stack[lenstack] = val; lenstack++; } break; case OPEN: if (makepol(state) == ERR) return ERR; while (lenstack && (stack[lenstack - 1] == (int32) '&' || stack[lenstack - 1] == (int32) '!')) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); } break; case CLOSE: while (lenstack) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); }; return END; break; case ERR: default: ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"))); return ERR; } } while (lenstack) { lenstack--; pushquery(state, OPR, stack[lenstack], 0, 0, 0); }; return END; } ; 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: varbit_in(PG_FUNCTION_ARGS) { char *input_string = PG_GETARG_CSTRING(0); #ifdef NOT_USED Oid typelem = PG_GETARG_OID(1); #endif int32 atttypmod = PG_GETARG_INT32(2); VarBit *result; /* The resulting bit string */ char *sp; /* pointer into the character string */ bits8 *r; /* pointer into the result */ int len, /* Length of the whole data structure */ bitlen, /* Number of bits in the bit string */ slen; /* Length of the input string */ bool bit_not_hex; /* false = hex string true = bit string */ int bc; bits8 x = 0; /* Check that the first character is a b or an x */ if (input_string[0] == 'b' || input_string[0] == 'B') { bit_not_hex = true; sp = input_string + 1; } else if (input_string[0] == 'x' || input_string[0] == 'X') { bit_not_hex = false; sp = input_string + 1; } else { bit_not_hex = true; sp = input_string; } slen = strlen(sp); /* Determine bitlength from input string */ if (bit_not_hex) bitlen = slen; else bitlen = slen * 4; /* * Sometimes atttypmod is not supplied. If it is supplied we need to make * sure that the bitstring fits. */ if (atttypmod <= 0) atttypmod = bitlen; else if (bitlen > atttypmod) ereport(ERROR, (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION), errmsg("bit string too long for type bit varying(%d)", atttypmod))); len = VARBITTOTALLEN(bitlen); /* set to 0 so that *r is always initialised and string is zero-padded */ result = (VarBit *) palloc0(len); SET_VARSIZE(result, len); VARBITLEN(result) = Min(bitlen, atttypmod); r = VARBITS(result); if (bit_not_hex) { /* Parse the bit representation of the string */ /* We know it fits, as bitlen was compared to atttypmod */ x = HIGHBIT; for (; *sp; sp++) { if (*sp == '1') *r |= x; else if (*sp != '0') ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("\"%c\" is not a valid binary digit", *sp))); x >>= 1; if (x == 0) { x = HIGHBIT; r++; } } } else { /* Parse the hex representation of the string */ for (bc = 0; *sp; sp++) { if (*sp >= '0' && *sp <= '9') x = (bits8) (*sp - '0'); else if (*sp >= 'A' && *sp <= 'F') x = (bits8) (*sp - 'A') + 10; else if (*sp >= 'a' && *sp <= 'f') x = (bits8) (*sp - 'a') + 10; else ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg("\"%c\" is not a valid hexadecimal digit", *sp))); if (bc) { *r++ |= x; bc = 0; } else { *r = x << 4; bc = 1; } } } PG_RETURN_VARBIT_P(result); } ; 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: parse_tsquery(char *buf, PushFunction pushval, Datum opaque, bool isplain) { struct TSQueryParserStateData state; int i; TSQuery query; int commonlen; QueryItem *ptr; ListCell *cell; /* init state */ state.buffer = buf; state.buf = buf; state.state = (isplain) ? WAITSINGLEOPERAND : WAITFIRSTOPERAND; state.count = 0; state.polstr = NIL; /* init value parser's state */ state.valstate = init_tsvector_parser(state.buffer, true, true); /* 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, pushval, opaque); close_tsvector_parser(state.valstate); if (list_length(state.polstr) == 0) { ereport(NOTICE, (errmsg("text-search query doesn't contain lexemes: \"%s\"", state.buffer))); query = (TSQuery) palloc(HDRSIZETQ); SET_VARSIZE(query, HDRSIZETQ); query->size = 0; return query; } /* Pack the QueryItems in the final TSQuery struct to return to caller */ commonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen); query = (TSQuery) palloc0(commonlen); SET_VARSIZE(query, commonlen); query->size = list_length(state.polstr); ptr = GETQUERY(query); /* Copy QueryItems to TSQuery */ i = 0; foreach(cell, state.polstr) { QueryItem *item = (QueryItem *) lfirst(cell); switch (item->type) { case QI_VAL: memcpy(&ptr[i], item, sizeof(QueryOperand)); break; case QI_VALSTOP: ptr[i].type = QI_VALSTOP; break; case QI_OPR: memcpy(&ptr[i], item, sizeof(QueryOperator)); break; default: elog(ERROR, "unrecognized QueryItem type: %d", item->type); } i++; } /* Copy all the operand strings to TSQuery */ memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen); pfree(state.op); /* Set left operand pointers for every operator. */ findoprnd(ptr, query->size); 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: validate_exec(const char *path) { struct stat buf; int is_r; int is_x; #ifdef WIN32 char path_exe[MAXPGPATH + sizeof(".exe") - 1]; /* Win32 requires a .exe suffix for stat() */ if (strlen(path) >= strlen(".exe") && pg_strcasecmp(path + strlen(path) - strlen(".exe"), ".exe") != 0) { strcpy(path_exe, path); strcat(path_exe, ".exe"); path = path_exe; } #endif /* * Ensure that the file exists and is a regular file. * * XXX if you have a broken system where stat() looks at the symlink * instead of the underlying file, you lose. */ if (stat(path, &buf) < 0) return -1; if (!S_ISREG(buf.st_mode)) return -1; /* * Ensure that the file is both executable and readable (required for * dynamic loading). */ #ifndef WIN32 is_r = (access(path, R_OK) == 0); is_x = (access(path, X_OK) == 0); #else is_r = buf.st_mode & S_IRUSR; is_x = buf.st_mode & S_IXUSR; #endif return is_x ? (is_r ? 0 : -2) : -1; } ; 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: resolve_symlinks(char *path) { #ifdef HAVE_READLINK struct stat buf; char orig_wd[MAXPGPATH], link_buf[MAXPGPATH]; char *fname; /* * To resolve a symlink properly, we have to chdir into its directory and * then chdir to where the symlink points; otherwise we may fail to * resolve relative links correctly (consider cases involving mount * points, for example). After following the final symlink, we use * getcwd() to figure out where the heck we're at. * * One might think we could skip all this if path doesn't point to a * symlink to start with, but that's wrong. We also want to get rid of * any directory symlinks that are present in the given path. We expect * getcwd() to give us an accurate, symlink-free path. */ if (!getcwd(orig_wd, MAXPGPATH)) { log_error(_("could not identify current directory: %s"), strerror(errno)); return -1; } for (;;) { char *lsep; int rllen; lsep = last_dir_separator(path); if (lsep) { *lsep = '\0'; if (chdir(path) == -1) { log_error4(_("could not change directory to \"%s\": %s"), path, strerror(errno)); return -1; } fname = lsep + 1; } else fname = path; if (lstat(fname, &buf) < 0 || !S_ISLNK(buf.st_mode)) break; rllen = readlink(fname, link_buf, sizeof(link_buf)); if (rllen < 0 || rllen >= sizeof(link_buf)) { log_error(_("could not read symbolic link \"%s\""), fname); return -1; } link_buf[rllen] = '\0'; strcpy(path, link_buf); } /* must copy final component out of 'path' temporarily */ strcpy(link_buf, fname); if (!getcwd(path, MAXPGPATH)) { log_error(_("could not identify current directory: %s"), strerror(errno)); return -1; } join_path_components(path, path, link_buf); canonicalize_path(path); if (chdir(orig_wd) == -1) { log_error4(_("could not change directory to \"%s\": %s"), orig_wd, strerror(errno)); return -1; } #endif /* HAVE_READLINK */ return 0; } ; 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 int usb_device_post_load(void *opaque, int version_id) { USBDevice *dev = opaque; if (dev->state == USB_STATE_NOTATTACHED) { dev->attached = 0; } else { dev->attached = 1; } if (dev->setup_index >= sizeof(dev->data_buf) || dev->setup_len >= sizeof(dev->data_buf)) { return -EINVAL; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'usb: sanity check setup_index+setup_len in post_load CVE-2013-4541 s->setup_len and s->setup_index are fed into usb_packet_copy as size/offset into s->data_buf, it's possible for invalid state to exploit this to load arbitrary data. setup_len and setup_index should be checked to make sure they are not negative. Cc: Gerd Hoffmann <kraxel@redhat.com> Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Reviewed-by: Gerd Hoffmann <kraxel@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: _gnutls_x509_verify_certificate (const gnutls_x509_crt_t * certificate_list, int clist_size, const gnutls_x509_crt_t * trusted_cas, int tcas_size, const gnutls_x509_crl_t * CRLs, int crls_size, unsigned int flags) { int i = 0, ret; unsigned int status = 0, output; if (clist_size > 1) { /* Check if the last certificate in the path is self signed. * In that case ignore it (a certificate is trusted only if it * leads to a trusted party by us, not the server's). * * This prevents from verifying self signed certificates against * themselves. This (although not bad) caused verification * failures on some root self signed certificates that use the * MD2 algorithm. */ if (gnutls_x509_crt_check_issuer (certificate_list[clist_size - 1], certificate_list[clist_size - 1]) > 0) { clist_size--; } } /* We want to shorten the chain by removing the cert that matches * one of the certs we trust and all the certs after that i.e. if * cert chain is A signed-by B signed-by C signed-by D (signed-by * self-signed E but already removed above), and we trust B, remove * B, C and D. We must leave the first cert on chain. */ if (clist_size > 1 && !(flags & GNUTLS_VERIFY_DO_NOT_ALLOW_SAME)) { for (i = 1; i < clist_size; i++) { int j; for (j = 0; j < tcas_size; j++) { if (check_if_same_cert (certificate_list[i], trusted_cas[j]) == 0) { clist_size = i; break; } } /* clist_size may have been changed which gets out of loop */ } } /* Verify the last certificate in the certificate path * against the trusted CA certificate list. * * If no CAs are present returns CERT_INVALID. Thus works * in self signed etc certificates. */ ret = _gnutls_verify_certificate2 (certificate_list[clist_size - 1], trusted_cas, tcas_size, flags, &output); if (ret == 0) { /* if the last certificate in the certificate * list is invalid, then the certificate is not * trusted. */ gnutls_assert (); status |= output; status |= GNUTLS_CERT_INVALID; return status; } /* Check for revoked certificates in the chain */ #ifdef ENABLE_PKI for (i = 0; i < clist_size; i++) { ret = gnutls_x509_crt_check_revocation (certificate_list[i], CRLs, crls_size); if (ret == 1) { /* revoked */ status |= GNUTLS_CERT_REVOKED; status |= GNUTLS_CERT_INVALID; return status; } } #endif /* Verify the certificate path (chain) */ for (i = clist_size - 1; i > 0; i--) { if (i - 1 < 0) break; /* note that here we disable this V1 CA flag. So that no version 1 * certificates can exist in a supplied chain. */ if (!(flags & GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT)) flags ^= GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT; if ((ret = _gnutls_verify_certificate2 (certificate_list[i - 1], &certificate_list[i], 1, flags, NULL)) == 0) { status |= GNUTLS_CERT_INVALID; return status; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Corrected bit disable (was flipping instead). Initialy reported by Daniel Kahn Gillmor on 9/1/2008. Many thanks to moog@sysdev.oucs.ox.ac.uk for bringing this into my attention.'</s>
<s>[INST] Given the following code containing errors, provide 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; 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)); } 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 (cvt_flip(m->in_type, flip)) { case FILE_BYTE: if (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 + 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 + 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 + 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 + 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 + 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 + 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 + 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; } switch (cvt_flip(m->in_type, flip)) { 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)); } } /* Verify we have enough data to match magic type */ switch (m->type) { case FILE_BYTE: if (nbytes < (offset + 1)) /* should always 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 (offset == 0) return 0; 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, recursion_level, 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, m->desc, offset) == -1) { if (rbuf) { efree(rbuf); } return -1; } if (file_printf(ms, "%s", rbuf) == -1) { if (rbuf) { efree(rbuf); } return -1; } } if (rbuf) { efree(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 */ 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': 'Fixed Bug #66820 out-of-bounds memory access in fileinfo Upstream fix: https://github.com/glensc/file/commit/447558595a3650db2886cd2f416ad0beba965801 Notice, test changed, with upstream agreement: -define OFFSET_OOB(n, o, i) ((n) < (o) || (i) >= ((n) - (o))) +define OFFSET_OOB(n, o, i) ((n) < (o) || (i) > ((n) - (o)))'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int64_t qcow2_alloc_clusters(BlockDriverState *bs, int64_t size) { int64_t offset; int ret; BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC); offset = alloc_clusters_noref(bs, size); if (offset < 0) { return offset; } ret = update_refcount(bs, offset, size, 1, QCOW2_DISCARD_NEVER); if (ret < 0) { return ret; } return offset; } ; 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: skb_zerocopy(struct sk_buff *to, const struct sk_buff *from, int len, int hlen) { int i, j = 0; int plen = 0; /* length of skb->head fragment */ struct page *page; unsigned int offset; BUG_ON(!from->head_frag && !hlen); /* dont bother with small payloads */ if (len <= skb_tailroom(to)) { skb_copy_bits(from, 0, skb_put(to, len), len); return; } if (hlen) { skb_copy_bits(from, 0, skb_put(to, hlen), hlen); len -= hlen; } else { plen = min_t(int, skb_headlen(from), len); if (plen) { page = virt_to_head_page(from->head); offset = from->data - (unsigned char *)page_address(page); __skb_fill_page_desc(to, 0, page, offset, plen); get_page(page); j = 1; len -= plen; } } to->truesize += len + plen; to->len += len + plen; to->data_len += len + plen; for (i = 0; i < skb_shinfo(from)->nr_frags; i++) { if (!len) break; skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i]; skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len); len -= skb_shinfo(to)->frags[j].size; skb_frag_ref(to, j); j++; } skb_shinfo(to)->nr_frags = j; } ; 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: static int hostmatch(const char *hostname, const char *pattern) { for(;;) { char c = *pattern++; if(c == '\0') return (*hostname ? HOST_NOMATCH : HOST_MATCH); if(c == '*') { c = *pattern; if(c == '\0') /* "*\0" matches anything remaining */ return HOST_MATCH; while(*hostname) { /* The only recursive function in libcurl! */ if(hostmatch(hostname++,pattern) == HOST_MATCH) return HOST_MATCH; } break; } if(Curl_raw_toupper(c) != Curl_raw_toupper(*hostname++)) break; } return HOST_NOMATCH; } ; 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 int vdi_create(const char *filename, QEMUOptionParameter *options, Error **errp) { int fd; int result = 0; uint64_t bytes = 0; uint32_t blocks; size_t block_size = DEFAULT_CLUSTER_SIZE; uint32_t image_type = VDI_TYPE_DYNAMIC; VdiHeader header; size_t i; size_t bmap_size; logout("\n"); /* Read out options. */ while (options && options->name) { if (!strcmp(options->name, BLOCK_OPT_SIZE)) { bytes = options->value.n; #if defined(CONFIG_VDI_BLOCK_SIZE) } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) { if (options->value.n) { /* TODO: Additional checks (SECTOR_SIZE * 2^n, ...). */ block_size = options->value.n; } #endif #if defined(CONFIG_VDI_STATIC_IMAGE) } else if (!strcmp(options->name, BLOCK_OPT_STATIC)) { if (options->value.n) { image_type = VDI_TYPE_STATIC; } #endif } options++; } fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY | O_LARGEFILE, 0644); if (fd < 0) { return -errno; } /* We need enough blocks to store the given disk size, so always round up. */ blocks = (bytes + block_size - 1) / block_size; bmap_size = blocks * sizeof(uint32_t); bmap_size = ((bmap_size + SECTOR_SIZE - 1) & ~(SECTOR_SIZE -1)); memset(&header, 0, sizeof(header)); pstrcpy(header.text, sizeof(header.text), VDI_TEXT); header.signature = VDI_SIGNATURE; header.version = VDI_VERSION_1_1; header.header_size = 0x180; header.image_type = image_type; header.offset_bmap = 0x200; header.offset_data = 0x200 + bmap_size; header.sector_size = SECTOR_SIZE; header.disk_size = bytes; header.block_size = block_size; header.blocks_in_image = blocks; if (image_type == VDI_TYPE_STATIC) { header.blocks_allocated = blocks; } uuid_generate(header.uuid_image); uuid_generate(header.uuid_last_snap); /* There is no need to set header.uuid_link or header.uuid_parent here. */ #if defined(CONFIG_VDI_DEBUG) vdi_header_print(&header); #endif vdi_header_to_le(&header); if (write(fd, &header, sizeof(header)) < 0) { result = -errno; } if (bmap_size > 0) { uint32_t *bmap = g_malloc0(bmap_size); for (i = 0; i < blocks; i++) { if (image_type == VDI_TYPE_STATIC) { bmap[i] = i; } else { bmap[i] = VDI_UNALLOCATED; } } if (write(fd, bmap, bmap_size) < 0) { result = -errno; } g_free(bmap); } if (image_type == VDI_TYPE_STATIC) { if (ftruncate(fd, sizeof(header) + bmap_size + blocks * block_size)) { result = -errno; } } if (close(fd) < 0) { result = -errno; } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'vdi: add bounds checks for blocks_in_image and disk_size header fields (CVE-2014-0144) The maximum blocks_in_image is 0xffffffff / 4, which also limits the maximum disk_size for a VDI image to 1024TB. Note that this is the maximum size that QEMU will currently support with this driver, not necessarily the maximum size allowed by the image format. This also fixes an incorrect error message, a bug introduced by commit 5b7aa9b56d1bfc79916262f380c3fc7961becb50 (Reported by Stefan Weil) Signed-off-by: Jeff Cody <jcody@redhat.com> Signed-off-by: Kevin Wolf <kwolf@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: int xenvif_kthread_guest_rx(void *data) { struct xenvif *vif = data; struct sk_buff *skb; while (!kthread_should_stop()) { wait_event_interruptible(vif->wq, rx_work_todo(vif) || kthread_should_stop()); if (kthread_should_stop()) break; if (vif->rx_queue_purge) { skb_queue_purge(&vif->rx_queue); vif->rx_queue_purge = false; } if (!skb_queue_empty(&vif->rx_queue)) xenvif_rx_action(vif); if (skb_queue_empty(&vif->rx_queue) && netif_queue_stopped(vif->dev)) { del_timer_sync(&vif->wake_queue); xenvif_start_queue(vif); } cond_resched(); } /* Bin any remaining skbs */ while ((skb = skb_dequeue(&vif->rx_queue)) != NULL) dev_kfree_skb(skb); return 0; } ; 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: static struct kioctx *ioctx_alloc(unsigned nr_events) { struct mm_struct *mm = current->mm; struct kioctx *ctx; int err = -ENOMEM; /* * We keep track of the number of available ringbuffer slots, to prevent * overflow (reqs_available), and we also use percpu counters for this. * * So since up to half the slots might be on other cpu's percpu counters * and unavailable, double nr_events so userspace sees what they * expected: additionally, we move req_batch slots to/from percpu * counters at a time, so make sure that isn't 0: */ nr_events = max(nr_events, num_possible_cpus() * 4); nr_events *= 2; /* Prevent overflows */ if ((nr_events > (0x10000000U / sizeof(struct io_event))) || (nr_events > (0x10000000U / sizeof(struct kiocb)))) { pr_debug("ENOMEM: nr_events too high\n"); return ERR_PTR(-EINVAL); } if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL)) return ERR_PTR(-EAGAIN); ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL); if (!ctx) return ERR_PTR(-ENOMEM); ctx->max_reqs = nr_events; if (percpu_ref_init(&ctx->users, free_ioctx_users)) goto err; if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs)) goto err; spin_lock_init(&ctx->ctx_lock); spin_lock_init(&ctx->completion_lock); mutex_init(&ctx->ring_lock); init_waitqueue_head(&ctx->wait); INIT_LIST_HEAD(&ctx->active_reqs); ctx->cpu = alloc_percpu(struct kioctx_cpu); if (!ctx->cpu) goto err; if (aio_setup_ring(ctx) < 0) goto err; atomic_set(&ctx->reqs_available, ctx->nr_events - 1); ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4); if (ctx->req_batch < 1) ctx->req_batch = 1; /* limit the number of system wide aios */ spin_lock(&aio_nr_lock); if (aio_nr + nr_events > (aio_max_nr * 2UL) || aio_nr + nr_events < aio_nr) { spin_unlock(&aio_nr_lock); err = -EAGAIN; goto err; } aio_nr += ctx->max_reqs; spin_unlock(&aio_nr_lock); percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */ err = ioctx_add_table(ctx, mm); if (err) goto err_cleanup; pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n", ctx, ctx->user_id, mm, ctx->nr_events); return ctx; err_cleanup: aio_nr_sub(ctx->max_reqs); err: aio_free_ring(ctx); free_percpu(ctx->cpu); free_percpu(ctx->reqs.pcpu_count); free_percpu(ctx->users.pcpu_count); kmem_cache_free(kioctx_cachep, ctx); pr_debug("error allocating ioctx %d\n", err); return ERR_PTR(err); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'aio: prevent double free in ioctx_alloc ioctx_alloc() calls aio_setup_ring() to allocate a ring. If aio_setup_ring() fails to do so it would call aio_free_ring() before returning, but ioctx_alloc() would call aio_free_ring() again causing a double free of the ring. This is easily reproducible from userspace. Signed-off-by: Sasha Levin <sasha.levin@oracle.com> Signed-off-by: Benjamin LaHaise <bcrl@kvack.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 route_doit(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct nlattr *tb[RTA_MAX+1]; struct net_device *dev; struct rtmsg *rtm; int err; u8 dst; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ASSERT_RTNL(); err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_phonet_policy); if (err < 0) return err; rtm = nlmsg_data(nlh); if (rtm->rtm_table != RT_TABLE_MAIN || rtm->rtm_type != RTN_UNICAST) return -EINVAL; if (tb[RTA_DST] == NULL || tb[RTA_OIF] == NULL) return -EINVAL; dst = nla_get_u8(tb[RTA_DST]); if (dst & 3) /* Phonet addresses only have 6 high-order bits */ return -EINVAL; dev = __dev_get_by_index(net, nla_get_u32(tb[RTA_OIF])); if (dev == NULL) return -ENODEV; if (nlh->nlmsg_type == RTM_NEWROUTE) err = phonet_route_add(dev, dst); else err = phonet_route_del(dev, dst); if (!err) rtm_phonet_notify(nlh->nlmsg_type, dev, dst); return err; } ; 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 dn_fib_rtm_newroute(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct dn_fib_table *tb; struct rtmsg *r = nlmsg_data(nlh); struct nlattr *attrs[RTA_MAX+1]; int err; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (!net_eq(net, &init_net)) return -EINVAL; err = nlmsg_parse(nlh, sizeof(*r), attrs, RTA_MAX, rtm_dn_policy); if (err < 0) return err; tb = dn_fib_get_table(rtm_get_table(attrs, r->rtm_table), 1); if (!tb) return -ENOBUFS; return tb->insert(tb, r, attrs, nlh, &NETLINK_CB(skb)); } ; 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 tc_ctl_action(struct sk_buff *skb, struct nlmsghdr *n) { struct net *net = sock_net(skb->sk); struct nlattr *tca[TCA_ACT_MAX + 1]; u32 portid = skb ? NETLINK_CB(skb).portid : 0; int ret = 0, ovr = 0; if ((n->nlmsg_type != RTM_GETACTION) && !capable(CAP_NET_ADMIN)) return -EPERM; ret = nlmsg_parse(n, sizeof(struct tcamsg), tca, TCA_ACT_MAX, NULL); if (ret < 0) return ret; if (tca[TCA_ACT_TAB] == NULL) { pr_notice("tc_ctl_action: received NO action attribs\n"); return -EINVAL; } /* n->nlmsg_flags & NLM_F_CREATE */ switch (n->nlmsg_type) { case RTM_NEWACTION: /* we are going to assume all other flags * imply create only if it doesn't exist * Note that CREATE | EXCL implies that * but since we want avoid ambiguity (eg when flags * is zero) then just set this */ if (n->nlmsg_flags & NLM_F_REPLACE) ovr = 1; replay: ret = tcf_action_add(net, tca[TCA_ACT_TAB], n, portid, ovr); if (ret == -EAGAIN) goto replay; break; case RTM_DELACTION: ret = tca_action_gd(net, tca[TCA_ACT_TAB], n, portid, RTM_DELACTION); break; case RTM_GETACTION: ret = tca_action_gd(net, tca[TCA_ACT_TAB], n, portid, RTM_GETACTION); break; default: BUG(); } return ret; } ; 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 void unqueue_me_pi(struct futex_q *q) { WARN_ON(plist_node_empty(&q->list)); plist_del(&q->list, &q->list.plist); BUG_ON(!q->pi_state); free_pi_state(q->pi_state); q->pi_state = NULL; spin_unlock(q->lock_ptr); 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 cap_bprm_set_creds(struct linux_binprm *bprm) { const struct cred *old = current_cred(); struct cred *new = bprm->cred; bool effective, has_cap = false; int ret; effective = false; ret = get_file_caps(bprm, &effective, &has_cap); if (ret < 0) return ret; if (!issecure(SECURE_NOROOT)) { /* * If the legacy file capability is set, then don't set privs * for a setuid root binary run by a non-root user. Do set it * for a root user just to cause least surprise to an admin. */ if (has_cap && new->uid != 0 && new->euid == 0) { warn_setuid_and_fcaps_mixed(bprm->filename); goto skip; } /* * To support inheritance of root-permissions and suid-root * executables under compatibility mode, we override the * capability sets for the file. * * If only the real uid is 0, we do not set the effective bit. */ if (new->euid == 0 || new->uid == 0) { /* pP' = (cap_bset & ~0) | (pI & ~0) */ new->cap_permitted = cap_combine(old->cap_bset, old->cap_inheritable); } if (new->euid == 0) effective = true; } skip: /* Don't let someone trace a set[ug]id/setpcap binary with the revised * credentials unless they have the appropriate permit */ if ((new->euid != old->uid || new->egid != old->gid || !cap_issubset(new->cap_permitted, old->cap_permitted)) && bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) { /* downgrade; they get no more than they had, and maybe less */ if (!capable(CAP_SETUID)) { new->euid = new->uid; new->egid = new->gid; } new->cap_permitted = cap_intersect(new->cap_permitted, old->cap_permitted); } new->suid = new->fsuid = new->euid; new->sgid = new->fsgid = new->egid; if (effective) new->cap_effective = new->cap_permitted; else cap_clear(new->cap_effective); bprm->cap_effective = effective; /* * Audit candidate if current->cap_effective is set * * We do not bother to audit if 3 things are true: * 1) cap_effective has all caps * 2) we are root * 3) root is supposed to have all caps (SECURE_NOROOT) * Since this is just a normal root execing a process. * * Number 1 above might fail if you don't have a full bset, but I think * that is interesting information to audit. */ if (!cap_isclear(new->cap_effective)) { if (!cap_issubset(CAP_FULL_SET, new->cap_effective) || new->euid != 0 || new->uid != 0 || issecure(SECURE_NOROOT)) { ret = audit_log_bprm_fcaps(bprm, new, old); if (ret < 0) return ret; } } new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS); return 0; } ; 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: 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, WSGI_LOG_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, WSGI_LOG_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, WSGI_LOG_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, WSGI_LOG_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, WSGI_LOG_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, WSGI_LOG_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, WSGI_LOG_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, WSGI_LOG_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, WSGI_LOG_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, WSGI_LOG_ALERT(errno), wsgi_server, "mod_wsgi (pid=%d): Unable to change to uid=%ld.", getpid(), (long)daemon->group->uid); } /* * 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, WSGI_LOG_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-264'], 'message': 'Local privilege escalation when using daemon mode. (CVE-2014-0240)'</s>
<s>[INST] Given the following code containing errors, provide 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_get_octet_der (const unsigned char *der, int der_len, int *ret_len, unsigned char *str, int str_size, int *str_len) { int len_len = 0; if (der_len <= 0) return ASN1_GENERIC_ERROR; /* if(str==NULL) return ASN1_SUCCESS; */ *str_len = asn1_get_length_der (der, der_len, &len_len); if (*str_len < 0) return ASN1_DER_ERROR; *ret_len = *str_len + len_len; if (str_size >= *str_len) { if (*str_len > 0) memcpy (str, der + len_len, *str_len); } else { return ASN1_MEM_ERROR; } return ASN1_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Allow a NULL value in asn1_read_value() for all types.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lookup_pi_state(u32 uval, struct futex_hash_bucket *hb, union futex_key *key, struct futex_pi_state **ps, struct task_struct *task) { struct futex_pi_state *pi_state = NULL; struct futex_q *this, *next; struct task_struct *p; pid_t pid = uval & FUTEX_TID_MASK; plist_for_each_entry_safe(this, next, &hb->chain, list) { if (match_futex(&this->key, key)) { /* * Another waiter already exists - bump up * the refcount and return its pi_state: */ pi_state = this->pi_state; /* * Userspace might have messed up non-PI and PI futexes */ if (unlikely(!pi_state)) return -EINVAL; WARN_ON(!atomic_read(&pi_state->refcount)); /* * When pi_state->owner is NULL then the owner died * and another waiter is on the fly. pi_state->owner * is fixed up by the task which acquires * pi_state->rt_mutex. * * We do not check for pid == 0 which can happen when * the owner died and robust_list_exit() cleared the * TID. */ if (pid && pi_state->owner) { /* * Bail out if user space manipulated the * futex value. */ if (pid != task_pid_vnr(pi_state->owner)) return -EINVAL; } /* * Protect against a corrupted uval. If uval * is 0x80000000 then pid is 0 and the waiter * bit is set. So the deadlock check in the * calling code has failed and we did not fall * into the check above due to !pid. */ if (task && pi_state->owner == task) return -EDEADLK; atomic_inc(&pi_state->refcount); *ps = pi_state; return 0; } } /* * We are the first waiter - try to look up the real owner and attach * the new pi_state to it, but bail out when TID = 0 */ if (!pid) return -ESRCH; p = futex_find_get_task(pid); if (!p) return -ESRCH; if (!p->mm) { put_task_struct(p); return -EPERM; } /* * We need to look at the task state flags to figure out, * whether the task is exiting. To protect against the do_exit * change of the task flags, we do this protected by * p->pi_lock: */ raw_spin_lock_irq(&p->pi_lock); if (unlikely(p->flags & PF_EXITING)) { /* * The task is on the way out. When PF_EXITPIDONE is * set, we know that the task has finished the * cleanup: */ int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN; raw_spin_unlock_irq(&p->pi_lock); put_task_struct(p); return ret; } pi_state = alloc_pi_state(); /* * Initialize the pi_mutex in locked state and make 'p' * the owner of it: */ rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p); /* Store the key for possible exit cleanups: */ pi_state->key = *key; WARN_ON(!list_empty(&pi_state->list)); list_add(&pi_state->list, &p->pi_state_list); pi_state->owner = p; raw_spin_unlock_irq(&p->pi_lock); put_task_struct(p); *ps = pi_state; return 0; } ; 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: int FUZ_SecurityTest() { char* output; char* input; int i, r; printf("Overflow test (issue 52)...\n"); input = (char*) malloc (20<<20); output = (char*) malloc (20<<20); input[0] = 0x0F; input[1] = 0x00; input[2] = 0x00; for(i = 3; i < 16840000; i++) input[i] = 0xff; r = LZ4_decompress_fast(input, output, 20<<20); free(input); free(output); printf(" Passed (return = %i < 0)\n",r); return 0; } ; 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_compat(struct task_struct *child, addr_t addr, addr_t data) { struct compat_user *dummy32 = NULL; __u32 tmp = (__u32) data; addr_t offset; if (addr < (addr_t) &dummy32->regs.acrs) { struct pt_regs *regs = task_pt_regs(child); /* * psw, gprs, acrs and orig_gpr2 are stored on the stack */ if (addr == (addr_t) &dummy32->regs.psw.mask) { __u32 mask = PSW32_MASK_USER; mask |= is_ri_task(child) ? PSW32_MASK_RI : 0; /* Build a 64 bit psw mask from 31 bit mask. */ if ((tmp & ~mask) != PSW32_USER_BITS) /* Invalid psw mask. */ return -EINVAL; regs->psw.mask = (regs->psw.mask & ~PSW_MASK_USER) | (regs->psw.mask & PSW_MASK_BA) | (__u64)(tmp & mask) << 32; } else if (addr == (addr_t) &dummy32->regs.psw.addr) { /* Build a 64 bit psw address from 31 bit address. */ regs->psw.addr = (__u64) tmp & PSW32_ADDR_INSN; /* Transfer 31 bit amode bit to psw mask. */ regs->psw.mask = (regs->psw.mask & ~PSW_MASK_BA) | (__u64)(tmp & PSW32_ADDR_AMODE); } else { /* gpr 0-15 */ *(__u32*)((addr_t) &regs->psw + addr*2 + 4) = tmp; } } else if (addr < (addr_t) (&dummy32->regs.orig_gpr2)) { /* * access registers are stored in the thread structure */ offset = addr - (addr_t) &dummy32->regs.acrs; *(__u32*)((addr_t) &child->thread.acrs + offset) = tmp; } else if (addr == (addr_t) (&dummy32->regs.orig_gpr2)) { /* * orig_gpr2 is stored on the kernel stack */ *(__u32*)((addr_t) &task_pt_regs(child)->orig_gpr2 + 4) = tmp; } else if (addr < (addr_t) &dummy32->regs.fp_regs) { /* * prevent writess of padding hole between * orig_gpr2 and fp_regs on s390. */ return 0; } else if (addr < (addr_t) (&dummy32->regs.fp_regs + 1)) { /* * floating point regs. are stored in the thread structure */ if (addr == (addr_t) &dummy32->regs.fp_regs.fpc && test_fp_ctl(tmp)) return -EINVAL; offset = addr - (addr_t) &dummy32->regs.fp_regs; *(__u32 *)((addr_t) &child->thread.fp_regs + offset) = tmp; } else if (addr < (addr_t) (&dummy32->regs.per_info + 1)) { /* * Handle access to the per_info structure. */ addr -= (addr_t) &dummy32->regs.per_info; __poke_user_per_compat(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: expand_string_internal(uschar *string, BOOL ket_ends, uschar **left, BOOL skipping, BOOL honour_dollar, BOOL *resetok_p) { int ptr = 0; int size = Ustrlen(string)+ 64; int item_type; uschar *yield = store_get(size); uschar *s = string; uschar *save_expand_nstring[EXPAND_MAXN+1]; int save_expand_nlength[EXPAND_MAXN+1]; BOOL resetok = TRUE; expand_string_forcedfail = FALSE; expand_string_message = US""; while (*s != 0) { uschar *value; uschar name[256]; /* \ escapes the next character, which must exist, or else the expansion fails. There's a special escape, \N, which causes copying of the subject verbatim up to the next \N. Otherwise, the escapes are the standard set. */ if (*s == '\\') { if (s[1] == 0) { expand_string_message = US"\\ at end of string"; goto EXPAND_FAILED; } if (s[1] == 'N') { uschar *t = s + 2; for (s = t; *s != 0; s++) if (*s == '\\' && s[1] == 'N') break; yield = string_cat(yield, &size, &ptr, t, s - t); if (*s != 0) s += 2; } else { uschar ch[1]; ch[0] = string_interpret_escape(&s); s++; yield = string_cat(yield, &size, &ptr, ch, 1); } continue; } /*{*/ /* Anything other than $ is just copied verbatim, unless we are looking for a terminating } character. */ /*{*/ if (ket_ends && *s == '}') break; if (*s != '$' || !honour_dollar) { yield = string_cat(yield, &size, &ptr, s++, 1); continue; } /* No { after the $ - must be a plain name or a number for string match variable. There has to be a fudge for variables that are the names of header fields preceded by "$header_" because header field names can contain any printing characters except space and colon. For those that don't like typing this much, "$h_" is a synonym for "$header_". A non-existent header yields a NULL value; nothing is inserted. */ /*}*/ if (isalpha((*(++s)))) { int len; int newsize = 0; s = read_name(name, sizeof(name), s, US"_"); /* If this is the first thing to be expanded, release the pre-allocated buffer. */ if (ptr == 0 && yield != NULL) { if (resetok) store_reset(yield); yield = NULL; size = 0; } /* Header */ if (Ustrncmp(name, "h_", 2) == 0 || Ustrncmp(name, "rh_", 3) == 0 || Ustrncmp(name, "bh_", 3) == 0 || Ustrncmp(name, "header_", 7) == 0 || Ustrncmp(name, "rheader_", 8) == 0 || Ustrncmp(name, "bheader_", 8) == 0) { BOOL want_raw = (name[0] == 'r')? TRUE : FALSE; uschar *charset = (name[0] == 'b')? NULL : headers_charset; s = read_header_name(name, sizeof(name), s); value = find_header(name, FALSE, &newsize, want_raw, charset); /* If we didn't find the header, and the header contains a closing brace character, this may be a user error where the terminating colon has been omitted. Set a flag to adjust the error message in this case. But there is no error here - nothing gets inserted. */ if (value == NULL) { if (Ustrchr(name, '}') != NULL) malformed_header = TRUE; continue; } } /* Variable */ else { value = find_variable(name, FALSE, skipping, &newsize); if (value == NULL) { expand_string_message = string_sprintf("unknown variable name \"%s\"", name); check_variable_error_message(name); goto EXPAND_FAILED; } } /* If the data is known to be in a new buffer, newsize will be set to the size of that buffer. If this is the first thing in an expansion string, yield will be NULL; just point it at the new store instead of copying. Many expansion strings contain just one reference, so this is a useful optimization, especially for humungous headers. */ len = Ustrlen(value); if (yield == NULL && newsize != 0) { yield = value; size = newsize; ptr = len; } else yield = string_cat(yield, &size, &ptr, value, len); continue; } if (isdigit(*s)) { int n; s = read_number(&n, s); if (n >= 0 && n <= expand_nmax) yield = string_cat(yield, &size, &ptr, expand_nstring[n], expand_nlength[n]); continue; } /* Otherwise, if there's no '{' after $ it's an error. */ /*}*/ if (*s != '{') /*}*/ { expand_string_message = US"$ not followed by letter, digit, or {"; /*}*/ goto EXPAND_FAILED; } /* After { there can be various things, but they all start with an initial word, except for a number for a string match variable. */ if (isdigit((*(++s)))) { int n; s = read_number(&n, s); /*{*/ if (*s++ != '}') { /*{*/ expand_string_message = US"} expected after number"; goto EXPAND_FAILED; } if (n >= 0 && n <= expand_nmax) yield = string_cat(yield, &size, &ptr, expand_nstring[n], expand_nlength[n]); continue; } if (!isalpha(*s)) { expand_string_message = US"letter or digit expected after ${"; /*}*/ goto EXPAND_FAILED; } /* Allow "-" in names to cater for substrings with negative arguments. Since we are checking for known names after { this is OK. */ s = read_name(name, sizeof(name), s, US"_-"); item_type = chop_match(name, item_table, sizeof(item_table)/sizeof(uschar *)); switch(item_type) { /* Call an ACL from an expansion. We feed data in via $acl_arg1 - $acl_arg9. If the ACL returns accept or reject we return content set by "message =" There is currently no limit on recursion; this would have us call acl_check_internal() directly and get a current level from somewhere. See also the acl expansion condition ECOND_ACL and the traditional acl modifier ACLC_ACL. Assume that the function has side-effects on the store that must be preserved. */ case EITEM_ACL: /* ${acl {name} {arg1}{arg2}...} */ { uschar *sub[10]; /* name + arg1-arg9 (which must match number of acl_arg[]) */ uschar *user_msg; switch(read_subs(sub, 10, 1, &s, skipping, TRUE, US"acl", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (skipping) continue; resetok = FALSE; switch(eval_acl(sub, sizeof(sub)/sizeof(*sub), &user_msg)) { case OK: case FAIL: DEBUG(D_expand) debug_printf("acl expansion yield: %s\n", user_msg); if (user_msg) yield = string_cat(yield, &size, &ptr, user_msg, Ustrlen(user_msg)); continue; case DEFER: expand_string_forcedfail = TRUE; default: expand_string_message = string_sprintf("error from acl \"%s\"", sub[0]); goto EXPAND_FAILED; } } /* Handle conditionals - preserve the values of the numerical expansion variables in case they get changed by a regular expression match in the condition. If not, they retain their external settings. At the end of this "if" section, they get restored to their previous values. */ case EITEM_IF: { BOOL cond = FALSE; uschar *next_s; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); while (isspace(*s)) s++; next_s = eval_condition(s, &resetok, skipping? NULL : &cond); if (next_s == NULL) goto EXPAND_FAILED; /* message already set */ DEBUG(D_expand) debug_printf("condition: %.*s\n result: %s\n", (int)(next_s - s), s, cond? "true" : "false"); s = next_s; /* The handling of "yes" and "no" result strings is now in a separate function that is also used by ${lookup} and ${extract} and ${run}. */ switch(process_yesno( skipping, /* were previously skipping */ cond, /* success/failure indicator */ lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"if", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* Restore external setting of expansion variables for continuation at this level. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* Handle database lookups unless locked out. If "skipping" is TRUE, we are expanding an internal string that isn't actually going to be used. All we need to do is check the syntax, so don't do a lookup at all. Preserve the values of the numerical expansion variables in case they get changed by a partial lookup. If not, they retain their external settings. At the end of this "lookup" section, they get restored to their previous values. */ case EITEM_LOOKUP: { int stype, partial, affixlen, starflags; int expand_setup = 0; int nameptr = 0; uschar *key, *filename, *affix; uschar *save_lookup_value = lookup_value; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); if ((expand_forbid & RDO_LOOKUP) != 0) { expand_string_message = US"lookup expansions are not permitted"; goto EXPAND_FAILED; } /* Get the key we are to look up for single-key+file style lookups. Otherwise set the key NULL pro-tem. */ while (isspace(*s)) s++; if (*s == '{') /*}*/ { key = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (key == NULL) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; } else key = NULL; /* Find out the type of database */ if (!isalpha(*s)) { expand_string_message = US"missing lookup type"; goto EXPAND_FAILED; } /* The type is a string that may contain special characters of various kinds. Allow everything except space or { to appear; the actual content is checked by search_findtype_partial. */ /*}*/ while (*s != 0 && *s != '{' && !isspace(*s)) /*}*/ { if (nameptr < sizeof(name) - 1) name[nameptr++] = *s; s++; } name[nameptr] = 0; while (isspace(*s)) s++; /* Now check for the individual search type and any partial or default options. Only those types that are actually in the binary are valid. */ stype = search_findtype_partial(name, &partial, &affix, &affixlen, &starflags); if (stype < 0) { expand_string_message = search_error_message; goto EXPAND_FAILED; } /* Check that a key was provided for those lookup types that need it, and was not supplied for those that use the query style. */ if (!mac_islookup(stype, lookup_querystyle|lookup_absfilequery)) { if (key == NULL) { expand_string_message = string_sprintf("missing {key} for single-" "key \"%s\" lookup", name); goto EXPAND_FAILED; } } else { if (key != NULL) { expand_string_message = string_sprintf("a single key was given for " "lookup type \"%s\", which is not a single-key lookup type", name); goto EXPAND_FAILED; } } /* Get the next string in brackets and expand it. It is the file name for single-key+file lookups, and the whole query otherwise. In the case of queries that also require a file name (e.g. sqlite), the file name comes first. */ if (*s != '{') goto EXPAND_FAILED_CURLY; filename = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (filename == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; /* If this isn't a single-key+file lookup, re-arrange the variables to be appropriate for the search_ functions. For query-style lookups, there is just a "key", and no file name. For the special query-style + file types, the query (i.e. "key") starts with a file name. */ if (key == NULL) { while (isspace(*filename)) filename++; key = filename; if (mac_islookup(stype, lookup_querystyle)) { filename = NULL; } else { if (*filename != '/') { expand_string_message = string_sprintf( "absolute file name expected for \"%s\" lookup", name); goto EXPAND_FAILED; } while (*key != 0 && !isspace(*key)) key++; if (*key != 0) *key++ = 0; } } /* If skipping, don't do the next bit - just lookup_value == NULL, as if the entry was not found. Note that there is no search_close() function. Files are left open in case of re-use. At suitable places in higher logic, search_tidyup() is called to tidy all open files. This can save opening the same file several times. However, files may also get closed when others are opened, if too many are open at once. The rule is that a handle should not be used after a second search_open(). Request that a partial search sets up $1 and maybe $2 by passing expand_setup containing zero. If its value changes, reset expand_nmax, since new variables will have been set. Note that at the end of this "lookup" section, the old numeric variables are restored. */ if (skipping) lookup_value = NULL; else { void *handle = search_open(filename, stype, 0, NULL, NULL); if (handle == NULL) { expand_string_message = search_error_message; goto EXPAND_FAILED; } lookup_value = search_find(handle, filename, key, partial, affix, affixlen, starflags, &expand_setup); if (search_find_defer) { expand_string_message = string_sprintf("lookup of \"%s\" gave DEFER: %s", string_printing2(key, FALSE), search_error_message); goto EXPAND_FAILED; } if (expand_setup > 0) expand_nmax = expand_setup; } /* The handling of "yes" and "no" result strings is now in a separate function that is also used by ${if} and ${extract}. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"lookup", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* Restore external setting of expansion variables for carrying on at this level, and continue. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* If Perl support is configured, handle calling embedded perl subroutines, unless locked out at this time. Syntax is ${perl{sub}} or ${perl{sub}{arg}} or ${perl{sub}{arg1}{arg2}} or up to a maximum of EXIM_PERL_MAX_ARGS arguments (defined below). */ #define EXIM_PERL_MAX_ARGS 8 case EITEM_PERL: #ifndef EXIM_PERL expand_string_message = US"\"${perl\" encountered, but this facility " /*}*/ "is not included in this binary"; goto EXPAND_FAILED; #else /* EXIM_PERL */ { uschar *sub_arg[EXIM_PERL_MAX_ARGS + 2]; uschar *new_yield; if ((expand_forbid & RDO_PERL) != 0) { expand_string_message = US"Perl calls are not permitted"; goto EXPAND_FAILED; } switch(read_subs(sub_arg, EXIM_PERL_MAX_ARGS + 1, 1, &s, skipping, TRUE, US"perl", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Start the interpreter if necessary */ if (!opt_perl_started) { uschar *initerror; if (opt_perl_startup == NULL) { expand_string_message = US"A setting of perl_startup is needed when " "using the Perl interpreter"; goto EXPAND_FAILED; } DEBUG(D_any) debug_printf("Starting Perl interpreter\n"); initerror = init_perl(opt_perl_startup); if (initerror != NULL) { expand_string_message = string_sprintf("error in perl_startup code: %s\n", initerror); goto EXPAND_FAILED; } opt_perl_started = TRUE; } /* Call the function */ sub_arg[EXIM_PERL_MAX_ARGS + 1] = NULL; new_yield = call_perl_cat(yield, &size, &ptr, &expand_string_message, sub_arg[0], sub_arg + 1); /* NULL yield indicates failure; if the message pointer has been set to NULL, the yield was undef, indicating a forced failure. Otherwise the message will indicate some kind of Perl error. */ if (new_yield == NULL) { if (expand_string_message == NULL) { expand_string_message = string_sprintf("Perl subroutine \"%s\" returned undef to force " "failure", sub_arg[0]); expand_string_forcedfail = TRUE; } goto EXPAND_FAILED; } /* Yield succeeded. Ensure forcedfail is unset, just in case it got set during a callback from Perl. */ expand_string_forcedfail = FALSE; yield = new_yield; continue; } #endif /* EXIM_PERL */ /* Transform email address to "prvs" scheme to use as BATV-signed return path */ case EITEM_PRVS: { uschar *sub_arg[3]; uschar *p,*domain; switch(read_subs(sub_arg, 3, 2, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* sub_arg[0] is the address */ domain = Ustrrchr(sub_arg[0],'@'); if ( (domain == NULL) || (domain == sub_arg[0]) || (Ustrlen(domain) == 1) ) { expand_string_message = US"prvs first argument must be a qualified email address"; goto EXPAND_FAILED; } /* Calculate the hash. The second argument must be a single-digit key number, or unset. */ if (sub_arg[2] != NULL && (!isdigit(sub_arg[2][0]) || sub_arg[2][1] != 0)) { expand_string_message = US"prvs second argument must be a single digit"; goto EXPAND_FAILED; } p = prvs_hmac_sha1(sub_arg[0],sub_arg[1],sub_arg[2],prvs_daystamp(7)); if (p == NULL) { expand_string_message = US"prvs hmac-sha1 conversion failed"; goto EXPAND_FAILED; } /* Now separate the domain from the local part */ *domain++ = '\0'; yield = string_cat(yield,&size,&ptr,US"prvs=",5); string_cat(yield,&size,&ptr,(sub_arg[2] != NULL) ? sub_arg[2] : US"0", 1); string_cat(yield,&size,&ptr,prvs_daystamp(7),3); string_cat(yield,&size,&ptr,p,6); string_cat(yield,&size,&ptr,US"=",1); string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0])); string_cat(yield,&size,&ptr,US"@",1); string_cat(yield,&size,&ptr,domain,Ustrlen(domain)); continue; } /* Check a prvs-encoded address for validity */ case EITEM_PRVSCHECK: { uschar *sub_arg[3]; int mysize = 0, myptr = 0; const pcre *re; uschar *p; /* TF: Ugliness: We want to expand parameter 1 first, then set up expansion variables that are used in the expansion of parameter 2. So we clone the string for the first expansion, where we only expand parameter 1. PH: Actually, that isn't necessary. The read_subs() function is designed to work this way for the ${if and ${lookup expansions. I've tidied the code. */ /* Reset expansion variables */ prvscheck_result = NULL; prvscheck_address = NULL; prvscheck_keynum = NULL; switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } re = regex_must_compile(US"^prvs\\=([0-9])([0-9]{3})([A-F0-9]{6})\\=(.+)\\@(.+)$", TRUE,FALSE); if (regex_match_and_setup(re,sub_arg[0],0,-1)) { uschar *local_part = string_copyn(expand_nstring[4],expand_nlength[4]); uschar *key_num = string_copyn(expand_nstring[1],expand_nlength[1]); uschar *daystamp = string_copyn(expand_nstring[2],expand_nlength[2]); uschar *hash = string_copyn(expand_nstring[3],expand_nlength[3]); uschar *domain = string_copyn(expand_nstring[5],expand_nlength[5]); DEBUG(D_expand) debug_printf("prvscheck localpart: %s\n", local_part); DEBUG(D_expand) debug_printf("prvscheck key number: %s\n", key_num); DEBUG(D_expand) debug_printf("prvscheck daystamp: %s\n", daystamp); DEBUG(D_expand) debug_printf("prvscheck hash: %s\n", hash); DEBUG(D_expand) debug_printf("prvscheck domain: %s\n", domain); /* Set up expansion variables */ prvscheck_address = string_cat(NULL, &mysize, &myptr, local_part, Ustrlen(local_part)); string_cat(prvscheck_address,&mysize,&myptr,US"@",1); string_cat(prvscheck_address,&mysize,&myptr,domain,Ustrlen(domain)); prvscheck_address[myptr] = '\0'; prvscheck_keynum = string_copy(key_num); /* Now expand the second argument */ switch(read_subs(sub_arg, 1, 1, &s, skipping, FALSE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Now we have the key and can check the address. */ p = prvs_hmac_sha1(prvscheck_address, sub_arg[0], prvscheck_keynum, daystamp); if (p == NULL) { expand_string_message = US"hmac-sha1 conversion failed"; goto EXPAND_FAILED; } DEBUG(D_expand) debug_printf("prvscheck: received hash is %s\n", hash); DEBUG(D_expand) debug_printf("prvscheck: own hash is %s\n", p); if (Ustrcmp(p,hash) == 0) { /* Success, valid BATV address. Now check the expiry date. */ uschar *now = prvs_daystamp(0); unsigned int inow = 0,iexpire = 1; (void)sscanf(CS now,"%u",&inow); (void)sscanf(CS daystamp,"%u",&iexpire); /* When "iexpire" is < 7, a "flip" has occured. Adjust "inow" accordingly. */ if ( (iexpire < 7) && (inow >= 993) ) inow = 0; if (iexpire >= inow) { prvscheck_result = US"1"; DEBUG(D_expand) debug_printf("prvscheck: success, $pvrs_result set to 1\n"); } else { prvscheck_result = NULL; DEBUG(D_expand) debug_printf("prvscheck: signature expired, $pvrs_result unset\n"); } } else { prvscheck_result = NULL; DEBUG(D_expand) debug_printf("prvscheck: hash failure, $pvrs_result unset\n"); } /* Now expand the final argument. We leave this till now so that it can include $prvscheck_result. */ switch(read_subs(sub_arg, 1, 0, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (sub_arg[0] == NULL || *sub_arg[0] == '\0') yield = string_cat(yield,&size,&ptr,prvscheck_address,Ustrlen(prvscheck_address)); else yield = string_cat(yield,&size,&ptr,sub_arg[0],Ustrlen(sub_arg[0])); /* Reset the "internal" variables afterwards, because they are in dynamic store that will be reclaimed if the expansion succeeded. */ prvscheck_address = NULL; prvscheck_keynum = NULL; } else { /* Does not look like a prvs encoded address, return the empty string. We need to make sure all subs are expanded first, so as to skip over the entire item. */ switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"prvs", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } } continue; } /* Handle "readfile" to insert an entire file */ case EITEM_READFILE: { FILE *f; uschar *sub_arg[2]; if ((expand_forbid & RDO_READFILE) != 0) { expand_string_message = US"file insertions are not permitted"; goto EXPAND_FAILED; } switch(read_subs(sub_arg, 2, 1, &s, skipping, TRUE, US"readfile", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Open the file and read it */ f = Ufopen(sub_arg[0], "rb"); if (f == NULL) { expand_string_message = string_open_failed(errno, "%s", sub_arg[0]); goto EXPAND_FAILED; } yield = cat_file(f, yield, &size, &ptr, sub_arg[1]); (void)fclose(f); continue; } /* Handle "readsocket" to insert data from a Unix domain socket */ case EITEM_READSOCK: { int fd; int timeout = 5; int save_ptr = ptr; FILE *f; struct sockaddr_un sockun; /* don't call this "sun" ! */ uschar *arg; uschar *sub_arg[4]; if ((expand_forbid & RDO_READSOCK) != 0) { expand_string_message = US"socket insertions are not permitted"; goto EXPAND_FAILED; } /* Read up to 4 arguments, but don't do the end of item check afterwards, because there may be a string for expansion on failure. */ switch(read_subs(sub_arg, 4, 2, &s, skipping, FALSE, US"readsocket", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: /* Won't occur: no end check */ case 3: goto EXPAND_FAILED; } /* Sort out timeout, if given */ if (sub_arg[2] != NULL) { timeout = readconf_readtime(sub_arg[2], 0, FALSE); if (timeout < 0) { expand_string_message = string_sprintf("bad time value %s", sub_arg[2]); goto EXPAND_FAILED; } } else sub_arg[3] = NULL; /* No eol if no timeout */ /* If skipping, we don't actually do anything. Otherwise, arrange to connect to either an IP or a Unix socket. */ if (!skipping) { /* Handle an IP (internet) domain */ if (Ustrncmp(sub_arg[0], "inet:", 5) == 0) { int port; uschar *server_name = sub_arg[0] + 5; uschar *port_name = Ustrrchr(server_name, ':'); /* Sort out the port */ if (port_name == NULL) { expand_string_message = string_sprintf("missing port for readsocket %s", sub_arg[0]); goto EXPAND_FAILED; } *port_name++ = 0; /* Terminate server name */ if (isdigit(*port_name)) { uschar *end; port = Ustrtol(port_name, &end, 0); if (end != port_name + Ustrlen(port_name)) { expand_string_message = string_sprintf("invalid port number %s", port_name); goto EXPAND_FAILED; } } else { struct servent *service_info = getservbyname(CS port_name, "tcp"); if (service_info == NULL) { expand_string_message = string_sprintf("unknown port \"%s\"", port_name); goto EXPAND_FAILED; } port = ntohs(service_info->s_port); } if ((fd = ip_connectedsocket(SOCK_STREAM, server_name, port, port, timeout, NULL, &expand_string_message)) < 0) goto SOCK_FAIL; } /* Handle a Unix domain socket */ else { int rc; if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) { expand_string_message = string_sprintf("failed to create socket: %s", strerror(errno)); goto SOCK_FAIL; } sockun.sun_family = AF_UNIX; sprintf(sockun.sun_path, "%.*s", (int)(sizeof(sockun.sun_path)-1), sub_arg[0]); sigalrm_seen = FALSE; alarm(timeout); rc = connect(fd, (struct sockaddr *)(&sockun), sizeof(sockun)); alarm(0); if (sigalrm_seen) { expand_string_message = US "socket connect timed out"; goto SOCK_FAIL; } if (rc < 0) { expand_string_message = string_sprintf("failed to connect to socket " "%s: %s", sub_arg[0], strerror(errno)); goto SOCK_FAIL; } } DEBUG(D_expand) debug_printf("connected to socket %s\n", sub_arg[0]); /* Allow sequencing of test actions */ if (running_in_test_harness) millisleep(100); /* Write the request string, if not empty */ if (sub_arg[1][0] != 0) { int len = Ustrlen(sub_arg[1]); DEBUG(D_expand) debug_printf("writing \"%s\" to socket\n", sub_arg[1]); if (write(fd, sub_arg[1], len) != len) { expand_string_message = string_sprintf("request write to socket " "failed: %s", strerror(errno)); goto SOCK_FAIL; } } /* Shut down the sending side of the socket. This helps some servers to recognise that it is their turn to do some work. Just in case some system doesn't have this function, make it conditional. */ #ifdef SHUT_WR shutdown(fd, SHUT_WR); #endif if (running_in_test_harness) millisleep(100); /* Now we need to read from the socket, under a timeout. The function that reads a file can be used. */ f = fdopen(fd, "rb"); sigalrm_seen = FALSE; alarm(timeout); yield = cat_file(f, yield, &size, &ptr, sub_arg[3]); alarm(0); (void)fclose(f); /* After a timeout, we restore the pointer in the result, that is, make sure we add nothing from the socket. */ if (sigalrm_seen) { ptr = save_ptr; expand_string_message = US "socket read timed out"; goto SOCK_FAIL; } } /* The whole thing has worked (or we were skipping). If there is a failure string following, we need to skip it. */ if (*s == '{') { if (expand_string_internal(s+1, TRUE, &s, TRUE, TRUE, &resetok) == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; } if (*s++ != '}') goto EXPAND_FAILED_CURLY; continue; /* Come here on failure to create socket, connect socket, write to the socket, or timeout on reading. If another substring follows, expand and use it. Otherwise, those conditions give expand errors. */ SOCK_FAIL: if (*s != '{') goto EXPAND_FAILED; DEBUG(D_any) debug_printf("%s\n", expand_string_message); arg = expand_string_internal(s+1, TRUE, &s, FALSE, TRUE, &resetok); if (arg == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, arg, Ustrlen(arg)); if (*s++ != '}') goto EXPAND_FAILED_CURLY; while (isspace(*s)) s++; if (*s++ != '}') goto EXPAND_FAILED_CURLY; continue; } /* Handle "run" to execute a program. */ case EITEM_RUN: { FILE *f; uschar *arg; uschar **argv; pid_t pid; int fd_in, fd_out; int lsize = 0; int lptr = 0; if ((expand_forbid & RDO_RUN) != 0) { expand_string_message = US"running a command is not permitted"; goto EXPAND_FAILED; } while (isspace(*s)) s++; if (*s != '{') goto EXPAND_FAILED_CURLY; arg = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (arg == NULL) goto EXPAND_FAILED; while (isspace(*s)) s++; if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (skipping) /* Just pretend it worked when we're skipping */ { runrc = 0; } else { if (!transport_set_up_command(&argv, /* anchor for arg list */ arg, /* raw command */ FALSE, /* don't expand the arguments */ 0, /* not relevant when... */ NULL, /* no transporting address */ US"${run} expansion", /* for error messages */ &expand_string_message)) /* where to put error message */ { goto EXPAND_FAILED; } /* Create the child process, making it a group leader. */ pid = child_open(argv, NULL, 0077, &fd_in, &fd_out, TRUE); if (pid < 0) { expand_string_message = string_sprintf("couldn't create child process: %s", strerror(errno)); goto EXPAND_FAILED; } /* Nothing is written to the standard input. */ (void)close(fd_in); /* Read the pipe to get the command's output into $value (which is kept in lookup_value). Read during execution, so that if the output exceeds the OS pipe buffer limit, we don't block forever. */ f = fdopen(fd_out, "rb"); sigalrm_seen = FALSE; alarm(60); lookup_value = cat_file(f, lookup_value, &lsize, &lptr, NULL); alarm(0); (void)fclose(f); /* Wait for the process to finish, applying the timeout, and inspect its return code for serious disasters. Simple non-zero returns are passed on. */ if (sigalrm_seen == TRUE || (runrc = child_close(pid, 30)) < 0) { if (sigalrm_seen == TRUE || runrc == -256) { expand_string_message = string_sprintf("command timed out"); killpg(pid, SIGKILL); /* Kill the whole process group */ } else if (runrc == -257) expand_string_message = string_sprintf("wait() failed: %s", strerror(errno)); else expand_string_message = string_sprintf("command killed by signal %d", -runrc); goto EXPAND_FAILED; } } /* Process the yes/no strings; $value may be useful in both cases */ switch(process_yesno( skipping, /* were previously skipping */ runrc == 0, /* success/failure indicator */ lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"run", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } continue; } /* Handle character translation for "tr" */ case EITEM_TR: { int oldptr = ptr; int o2m; uschar *sub[3]; switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"tr", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, sub[0], Ustrlen(sub[0])); o2m = Ustrlen(sub[2]) - 1; if (o2m >= 0) for (; oldptr < ptr; oldptr++) { uschar *m = Ustrrchr(sub[1], yield[oldptr]); if (m != NULL) { int o = m - sub[1]; yield[oldptr] = sub[2][(o < o2m)? o : o2m]; } } continue; } /* Handle "hash", "length", "nhash", and "substr" when they are given with expanded arguments. */ case EITEM_HASH: case EITEM_LENGTH: case EITEM_NHASH: case EITEM_SUBSTR: { int i; int len; uschar *ret; int val[2] = { 0, -1 }; uschar *sub[3]; /* "length" takes only 2 arguments whereas the others take 2 or 3. Ensure that sub[2] is set in the ${length } case. */ sub[2] = NULL; switch(read_subs(sub, (item_type == EITEM_LENGTH)? 2:3, 2, &s, skipping, TRUE, name, &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Juggle the arguments if there are only two of them: always move the string to the last position and make ${length{n}{str}} equivalent to ${substr{0}{n}{str}}. See the defaults for val[] above. */ if (sub[2] == NULL) { sub[2] = sub[1]; sub[1] = NULL; if (item_type == EITEM_LENGTH) { sub[1] = sub[0]; sub[0] = NULL; } } for (i = 0; i < 2; i++) { if (sub[i] == NULL) continue; val[i] = (int)Ustrtol(sub[i], &ret, 10); if (*ret != 0 || (i != 0 && val[i] < 0)) { expand_string_message = string_sprintf("\"%s\" is not a%s number " "(in \"%s\" expansion)", sub[i], (i != 0)? " positive" : "", name); goto EXPAND_FAILED; } } ret = (item_type == EITEM_HASH)? compute_hash(sub[2], val[0], val[1], &len) : (item_type == EITEM_NHASH)? compute_nhash(sub[2], val[0], val[1], &len) : extract_substr(sub[2], val[0], val[1], &len); if (ret == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, ret, len); continue; } /* Handle HMAC computation: ${hmac{<algorithm>}{<secret>}{<text>}} This code originally contributed by Steve Haslam. It currently supports the use of MD5 and SHA-1 hashes. We need some workspace that is large enough to handle all the supported hash types. Use macros to set the sizes rather than be too elaborate. */ #define MAX_HASHLEN 20 #define MAX_HASHBLOCKLEN 64 case EITEM_HMAC: { uschar *sub[3]; md5 md5_base; sha1 sha1_base; void *use_base; int type, i; int hashlen; /* Number of octets for the hash algorithm's output */ int hashblocklen; /* Number of octets the hash algorithm processes */ uschar *keyptr, *p; unsigned int keylen; uschar keyhash[MAX_HASHLEN]; uschar innerhash[MAX_HASHLEN]; uschar finalhash[MAX_HASHLEN]; uschar finalhash_hex[2*MAX_HASHLEN]; uschar innerkey[MAX_HASHBLOCKLEN]; uschar outerkey[MAX_HASHBLOCKLEN]; switch (read_subs(sub, 3, 3, &s, skipping, TRUE, name, &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } if (Ustrcmp(sub[0], "md5") == 0) { type = HMAC_MD5; use_base = &md5_base; hashlen = 16; hashblocklen = 64; } else if (Ustrcmp(sub[0], "sha1") == 0) { type = HMAC_SHA1; use_base = &sha1_base; hashlen = 20; hashblocklen = 64; } else { expand_string_message = string_sprintf("hmac algorithm \"%s\" is not recognised", sub[0]); goto EXPAND_FAILED; } keyptr = sub[1]; keylen = Ustrlen(keyptr); /* If the key is longer than the hash block length, then hash the key first */ if (keylen > hashblocklen) { chash_start(type, use_base); chash_end(type, use_base, keyptr, keylen, keyhash); keyptr = keyhash; keylen = hashlen; } /* Now make the inner and outer key values */ memset(innerkey, 0x36, hashblocklen); memset(outerkey, 0x5c, hashblocklen); for (i = 0; i < keylen; i++) { innerkey[i] ^= keyptr[i]; outerkey[i] ^= keyptr[i]; } /* Now do the hashes */ chash_start(type, use_base); chash_mid(type, use_base, innerkey); chash_end(type, use_base, sub[2], Ustrlen(sub[2]), innerhash); chash_start(type, use_base); chash_mid(type, use_base, outerkey); chash_end(type, use_base, innerhash, hashlen, finalhash); /* Encode the final hash as a hex string */ p = finalhash_hex; for (i = 0; i < hashlen; i++) { *p++ = hex_digits[(finalhash[i] & 0xf0) >> 4]; *p++ = hex_digits[finalhash[i] & 0x0f]; } DEBUG(D_any) debug_printf("HMAC[%s](%.*s,%.*s)=%.*s\n", sub[0], (int)keylen, keyptr, Ustrlen(sub[2]), sub[2], hashlen*2, finalhash_hex); yield = string_cat(yield, &size, &ptr, finalhash_hex, hashlen*2); } continue; /* Handle global substitution for "sg" - like Perl's s/xxx/yyy/g operator. We have to save the numerical variables and restore them afterwards. */ case EITEM_SG: { const pcre *re; int moffset, moffsetextra, slen; int roffset; int emptyopt; const uschar *rerror; uschar *subject; uschar *sub[3]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); switch(read_subs(sub, 3, 3, &s, skipping, TRUE, US"sg", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* Compile the regular expression */ re = pcre_compile(CS sub[1], PCRE_COPT, (const char **)&rerror, &roffset, NULL); if (re == NULL) { expand_string_message = string_sprintf("regular expression error in " "\"%s\": %s at offset %d", sub[1], rerror, roffset); goto EXPAND_FAILED; } /* Now run a loop to do the substitutions as often as necessary. It ends when there are no more matches. Take care over matches of the null string; do the same thing as Perl does. */ subject = sub[0]; slen = Ustrlen(sub[0]); moffset = moffsetextra = 0; emptyopt = 0; for (;;) { int ovector[3*(EXPAND_MAXN+1)]; int n = pcre_exec(re, NULL, CS subject, slen, moffset + moffsetextra, PCRE_EOPT | emptyopt, ovector, sizeof(ovector)/sizeof(int)); int nn; uschar *insert; /* No match - if we previously set PCRE_NOTEMPTY after a null match, this is not necessarily the end. We want to repeat the match from one character further along, but leaving the basic offset the same (for copying below). We can't be at the end of the string - that was checked before setting PCRE_NOTEMPTY. If PCRE_NOTEMPTY is not set, we are finished; copy the remaining string and end the loop. */ if (n < 0) { if (emptyopt != 0) { moffsetextra = 1; emptyopt = 0; continue; } yield = string_cat(yield, &size, &ptr, subject+moffset, slen-moffset); break; } /* Match - set up for expanding the replacement. */ if (n == 0) n = EXPAND_MAXN + 1; expand_nmax = 0; for (nn = 0; nn < n*2; nn += 2) { expand_nstring[expand_nmax] = subject + ovector[nn]; expand_nlength[expand_nmax++] = ovector[nn+1] - ovector[nn]; } expand_nmax--; /* Copy the characters before the match, plus the expanded insertion. */ yield = string_cat(yield, &size, &ptr, subject + moffset, ovector[0] - moffset); insert = expand_string(sub[2]); if (insert == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, insert, Ustrlen(insert)); moffset = ovector[1]; moffsetextra = 0; emptyopt = 0; /* If we have matched an empty string, first check to see if we are at the end of the subject. If so, the loop is over. Otherwise, mimic what Perl's /g options does. This turns out to be rather cunning. First we set PCRE_NOTEMPTY and PCRE_ANCHORED and try the match a non-empty string at the same point. If this fails (picked up above) we advance to the next character. */ if (ovector[0] == ovector[1]) { if (ovector[0] == slen) break; emptyopt = PCRE_NOTEMPTY | PCRE_ANCHORED; } } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* Handle keyed and numbered substring extraction. If the first argument consists entirely of digits, then a numerical extraction is assumed. */ case EITEM_EXTRACT: { int i; int j = 2; int field_number = 1; BOOL field_number_set = FALSE; uschar *save_lookup_value = lookup_value; uschar *sub[3]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the arguments */ for (i = 0; i < j; i++) { while (isspace(*s)) s++; if (*s == '{') /*}*/ { sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (sub[i] == NULL) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* After removal of leading and trailing white space, the first argument must not be empty; if it consists entirely of digits (optionally preceded by a minus sign), this is a numerical extraction, and we expect 3 arguments. */ if (i == 0) { int len; int x = 0; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; if (*p == 0 && !skipping) { expand_string_message = US"first argument of \"extract\" must " "not be empty"; goto EXPAND_FAILED; } if (*p == '-') { field_number = -1; p++; } while (*p != 0 && isdigit(*p)) x = x * 10 + *p++ - '0'; if (*p == 0) { field_number *= x; j = 3; /* Need 3 args */ field_number_set = TRUE; } } } else goto EXPAND_FAILED_CURLY; } /* Extract either the numbered or the keyed substring into $value. If skipping, just pretend the extraction failed. */ lookup_value = skipping? NULL : field_number_set? expand_gettokened(field_number, sub[1], sub[2]) : expand_getkeyed(sub[0], sub[1]); /* If no string follows, $value gets substituted; otherwise there can be yes/no strings, as for lookup or if. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } /* return the Nth item from a list */ case EITEM_LISTEXTRACT: { int i; int field_number = 1; uschar *save_lookup_value = lookup_value; uschar *sub[2]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the field & list arguments */ for (i = 0; i < 2; i++) { while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; sub[i] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub[i]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* After removal of leading and trailing white space, the first argument must be numeric and nonempty. */ if (i == 0) { int len; int x = 0; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; if (!*p && !skipping) { expand_string_message = US"first argument of \"listextract\" must " "not be empty"; goto EXPAND_FAILED; } if (*p == '-') { field_number = -1; p++; } while (*p && isdigit(*p)) x = x * 10 + *p++ - '0'; if (*p) { expand_string_message = US"first argument of \"listextract\" must " "be numeric"; goto EXPAND_FAILED; } field_number *= x; } } /* Extract the numbered element into $value. If skipping, just pretend the extraction failed. */ lookup_value = skipping? NULL : expand_getlistele(field_number, sub[1]); /* If no string follows, $value gets substituted; otherwise there can be yes/no strings, as for lookup or if. */ switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } /* All done - restore numerical variables. */ restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } #ifdef SUPPORT_TLS case EITEM_CERTEXTRACT: { uschar *save_lookup_value = lookup_value; uschar *sub[2]; int save_expand_nmax = save_expand_strings(save_expand_nstring, save_expand_nlength); /* Read the field argument */ while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; sub[0] = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub[0]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; /* strip spaces fore & aft */ { int len; uschar *p = sub[0]; while (isspace(*p)) p++; sub[0] = p; len = Ustrlen(p); while (len > 0 && isspace(p[len-1])) len--; p[len] = 0; } /* inspect the cert argument */ while (isspace(*s)) s++; if (*s != '{') /*}*/ goto EXPAND_FAILED_CURLY; if (*++s != '$') { expand_string_message = US"second argument of \"certextract\" must " "be a certificate variable"; goto EXPAND_FAILED; } sub[1] = expand_string_internal(s+1, TRUE, &s, skipping, FALSE, &resetok); if (!sub[1]) goto EXPAND_FAILED; /*{*/ if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (skipping) lookup_value = NULL; else { lookup_value = expand_getcertele(sub[0], sub[1]); if (*expand_string_message) goto EXPAND_FAILED; } switch(process_yesno( skipping, /* were previously skipping */ lookup_value != NULL, /* success/failure indicator */ save_lookup_value, /* value to reset for string2 */ &s, /* input pointer */ &yield, /* output pointer */ &size, /* output size */ &ptr, /* output current point */ US"extract", /* condition type */ &resetok)) { case 1: goto EXPAND_FAILED; /* when all is well, the */ case 2: goto EXPAND_FAILED_CURLY; /* returned value is 0 */ } restore_expand_strings(save_expand_nmax, save_expand_nstring, save_expand_nlength); continue; } #endif /*SUPPORT_TLS*/ /* Handle list operations */ case EITEM_FILTER: case EITEM_MAP: case EITEM_REDUCE: { int sep = 0; int save_ptr = ptr; uschar outsep[2] = { '\0', '\0' }; uschar *list, *expr, *temp; uschar *save_iterate_item = iterate_item; uschar *save_lookup_value = lookup_value; while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; list = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok); if (list == NULL) goto EXPAND_FAILED; if (*s++ != '}') goto EXPAND_FAILED_CURLY; if (item_type == EITEM_REDUCE) { while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; temp = expand_string_internal(s, TRUE, &s, skipping, TRUE, &resetok); if (temp == NULL) goto EXPAND_FAILED; lookup_value = temp; if (*s++ != '}') goto EXPAND_FAILED_CURLY; } while (isspace(*s)) s++; if (*s++ != '{') goto EXPAND_FAILED_CURLY; expr = s; /* For EITEM_FILTER, call eval_condition once, with result discarded (as if scanning a "false" part). This allows us to find the end of the condition, because if the list is empty, we won't actually evaluate the condition for real. For EITEM_MAP and EITEM_REDUCE, do the same, using the normal internal expansion function. */ if (item_type == EITEM_FILTER) { temp = eval_condition(expr, &resetok, NULL); if (temp != NULL) s = temp; } else { temp = expand_string_internal(s, TRUE, &s, TRUE, TRUE, &resetok); } if (temp == NULL) { expand_string_message = string_sprintf("%s inside \"%s\" item", expand_string_message, name); goto EXPAND_FAILED; } while (isspace(*s)) s++; if (*s++ != '}') { /*{*/ expand_string_message = string_sprintf("missing } at end of condition " "or expression inside \"%s\"", name); goto EXPAND_FAILED; } while (isspace(*s)) s++; /*{*/ if (*s++ != '}') { /*{*/ expand_string_message = string_sprintf("missing } at end of \"%s\"", name); goto EXPAND_FAILED; } /* If we are skipping, we can now just move on to the next item. When processing for real, we perform the iteration. */ if (skipping) continue; while ((iterate_item = string_nextinlist(&list, &sep, NULL, 0)) != NULL) { *outsep = (uschar)sep; /* Separator as a string */ DEBUG(D_expand) debug_printf("%s: $item = \"%s\"\n", name, iterate_item); if (item_type == EITEM_FILTER) { BOOL condresult; if (eval_condition(expr, &resetok, &condresult) == NULL) { iterate_item = save_iterate_item; lookup_value = save_lookup_value; expand_string_message = string_sprintf("%s inside \"%s\" condition", expand_string_message, name); goto EXPAND_FAILED; } DEBUG(D_expand) debug_printf("%s: condition is %s\n", name, condresult? "true":"false"); if (condresult) temp = iterate_item; /* TRUE => include this item */ else continue; /* FALSE => skip this item */ } /* EITEM_MAP and EITEM_REDUCE */ else { temp = expand_string_internal(expr, TRUE, NULL, skipping, TRUE, &resetok); if (temp == NULL) { iterate_item = save_iterate_item; expand_string_message = string_sprintf("%s inside \"%s\" item", expand_string_message, name); goto EXPAND_FAILED; } if (item_type == EITEM_REDUCE) { lookup_value = temp; /* Update the value of $value */ continue; /* and continue the iteration */ } } /* We reach here for FILTER if the condition is true, always for MAP, and never for REDUCE. The value in "temp" is to be added to the output list that is being created, ensuring that any occurrences of the separator character are doubled. Unless we are dealing with the first item of the output list, add in a space if the new item begins with the separator character, or is an empty string. */ if (ptr != save_ptr && (temp[0] == *outsep || temp[0] == 0)) yield = string_cat(yield, &size, &ptr, US" ", 1); /* Add the string in "temp" to the output list that we are building, This is done in chunks by searching for the separator character. */ for (;;) { size_t seglen = Ustrcspn(temp, outsep); yield = string_cat(yield, &size, &ptr, temp, seglen + 1); /* If we got to the end of the string we output one character too many; backup and end the loop. Otherwise arrange to double the separator. */ if (temp[seglen] == '\0') { ptr--; break; } yield = string_cat(yield, &size, &ptr, outsep, 1); temp += seglen + 1; } /* Output a separator after the string: we will remove the redundant final one at the end. */ yield = string_cat(yield, &size, &ptr, outsep, 1); } /* End of iteration over the list loop */ /* REDUCE has generated no output above: output the final value of $value. */ if (item_type == EITEM_REDUCE) { yield = string_cat(yield, &size, &ptr, lookup_value, Ustrlen(lookup_value)); lookup_value = save_lookup_value; /* Restore $value */ } /* FILTER and MAP generate lists: if they have generated anything, remove the redundant final separator. Even though an empty item at the end of a list does not count, this is tidier. */ else if (ptr != save_ptr) ptr--; /* Restore preserved $item */ iterate_item = save_iterate_item; continue; } /* If ${dlfunc } support is configured, handle calling dynamically-loaded functions, unless locked out at this time. Syntax is ${dlfunc{file}{func}} or ${dlfunc{file}{func}{arg}} or ${dlfunc{file}{func}{arg1}{arg2}} or up to a maximum of EXPAND_DLFUNC_MAX_ARGS arguments (defined below). */ #define EXPAND_DLFUNC_MAX_ARGS 8 case EITEM_DLFUNC: #ifndef EXPAND_DLFUNC expand_string_message = US"\"${dlfunc\" encountered, but this facility " /*}*/ "is not included in this binary"; goto EXPAND_FAILED; #else /* EXPAND_DLFUNC */ { tree_node *t; exim_dlfunc_t *func; uschar *result; int status, argc; uschar *argv[EXPAND_DLFUNC_MAX_ARGS + 3]; if ((expand_forbid & RDO_DLFUNC) != 0) { expand_string_message = US"dynamically-loaded functions are not permitted"; goto EXPAND_FAILED; } switch(read_subs(argv, EXPAND_DLFUNC_MAX_ARGS + 2, 2, &s, skipping, TRUE, US"dlfunc", &resetok)) { case 1: goto EXPAND_FAILED_CURLY; case 2: case 3: goto EXPAND_FAILED; } /* If skipping, we don't actually do anything */ if (skipping) continue; /* Look up the dynamically loaded object handle in the tree. If it isn't found, dlopen() the file and put the handle in the tree for next time. */ t = tree_search(dlobj_anchor, argv[0]); if (t == NULL) { void *handle = dlopen(CS argv[0], RTLD_LAZY); if (handle == NULL) { expand_string_message = string_sprintf("dlopen \"%s\" failed: %s", argv[0], dlerror()); log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message); goto EXPAND_FAILED; } t = store_get_perm(sizeof(tree_node) + Ustrlen(argv[0])); Ustrcpy(t->name, argv[0]); t->data.ptr = handle; (void)tree_insertnode(&dlobj_anchor, t); } /* Having obtained the dynamically loaded object handle, look up the function pointer. */ func = (exim_dlfunc_t *)dlsym(t->data.ptr, CS argv[1]); if (func == NULL) { expand_string_message = string_sprintf("dlsym \"%s\" in \"%s\" failed: " "%s", argv[1], argv[0], dlerror()); log_write(0, LOG_MAIN|LOG_PANIC, "%s", expand_string_message); goto EXPAND_FAILED; } /* Call the function and work out what to do with the result. If it returns OK, we have a replacement string; if it returns DEFER then expansion has failed in a non-forced manner; if it returns FAIL then failure was forced; if it returns ERROR or any other value there's a problem, so panic slightly. In any case, assume that the function has side-effects on the store that must be preserved. */ resetok = FALSE; result = NULL; for (argc = 0; argv[argc] != NULL; argc++); status = func(&result, argc - 2, &argv[2]); if(status == OK) { if (result == NULL) result = US""; yield = string_cat(yield, &size, &ptr, result, Ustrlen(result)); continue; } else { expand_string_message = result == NULL ? US"(no message)" : result; if(status == FAIL_FORCED) expand_string_forcedfail = TRUE; else if(status != FAIL) log_write(0, LOG_MAIN|LOG_PANIC, "dlfunc{%s}{%s} failed (%d): %s", argv[0], argv[1], status, expand_string_message); goto EXPAND_FAILED; } } #endif /* EXPAND_DLFUNC */ } /* EITEM_* switch */ /* Control reaches here if the name is not recognized as one of the more complicated expansion items. Check for the "operator" syntax (name terminated by a colon). Some of the operators have arguments, separated by _ from the name. */ if (*s == ':') { int c; uschar *arg = NULL; uschar *sub; var_entry *vp = NULL; /* Owing to an historical mis-design, an underscore may be part of the operator name, or it may introduce arguments. We therefore first scan the table of names that contain underscores. If there is no match, we cut off the arguments and then scan the main table. */ if ((c = chop_match(name, op_table_underscore, sizeof(op_table_underscore)/sizeof(uschar *))) < 0) { arg = Ustrchr(name, '_'); if (arg != NULL) *arg = 0; c = chop_match(name, op_table_main, sizeof(op_table_main)/sizeof(uschar *)); if (c >= 0) c += sizeof(op_table_underscore)/sizeof(uschar *); if (arg != NULL) *arg++ = '_'; /* Put back for error messages */ } /* Deal specially with operators that might take a certificate variable as we do not want to do the usual expansion. For most, expand the string.*/ switch(c) { #ifdef SUPPORT_TLS case EOP_MD5: case EOP_SHA1: case EOP_SHA256: if (s[1] == '$') { uschar * s1 = s; sub = expand_string_internal(s+2, TRUE, &s1, skipping, FALSE, &resetok); if (!sub) goto EXPAND_FAILED; /*{*/ if (*s1 != '}') goto EXPAND_FAILED_CURLY; if ((vp = find_var_ent(sub)) && vp->type == vtype_cert) { s = s1+1; break; } vp = NULL; } /*FALLTHROUGH*/ #endif default: sub = expand_string_internal(s+1, TRUE, &s, skipping, TRUE, &resetok); if (!sub) goto EXPAND_FAILED; s++; break; } /* If we are skipping, we don't need to perform the operation at all. This matters for operations like "mask", because the data may not be in the correct format when skipping. For example, the expression may test for the existence of $sender_host_address before trying to mask it. For other operations, doing them may not fail, but it is a waste of time. */ if (skipping && c >= 0) continue; /* Otherwise, switch on the operator type */ switch(c) { case EOP_BASE62: { uschar *t; unsigned long int n = Ustrtoul(sub, &t, 10); if (*t != 0) { expand_string_message = string_sprintf("argument for base62 " "operator is \"%s\", which is not a decimal number", sub); goto EXPAND_FAILED; } t = string_base62(n); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Note that for Darwin and Cygwin, BASE_62 actually has the value 36 */ case EOP_BASE62D: { uschar buf[16]; uschar *tt = sub; unsigned long int n = 0; while (*tt != 0) { uschar *t = Ustrchr(base62_chars, *tt++); if (t == NULL) { expand_string_message = string_sprintf("argument for base62d " "operator is \"%s\", which is not a base %d number", sub, BASE_62); goto EXPAND_FAILED; } n = n * BASE_62 + (t - base62_chars); } (void)sprintf(CS buf, "%ld", n); yield = string_cat(yield, &size, &ptr, buf, Ustrlen(buf)); continue; } case EOP_EXPAND: { uschar *expanded = expand_string_internal(sub, FALSE, NULL, skipping, TRUE, &resetok); if (expanded == NULL) { expand_string_message = string_sprintf("internal expansion of \"%s\" failed: %s", sub, expand_string_message); goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, expanded, Ustrlen(expanded)); continue; } case EOP_LC: { int count = 0; uschar *t = sub - 1; while (*(++t) != 0) { *t = tolower(*t); count++; } yield = string_cat(yield, &size, &ptr, sub, count); continue; } case EOP_UC: { int count = 0; uschar *t = sub - 1; while (*(++t) != 0) { *t = toupper(*t); count++; } yield = string_cat(yield, &size, &ptr, sub, count); continue; } case EOP_MD5: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_md5(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); } else #endif { md5 base; uschar digest[16]; int j; char st[33]; md5_start(&base); md5_end(&base, sub, Ustrlen(sub), digest); for(j = 0; j < 16; j++) sprintf(st+2*j, "%02x", digest[j]); yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st)); } continue; case EOP_SHA1: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_sha1(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); } else #endif { sha1 base; uschar digest[20]; int j; char st[41]; sha1_start(&base); sha1_end(&base, sub, Ustrlen(sub), digest); for(j = 0; j < 20; j++) sprintf(st+2*j, "%02X", digest[j]); yield = string_cat(yield, &size, &ptr, US st, (int)strlen(st)); } continue; case EOP_SHA256: #ifdef SUPPORT_TLS if (vp && *(void **)vp->value) { uschar * cp = tls_cert_fprt_sha256(*(void **)vp->value); yield = string_cat(yield, &size, &ptr, cp, (int)Ustrlen(cp)); } else #endif expand_string_message = US"sha256 only supported for certificates"; continue; /* Convert hex encoding to base64 encoding */ case EOP_HEX2B64: { int c = 0; int b = -1; uschar *in = sub; uschar *out = sub; uschar *enc; for (enc = sub; *enc != 0; enc++) { if (!isxdigit(*enc)) { expand_string_message = string_sprintf("\"%s\" is not a hex " "string", sub); goto EXPAND_FAILED; } c++; } if ((c & 1) != 0) { expand_string_message = string_sprintf("\"%s\" contains an odd " "number of characters", sub); goto EXPAND_FAILED; } while ((c = *in++) != 0) { if (isdigit(c)) c -= '0'; else c = toupper(c) - 'A' + 10; if (b == -1) { b = c << 4; } else { *out++ = b | c; b = -1; } } enc = auth_b64encode(sub, out - sub); yield = string_cat(yield, &size, &ptr, enc, Ustrlen(enc)); continue; } /* Convert octets outside 0x21..0x7E to \xXX form */ case EOP_HEXQUOTE: { uschar *t = sub - 1; while (*(++t) != 0) { if (*t < 0x21 || 0x7E < *t) yield = string_cat(yield, &size, &ptr, string_sprintf("\\x%02x", *t), 4); else yield = string_cat(yield, &size, &ptr, t, 1); } continue; } /* count the number of list elements */ case EOP_LISTCOUNT: { int cnt = 0; int sep = 0; uschar * cp; uschar buffer[256]; while (string_nextinlist(&sub, &sep, buffer, sizeof(buffer)) != NULL) cnt++; cp = string_sprintf("%d", cnt); yield = string_cat(yield, &size, &ptr, cp, Ustrlen(cp)); continue; } /* expand a named list given the name */ /* handles nested named lists; requotes as colon-sep list */ case EOP_LISTNAMED: { tree_node *t = NULL; uschar * list; int sep = 0; uschar * item; uschar * suffix = US""; BOOL needsep = FALSE; uschar buffer[256]; if (*sub == '+') sub++; if (arg == NULL) /* no-argument version */ { if (!(t = tree_search(addresslist_anchor, sub)) && !(t = tree_search(domainlist_anchor, sub)) && !(t = tree_search(hostlist_anchor, sub))) t = tree_search(localpartlist_anchor, sub); } else switch(*arg) /* specific list-type version */ { case 'a': t = tree_search(addresslist_anchor, sub); suffix = US"_a"; break; case 'd': t = tree_search(domainlist_anchor, sub); suffix = US"_d"; break; case 'h': t = tree_search(hostlist_anchor, sub); suffix = US"_h"; break; case 'l': t = tree_search(localpartlist_anchor, sub); suffix = US"_l"; break; default: expand_string_message = string_sprintf("bad suffix on \"list\" operator"); goto EXPAND_FAILED; } if(!t) { expand_string_message = string_sprintf("\"%s\" is not a %snamed list", sub, !arg?"" : *arg=='a'?"address " : *arg=='d'?"domain " : *arg=='h'?"host " : *arg=='l'?"localpart " : 0); goto EXPAND_FAILED; } list = ((namedlist_block *)(t->data.ptr))->string; while ((item = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL) { uschar * buf = US" : "; if (needsep) yield = string_cat(yield, &size, &ptr, buf, 3); else needsep = TRUE; if (*item == '+') /* list item is itself a named list */ { uschar * sub = string_sprintf("${listnamed%s:%s}", suffix, item); item = expand_string_internal(sub, FALSE, NULL, FALSE, TRUE, &resetok); } else if (sep != ':') /* item from non-colon-sep list, re-quote for colon list-separator */ { char * cp; char tok[3]; tok[0] = sep; tok[1] = ':'; tok[2] = 0; while ((cp= strpbrk((const char *)item, tok))) { yield = string_cat(yield, &size, &ptr, item, cp-(char *)item); if (*cp++ == ':') /* colon in a non-colon-sep list item, needs doubling */ { yield = string_cat(yield, &size, &ptr, US"::", 2); item = (uschar *)cp; } else /* sep in item; should already be doubled; emit once */ { yield = string_cat(yield, &size, &ptr, (uschar *)tok, 1); if (*cp == sep) cp++; item = (uschar *)cp; } } } yield = string_cat(yield, &size, &ptr, item, Ustrlen(item)); } continue; } /* mask applies a mask to an IP address; for example the result of ${mask:131.111.10.206/28} is 131.111.10.192/28. */ case EOP_MASK: { int count; uschar *endptr; int binary[4]; int mask, maskoffset; int type = string_is_ip_address(sub, &maskoffset); uschar buffer[64]; if (type == 0) { expand_string_message = string_sprintf("\"%s\" is not an IP address", sub); goto EXPAND_FAILED; } if (maskoffset == 0) { expand_string_message = string_sprintf("missing mask value in \"%s\"", sub); goto EXPAND_FAILED; } mask = Ustrtol(sub + maskoffset + 1, &endptr, 10); if (*endptr != 0 || mask < 0 || mask > ((type == 4)? 32 : 128)) { expand_string_message = string_sprintf("mask value too big in \"%s\"", sub); goto EXPAND_FAILED; } /* Convert the address to binary integer(s) and apply the mask */ sub[maskoffset] = 0; count = host_aton(sub, binary); host_mask(count, binary, mask); /* Convert to masked textual format and add to output. */ yield = string_cat(yield, &size, &ptr, buffer, host_nmtoa(count, binary, mask, buffer, '.')); continue; } case EOP_ADDRESS: case EOP_LOCAL_PART: case EOP_DOMAIN: { uschar *error; int start, end, domain; uschar *t = parse_extract_address(sub, &error, &start, &end, &domain, FALSE); if (t != NULL) { if (c != EOP_DOMAIN) { if (c == EOP_LOCAL_PART && domain != 0) end = start + domain - 1; yield = string_cat(yield, &size, &ptr, sub+start, end-start); } else if (domain != 0) { domain += start; yield = string_cat(yield, &size, &ptr, sub+domain, end-domain); } } continue; } case EOP_ADDRESSES: { uschar outsep[2] = { ':', '\0' }; uschar *address, *error; int save_ptr = ptr; int start, end, domain; /* Not really used */ while (isspace(*sub)) sub++; if (*sub == '>') { *outsep = *++sub; ++sub; } parse_allow_group = TRUE; for (;;) { uschar *p = parse_find_address_end(sub, FALSE); uschar saveend = *p; *p = '\0'; address = parse_extract_address(sub, &error, &start, &end, &domain, FALSE); *p = saveend; /* Add the address to the output list that we are building. This is done in chunks by searching for the separator character. At the start, unless we are dealing with the first address of the output list, add in a space if the new address begins with the separator character, or is an empty string. */ if (address != NULL) { if (ptr != save_ptr && address[0] == *outsep) yield = string_cat(yield, &size, &ptr, US" ", 1); for (;;) { size_t seglen = Ustrcspn(address, outsep); yield = string_cat(yield, &size, &ptr, address, seglen + 1); /* If we got to the end of the string we output one character too many. */ if (address[seglen] == '\0') { ptr--; break; } yield = string_cat(yield, &size, &ptr, outsep, 1); address += seglen + 1; } /* Output a separator after the string: we will remove the redundant final one at the end. */ yield = string_cat(yield, &size, &ptr, outsep, 1); } if (saveend == '\0') break; sub = p + 1; } /* If we have generated anything, remove the redundant final separator. */ if (ptr != save_ptr) ptr--; parse_allow_group = FALSE; continue; } /* quote puts a string in quotes if it is empty or contains anything other than alphamerics, underscore, dot, or hyphen. quote_local_part puts a string in quotes if RFC 2821/2822 requires it to be quoted in order to be a valid local part. In both cases, newlines and carriage returns are converted into \n and \r respectively */ case EOP_QUOTE: case EOP_QUOTE_LOCAL_PART: if (arg == NULL) { BOOL needs_quote = (*sub == 0); /* TRUE for empty string */ uschar *t = sub - 1; if (c == EOP_QUOTE) { while (!needs_quote && *(++t) != 0) needs_quote = !isalnum(*t) && !strchr("_-.", *t); } else /* EOP_QUOTE_LOCAL_PART */ { while (!needs_quote && *(++t) != 0) needs_quote = !isalnum(*t) && strchr("!#$%&'*+-/=?^_`{|}~", *t) == NULL && (*t != '.' || t == sub || t[1] == 0); } if (needs_quote) { yield = string_cat(yield, &size, &ptr, US"\"", 1); t = sub - 1; while (*(++t) != 0) { if (*t == '\n') yield = string_cat(yield, &size, &ptr, US"\\n", 2); else if (*t == '\r') yield = string_cat(yield, &size, &ptr, US"\\r", 2); else { if (*t == '\\' || *t == '"') yield = string_cat(yield, &size, &ptr, US"\\", 1); yield = string_cat(yield, &size, &ptr, t, 1); } } yield = string_cat(yield, &size, &ptr, US"\"", 1); } else yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub)); continue; } /* quote_lookuptype does lookup-specific quoting */ else { int n; uschar *opt = Ustrchr(arg, '_'); if (opt != NULL) *opt++ = 0; n = search_findtype(arg, Ustrlen(arg)); if (n < 0) { expand_string_message = search_error_message; goto EXPAND_FAILED; } if (lookup_list[n]->quote != NULL) sub = (lookup_list[n]->quote)(sub, opt); else if (opt != NULL) sub = NULL; if (sub == NULL) { expand_string_message = string_sprintf( "\"%s\" unrecognized after \"${quote_%s\"", opt, arg); goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, sub, Ustrlen(sub)); continue; } /* rx quote sticks in \ before any non-alphameric character so that the insertion works in a regular expression. */ case EOP_RXQUOTE: { uschar *t = sub - 1; while (*(++t) != 0) { if (!isalnum(*t)) yield = string_cat(yield, &size, &ptr, US"\\", 1); yield = string_cat(yield, &size, &ptr, t, 1); } continue; } /* RFC 2047 encodes, assuming headers_charset (default ISO 8859-1) as prescribed by the RFC, if there are characters that need to be encoded */ case EOP_RFC2047: { uschar buffer[2048]; uschar *string = parse_quote_2047(sub, Ustrlen(sub), headers_charset, buffer, sizeof(buffer), FALSE); yield = string_cat(yield, &size, &ptr, string, Ustrlen(string)); continue; } /* RFC 2047 decode */ case EOP_RFC2047D: { int len; uschar *error; uschar *decoded = rfc2047_decode(sub, check_rfc2047_length, headers_charset, '?', &len, &error); if (error != NULL) { expand_string_message = error; goto EXPAND_FAILED; } yield = string_cat(yield, &size, &ptr, decoded, len); continue; } /* from_utf8 converts UTF-8 to 8859-1, turning non-existent chars into underscores */ case EOP_FROM_UTF8: { while (*sub != 0) { int c; uschar buff[4]; GETUTF8INC(c, sub); if (c > 255) c = '_'; buff[0] = c; yield = string_cat(yield, &size, &ptr, buff, 1); } continue; } /* replace illegal UTF-8 sequences by replacement character */ #define UTF8_REPLACEMENT_CHAR US"?" case EOP_UTF8CLEAN: { int seq_len, index = 0; int bytes_left = 0; uschar seq_buff[4]; /* accumulate utf-8 here */ while (*sub != 0) { int complete; long codepoint; uschar c; complete = 0; c = *sub++; if (bytes_left) { if ((c & 0xc0) != 0x80) { /* wrong continuation byte; invalidate all bytes */ complete = 1; /* error */ } else { codepoint = (codepoint << 6) | (c & 0x3f); seq_buff[index++] = c; if (--bytes_left == 0) /* codepoint complete */ { if(codepoint > 0x10FFFF) /* is it too large? */ complete = -1; /* error */ else { /* finished; output utf-8 sequence */ yield = string_cat(yield, &size, &ptr, seq_buff, seq_len); index = 0; } } } } else /* no bytes left: new sequence */ { if((c & 0x80) == 0) /* 1-byte sequence, US-ASCII, keep it */ { yield = string_cat(yield, &size, &ptr, &c, 1); continue; } if((c & 0xe0) == 0xc0) /* 2-byte sequence */ { if(c == 0xc0 || c == 0xc1) /* 0xc0 and 0xc1 are illegal */ complete = -1; else { bytes_left = 1; codepoint = c & 0x1f; } } else if((c & 0xf0) == 0xe0) /* 3-byte sequence */ { bytes_left = 2; codepoint = c & 0x0f; } else if((c & 0xf8) == 0xf0) /* 4-byte sequence */ { bytes_left = 3; codepoint = c & 0x07; } else /* invalid or too long (RFC3629 allows only 4 bytes) */ complete = -1; seq_buff[index++] = c; seq_len = bytes_left + 1; } /* if(bytes_left) */ if (complete != 0) { bytes_left = index = 0; yield = string_cat(yield, &size, &ptr, UTF8_REPLACEMENT_CHAR, 1); } if ((complete == 1) && ((c & 0x80) == 0)) { /* ASCII character follows incomplete sequence */ yield = string_cat(yield, &size, &ptr, &c, 1); } } continue; } /* escape turns all non-printing characters into escape sequences. */ case EOP_ESCAPE: { uschar *t = string_printing(sub); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Handle numeric expression evaluation */ case EOP_EVAL: case EOP_EVAL10: { uschar *save_sub = sub; uschar *error = NULL; int_eximarith_t n = eval_expr(&sub, (c == EOP_EVAL10), &error, FALSE); if (error != NULL) { expand_string_message = string_sprintf("error in expression " "evaluation: %s (after processing \"%.*s\")", error, sub-save_sub, save_sub); goto EXPAND_FAILED; } sprintf(CS var_buffer, PR_EXIM_ARITH, n); yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer)); continue; } /* Handle time period formating */ case EOP_TIME_EVAL: { int n = readconf_readtime(sub, 0, FALSE); if (n < 0) { expand_string_message = string_sprintf("string \"%s\" is not an " "Exim time interval in \"%s\" operator", sub, name); goto EXPAND_FAILED; } sprintf(CS var_buffer, "%d", n); yield = string_cat(yield, &size, &ptr, var_buffer, Ustrlen(var_buffer)); continue; } case EOP_TIME_INTERVAL: { int n; uschar *t = read_number(&n, sub); if (*t != 0) /* Not A Number*/ { expand_string_message = string_sprintf("string \"%s\" is not a " "positive number in \"%s\" operator", sub, name); goto EXPAND_FAILED; } t = readconf_printtime(n); yield = string_cat(yield, &size, &ptr, t, Ustrlen(t)); continue; } /* Convert string to base64 encoding */ case EOP_STR2B64: { uschar *encstr = auth_b64encode(sub, Ustrlen(sub)); yield = string_cat(yield, &size, &ptr, encstr, Ustrlen(encstr)); continue; } /* strlen returns the length of the string */ case EOP_STRLEN: { uschar buff[24]; (void)sprintf(CS buff, "%d", Ustrlen(sub)); yield = string_cat(yield, &size, &ptr, buff, Ustrlen(buff)); continue; } /* length_n or l_n takes just the first n characters or the whole string, whichever is the shorter; substr_m_n, and s_m_n take n characters from offset m; negative m take from the end; l_n is synonymous with s_0_n. If n is omitted in substr it takes the rest, either to the right or to the left. hash_n or h_n makes a hash of length n from the string, yielding n characters from the set a-z; hash_n_m makes a hash of length n, but uses m characters from the set a-zA-Z0-9. nhash_n returns a single number between 0 and n-1 (in text form), while nhash_n_m returns a div/mod hash as two numbers "a/b". The first lies between 0 and n-1 and the second between 0 and m-1. */ case EOP_LENGTH: case EOP_L: case EOP_SUBSTR: case EOP_S: case EOP_HASH: case EOP_H: case EOP_NHASH: case EOP_NH: { int sign = 1; int value1 = 0; int value2 = -1; int *pn; int len; uschar *ret; if (arg == NULL) { expand_string_message = string_sprintf("missing values after %s", name); goto EXPAND_FAILED; } /* "length" has only one argument, effectively being synonymous with substr_0_n. */ if (c == EOP_LENGTH || c == EOP_L) { pn = &value2; value2 = 0; } /* The others have one or two arguments; for "substr" the first may be negative. The second being negative means "not supplied". */ else { pn = &value1; if (name[0] == 's' && *arg == '-') { sign = -1; arg++; } } /* Read up to two numbers, separated by underscores */ ret = arg; while (*arg != 0) { if (arg != ret && *arg == '_' && pn == &value1) { pn = &value2; value2 = 0; if (arg[1] != 0) arg++; } else if (!isdigit(*arg)) { expand_string_message = string_sprintf("non-digit after underscore in \"%s\"", name); goto EXPAND_FAILED; } else *pn = (*pn)*10 + *arg++ - '0'; } value1 *= sign; /* Perform the required operation */ ret = (c == EOP_HASH || c == EOP_H)? compute_hash(sub, value1, value2, &len) : (c == EOP_NHASH || c == EOP_NH)? compute_nhash(sub, value1, value2, &len) : extract_substr(sub, value1, value2, &len); if (ret == NULL) goto EXPAND_FAILED; yield = string_cat(yield, &size, &ptr, ret, len); continue; } /* Stat a path */ case EOP_STAT: { uschar *s; uschar smode[12]; uschar **modetable[3]; int i; mode_t mode; struct stat st; if ((expand_forbid & RDO_EXISTS) != 0) { expand_string_message = US"Use of the stat() expansion is not permitted"; goto EXPAND_FAILED; } if (stat(CS sub, &st) < 0) { expand_string_message = string_sprintf("stat(%s) failed: %s", sub, strerror(errno)); goto EXPAND_FAILED; } mode = st.st_mode; switch (mode & S_IFMT) { case S_IFIFO: smode[0] = 'p'; break; case S_IFCHR: smode[0] = 'c'; break; case S_IFDIR: smode[0] = 'd'; break; case S_IFBLK: smode[0] = 'b'; break; case S_IFREG: smode[0] = '-'; break; default: smode[0] = '?'; break; } modetable[0] = ((mode & 01000) == 0)? mtable_normal : mtable_sticky; modetable[1] = ((mode & 02000) == 0)? mtable_normal : mtable_setid; modetable[2] = ((mode & 04000) == 0)? mtable_normal : mtable_setid; for (i = 0; i < 3; i++) { memcpy(CS(smode + 7 - i*3), CS(modetable[i][mode & 7]), 3); mode >>= 3; } smode[10] = 0; s = string_sprintf("mode=%04lo smode=%s inode=%ld device=%ld links=%ld " "uid=%ld gid=%ld size=" OFF_T_FMT " atime=%ld mtime=%ld ctime=%ld", (long)(st.st_mode & 077777), smode, (long)st.st_ino, (long)st.st_dev, (long)st.st_nlink, (long)st.st_uid, (long)st.st_gid, st.st_size, (long)st.st_atime, (long)st.st_mtime, (long)st.st_ctime); yield = string_cat(yield, &size, &ptr, s, Ustrlen(s)); continue; } /* vaguely random number less than N */ case EOP_RANDINT: { int_eximarith_t max; uschar *s; max = expand_string_integer(sub, TRUE); if (expand_string_message != NULL) goto EXPAND_FAILED; s = string_sprintf("%d", vaguely_random_number((int)max)); yield = string_cat(yield, &size, &ptr, s, Ustrlen(s)); continue; } /* Reverse IP, including IPv6 to dotted-nibble */ case EOP_REVERSE_IP: { int family, maskptr; uschar reversed[128]; family = string_is_ip_address(sub, &maskptr); if (family == 0) { expand_string_message = string_sprintf( "reverse_ip() not given an IP address [%s]", sub); goto EXPAND_FAILED; } invert_address(reversed, sub); yield = string_cat(yield, &size, &ptr, reversed, Ustrlen(reversed)); continue; } /* Unknown operator */ default: expand_string_message = string_sprintf("unknown expansion operator \"%s\"", name); goto EXPAND_FAILED; } } /* Handle a plain name. If this is the first thing in the expansion, release the pre-allocated buffer. If the result data is known to be in a new buffer, newsize will be set to the size of that buffer, and we can just point at that store instead of copying. Many expansion strings contain just one reference, so this is a useful optimization, especially for humungous headers ($message_headers). */ /*{*/ if (*s++ == '}') { int len; int newsize = 0; if (ptr == 0) { if (resetok) store_reset(yield); yield = NULL; size = 0; } value = find_variable(name, FALSE, skipping, &newsize); if (value == NULL) { expand_string_message = string_sprintf("unknown variable in \"${%s}\"", name); check_variable_error_message(name); goto EXPAND_FAILED; } len = Ustrlen(value); if (yield == NULL && newsize != 0) { yield = value; size = newsize; ptr = len; } else yield = string_cat(yield, &size, &ptr, value, len); continue; } /* Else there's something wrong */ expand_string_message = string_sprintf("\"${%s\" is not a known operator (or a } is missing " "in a variable reference)", name); goto EXPAND_FAILED; } /* If we hit the end of the string when ket_ends is set, there is a missing terminating brace. */ if (ket_ends && *s == 0) { expand_string_message = malformed_header? US"missing } at end of string - could be header name not terminated by colon" : US"missing } at end of string"; goto EXPAND_FAILED; } /* Expansion succeeded; yield may still be NULL here if nothing was actually added to the string. If so, set up an empty string. Add a terminating zero. If left != NULL, return a pointer to the terminator. */ if (yield == NULL) yield = store_get(1); yield[ptr] = 0; if (left != NULL) *left = s; /* Any stacking store that was used above the final string is no longer needed. In many cases the final string will be the first one that was got and so there will be optimal store usage. */ if (resetok) store_reset(yield + ptr + 1); else if (resetok_p) *resetok_p = FALSE; DEBUG(D_expand) { debug_printf("expanding: %.*s\n result: %s\n", (int)(s - string), string, yield); if (skipping) debug_printf("skipping: result is not used\n"); } return yield; /* This is the failure exit: easiest to program with a goto. We still need to update the pointer to the terminator, for cases of nested calls with "fail". */ EXPAND_FAILED_CURLY: expand_string_message = malformed_header? US"missing or misplaced { or } - could be header name not terminated by colon" : US"missing or misplaced { or }"; /* At one point, Exim reset the store to yield (if yield was not NULL), but that is a bad idea, because expand_string_message is in dynamic store. */ EXPAND_FAILED: if (left != NULL) *left = s; DEBUG(D_expand) { debug_printf("failed to expand: %s\n", string); debug_printf(" error message: %s\n", expand_string_message); if (expand_string_forcedfail) debug_printf("failure was forced\n"); } if (resetok_p) *resetok_p = resetok; return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': 'Only expand integers for integer math once'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int do_remount(struct path *path, int flags, int mnt_flags, void *data) { int err; struct super_block *sb = path->mnt->mnt_sb; struct mount *mnt = real_mount(path->mnt); if (!check_mnt(mnt)) return -EINVAL; if (path->dentry != path->mnt->mnt_root) return -EINVAL; err = security_sb_remount(sb, data); if (err) return err; down_write(&sb->s_umount); if (flags & MS_BIND) err = change_mount_flags(path->mnt, flags); else if (!capable(CAP_SYS_ADMIN)) err = -EPERM; else err = do_remount_sb(sb, flags, data, 0); if (!err) { lock_mount_hash(); mnt_flags |= mnt->mnt.mnt_flags & ~MNT_USER_SETTABLE_MASK; mnt->mnt.mnt_flags = mnt_flags; touch_mnt_namespace(mnt->mnt_ns); unlock_mount_hash(); } up_write(&sb->s_umount); return err; } ; 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 qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd) { QXLDevSurfaceCreate surface; memset(&surface, 0, sizeof(surface)); dprint(1, "%s/%d: %dx%d\n", __func__, ssd->qxl.id, surface_width(ssd->ds), surface_height(ssd->ds)); surface.format = SPICE_SURFACE_FMT_32_xRGB; surface.width = surface_width(ssd->ds); surface.height = surface_height(ssd->ds); surface.stride = -surface.width * 4; surface.mouse_mode = true; surface.flags = 0; surface.type = 0; surface.mem = (uintptr_t)ssd->buf; surface.group_id = MEMSLOT_GROUP_HOST; qemu_spice_create_primary_surface(ssd, 0, &surface, QXL_SYNC); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'spice: make sure we don't overflow ssd->buf Related spice-only bug. We have a fixed 16 MB buffer here, being presented to the spice-server as qxl video memory in case spice is used with a non-qxl card. It's also used with qxl in vga mode. When using display resolutions requiring more than 16 MB of memory we are going to overflow that buffer. In theory the guest can write, indirectly via spice-server. The spice-server clears the memory after setting a new video mode though, triggering a segfault in the overflow case, so qemu crashes before the guest has a chance to do something evil. Fix that by switching to dynamic allocation for the buffer. 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: evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen) { /*XXX fails badly on sendfile case. */ struct evbuffer_chain *chain; char *data = data_out; size_t nread; ev_ssize_t result = 0; EVBUFFER_LOCK(buf); chain = buf->first; if (datlen >= buf->total_len) datlen = buf->total_len; if (datlen == 0) goto done; if (buf->freeze_start) { result = -1; goto done; } nread = datlen; while (datlen && datlen >= chain->off) { memcpy(data, chain->buffer + chain->misalign, chain->off); data += chain->off; datlen -= chain->off; chain = chain->next; EVUTIL_ASSERT(chain || datlen==0); } if (datlen) { EVUTIL_ASSERT(chain); memcpy(data, chain->buffer + chain->misalign, datlen); } result = nread; 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_add_file(struct evbuffer *outbuf, int fd, ev_off_t offset, ev_off_t length) { #if defined(USE_SENDFILE) || defined(_EVENT_HAVE_MMAP) struct evbuffer_chain *chain; struct evbuffer_chain_fd *info; #endif #if defined(USE_SENDFILE) int sendfile_okay = 1; #endif int ok = 1; #if defined(USE_SENDFILE) if (use_sendfile) { EVBUFFER_LOCK(outbuf); sendfile_okay = outbuf->flags & EVBUFFER_FLAG_DRAINS_TO_FD; EVBUFFER_UNLOCK(outbuf); } if (use_sendfile && sendfile_okay) { chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_fd)); if (chain == NULL) { event_warn("%s: out of memory", __func__); return (-1); } chain->flags |= EVBUFFER_SENDFILE | EVBUFFER_IMMUTABLE; chain->buffer = NULL; /* no reading possible */ chain->buffer_len = length + offset; chain->off = length; chain->misalign = offset; info = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_fd, chain); info->fd = fd; EVBUFFER_LOCK(outbuf); if (outbuf->freeze_end) { mm_free(chain); ok = 0; } else { outbuf->n_add_for_cb += length; evbuffer_chain_insert(outbuf, chain); } } else #endif #if defined(_EVENT_HAVE_MMAP) if (use_mmap) { void *mapped = mmap(NULL, length + offset, PROT_READ, #ifdef MAP_NOCACHE MAP_NOCACHE | #endif #ifdef MAP_FILE MAP_FILE | #endif MAP_PRIVATE, fd, 0); /* some mmap implementations require offset to be a multiple of * the page size. most users of this api, are likely to use 0 * so mapping everything is not likely to be a problem. * TODO(niels): determine page size and round offset to that * page size to avoid mapping too much memory. */ if (mapped == MAP_FAILED) { event_warn("%s: mmap(%d, %d, %zu) failed", __func__, fd, 0, (size_t)(offset + length)); return (-1); } chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_fd)); if (chain == NULL) { event_warn("%s: out of memory", __func__); munmap(mapped, length); return (-1); } chain->flags |= EVBUFFER_MMAP | EVBUFFER_IMMUTABLE; chain->buffer = mapped; chain->buffer_len = length + offset; chain->off = length + offset; info = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_fd, chain); info->fd = fd; EVBUFFER_LOCK(outbuf); if (outbuf->freeze_end) { info->fd = -1; evbuffer_chain_free(chain); ok = 0; } else { outbuf->n_add_for_cb += length; evbuffer_chain_insert(outbuf, chain); /* we need to subtract whatever we don't need */ evbuffer_drain(outbuf, offset); } } else #endif { /* the default implementation */ struct evbuffer *tmp = evbuffer_new(); ev_ssize_t read; if (tmp == NULL) return (-1); #ifdef WIN32 #define lseek _lseeki64 #endif if (lseek(fd, offset, SEEK_SET) == -1) { evbuffer_free(tmp); return (-1); } /* we add everything to a temporary buffer, so that we * can abort without side effects if the read fails. */ while (length) { read = evbuffer_readfile(tmp, fd, (ev_ssize_t)length); if (read == -1) { evbuffer_free(tmp); return (-1); } length -= read; } EVBUFFER_LOCK(outbuf); if (outbuf->freeze_end) { evbuffer_free(tmp); ok = 0; } else { evbuffer_add_buffer(outbuf, tmp); evbuffer_free(tmp); #ifdef WIN32 #define close _close #endif close(fd); } } if (ok) evbuffer_invoke_callbacks(outbuf); EVBUFFER_UNLOCK(outbuf); return ok ? 0 : -1; } ; 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_read(struct evbuffer *buf, evutil_socket_t fd, int howmuch) { struct evbuffer_chain **chainp; int n; int result; #ifdef USE_IOVEC_IMPL int nvecs, i, remaining; #else struct evbuffer_chain *chain; unsigned char *p; #endif EVBUFFER_LOCK(buf); if (buf->freeze_end) { result = -1; goto done; } n = get_n_bytes_readable_on_socket(fd); if (n <= 0 || n > EVBUFFER_MAX_READ) n = EVBUFFER_MAX_READ; if (howmuch < 0 || howmuch > n) howmuch = n; #ifdef USE_IOVEC_IMPL /* Since we can use iovecs, we're willing to use the last * NUM_READ_IOVEC chains. */ if (evbuffer_expand_fast_(buf, howmuch, NUM_READ_IOVEC) == -1) { result = -1; goto done; } else { IOV_TYPE vecs[NUM_READ_IOVEC]; #ifdef EVBUFFER_IOVEC_IS_NATIVE_ nvecs = evbuffer_read_setup_vecs_(buf, howmuch, vecs, NUM_READ_IOVEC, &chainp, 1); #else /* We aren't using the native struct iovec. Therefore, we are on win32. */ struct evbuffer_iovec ev_vecs[NUM_READ_IOVEC]; nvecs = evbuffer_read_setup_vecs_(buf, howmuch, ev_vecs, 2, &chainp, 1); for (i=0; i < nvecs; ++i) WSABUF_FROM_EVBUFFER_IOV(&vecs[i], &ev_vecs[i]); #endif #ifdef _WIN32 { DWORD bytesRead; DWORD flags=0; if (WSARecv(fd, vecs, nvecs, &bytesRead, &flags, NULL, NULL)) { /* The read failed. It might be a close, * or it might be an error. */ if (WSAGetLastError() == WSAECONNABORTED) n = 0; else n = -1; } else n = bytesRead; } #else n = readv(fd, vecs, nvecs); #endif } #else /*!USE_IOVEC_IMPL*/ /* If we don't have FIONREAD, we might waste some space here */ /* XXX we _will_ waste some space here if there is any space left * over on buf->last. */ if ((chain = evbuffer_expand_singlechain(buf, howmuch)) == NULL) { result = -1; goto done; } /* We can append new data at this point */ p = chain->buffer + chain->misalign + chain->off; #ifndef _WIN32 n = read(fd, p, howmuch); #else n = recv(fd, p, howmuch, 0); #endif #endif /* USE_IOVEC_IMPL */ if (n == -1) { result = -1; goto done; } if (n == 0) { result = 0; goto done; } #ifdef USE_IOVEC_IMPL remaining = n; for (i=0; i < nvecs; ++i) { ev_ssize_t space = (ev_ssize_t) CHAIN_SPACE_LEN(*chainp); if (space < remaining) { (*chainp)->off += space; remaining -= (int)space; } else { (*chainp)->off += remaining; buf->last_with_datap = chainp; break; } chainp = &(*chainp)->next; } #else chain->off += n; advance_last_with_data(buf); #endif buf->total_len += n; buf->n_add_for_cb += n; /* Tell someone about changes in this buffer */ evbuffer_invoke_callbacks_(buf); result = n; 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.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: kadm5_randkey_principal_3(void *server_handle, krb5_principal principal, krb5_boolean keepold, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, krb5_keyblock **keyblocks, int *n_keys) { krb5_db_entry *kdb; osa_princ_ent_rec adb; krb5_int32 now; kadm5_policy_ent_rec pol; int ret, last_pwd; krb5_boolean have_pol = FALSE; kadm5_server_handle_t handle = server_handle; krb5_keyblock *act_mkey; krb5_kvno act_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; if (keyblocks) *keyblocks = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); if (principal == NULL) return EINVAL; if ((ret = kdb_get_entry(handle, principal, &kdb, &adb))) return(ret); ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto done; if (krb5_principal_compare(handle->context, principal, hist_princ)) { /* If changing the history entry, the new entry must have exactly one * key. */ if (keepold) return KADM5_PROTECT_PRINCIPAL; new_n_ks_tuple = 1; } ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto done; ret = krb5_dbe_crk(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, keepold, kdb); if (ret) goto done; ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto done; kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE; ret = krb5_timeofday(handle->context, &now); if (ret) goto done; if ((adb.aux_attributes & KADM5_POLICY)) { ret = get_policy(handle, adb.policy, &pol, &have_pol); if (ret) goto done; } if (have_pol) { ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd); if (ret) goto done; #if 0 /* * The spec says this check is overridden if the caller has * modify privilege. The admin server therefore makes this * check itself (in chpass_principal_wrapper, misc.c). A * local caller implicitly has all authorization bits. */ if((now - last_pwd) < pol.pw_min_life && !(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) { ret = KADM5_PASS_TOOSOON; goto done; } #endif if (pol.pw_max_life) kdb->pw_expiration = now + pol.pw_max_life; else kdb->pw_expiration = 0; } else { kdb->pw_expiration = 0; } ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now); if (ret) goto done; /* unlock principal on this KDC */ kdb->fail_auth_count = 0; if (keyblocks) { ret = decrypt_key_data(handle->context, kdb->n_key_data, kdb->key_data, keyblocks, n_keys); if (ret) goto done; } /* key data changed, let the database provider know */ kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT; /* | KADM5_RANDKEY_USED */; ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold, new_n_ks_tuple, new_ks_tuple, NULL); if (ret) goto done; if ((ret = kdb_put_entry(handle, kdb, &adb))) goto done; (void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, principal, keepold, new_n_ks_tuple, new_ks_tuple, NULL); ret = KADM5_OK; done: free(new_ks_tuple); kdb_free_entry(handle, kdb, &adb); if (have_pol) kadm5_free_policy_ent(handle->lhandle, &pol); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-522', 'CWE-255'], 'message': 'Return only new keys in randkey [CVE-2014-5351] In kadmind's randkey operation, if a client specifies the keepold flag, do not include the preserved old keys in the response. CVE-2014-5351: An authenticated remote attacker can retrieve the current keys for a service principal when generating a new set of keys for that principal. The attacker needs to be authenticated as a user who has the elevated privilege for randomizing the keys of other principals. Normally, when a Kerberos administrator randomizes the keys of a service principal, kadmind returns only the new keys. This prevents an administrator who lacks legitimate privileged access to a service from forging tickets to authenticate to that service. If the "keepold" flag to the kadmin randkey RPC operation is true, kadmind retains the old keys in the KDC database as intended, but also unexpectedly returns the old keys to the client, which exposes the service to ticket forgery attacks from the administrator. A mitigating factor is that legitimate clients of the affected service will start failing to authenticate to the service once they begin to receive service tickets encrypted in the new keys. The affected service will be unable to decrypt the newly issued tickets, possibly alerting the legitimate administrator of the affected service. CVSSv2: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C [tlyu@mit.edu: CVE description and CVSS score] ticket: 8018 (new) target_version: 1.13 tags: pullup'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void __net_random_once_deferred(struct work_struct *w) { struct __net_random_once_work *work = container_of(w, struct __net_random_once_work, work); if (!static_key_enabled(work->key)) static_key_slow_inc(work->key); kfree(work); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'net: avoid dependency of net_get_random_once on nop patching net_get_random_once depends on the static keys infrastructure to patch up the branch to the slow path during boot. This was realized by abusing the static keys api and defining a new initializer to not enable the call site while still indicating that the branch point should get patched up. This was needed to have the fast path considered likely by gcc. The static key initialization during boot up normally walks through all the registered keys and either patches in ideal nops or enables the jump site but omitted that step on x86 if ideal nops where already placed at static_key branch points. Thus net_get_random_once branches not always became active. This patch switches net_get_random_once to the ordinary static_key api and thus places the kernel fast path in the - by gcc considered - unlikely path. Microbenchmarks on Intel and AMD x86-64 showed that the unlikely path actually beats the likely path in terms of cycle cost and that different nop patterns did not make much difference, thus this switch should not be noticeable. Fixes: a48e42920ff38b ("net: introduce new macro net_get_random_once") Reported-by: Tuomas Räsänen <tuomasjjrasanen@tjjr.fi> Cc: Linus Torvalds <torvalds@linux-foundation.org> 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: _gnutls_server_select_suite(gnutls_session_t session, uint8_t * data, unsigned int datalen) { int ret; unsigned int i, j, cipher_suites_size; size_t pk_algos_size; uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE]; int retval; gnutls_pk_algorithm_t pk_algos[MAX_ALGOS]; /* will hold the pk algorithms * supported by the peer. */ for (i = 0; i < datalen; i += 2) { /* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */ if (session->internals.priorities.sr != SR_DISABLED && data[i] == GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR && data[i + 1] == GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR) { _gnutls_handshake_log ("HSK[%p]: Received safe renegotiation CS\n", session); retval = _gnutls_ext_sr_recv_cs(session); if (retval < 0) { gnutls_assert(); return retval; } } /* TLS_FALLBACK_SCSV */ if (data[i] == GNUTLS_FALLBACK_SCSV_MAJOR && data[i + 1] == GNUTLS_FALLBACK_SCSV_MINOR) { _gnutls_handshake_log ("HSK[%p]: Received fallback CS\n", session); if (gnutls_protocol_get_version(session) != GNUTLS_TLS_VERSION_MAX) return GNUTLS_E_INAPPROPRIATE_FALLBACK; } } pk_algos_size = MAX_ALGOS; ret = server_find_pk_algos_in_ciphersuites(data, datalen, pk_algos, &pk_algos_size); if (ret < 0) return gnutls_assert_val(ret); ret = _gnutls_supported_ciphersuites(session, cipher_suites, sizeof(cipher_suites)); if (ret < 0) return gnutls_assert_val(ret); cipher_suites_size = ret; /* Here we remove any ciphersuite that does not conform * the certificate requested, or to the * authentication requested (e.g. SRP). */ ret = _gnutls_remove_unwanted_ciphersuites(session, cipher_suites, cipher_suites_size, pk_algos, pk_algos_size); if (ret <= 0) { gnutls_assert(); if (ret < 0) return ret; else return GNUTLS_E_UNKNOWN_CIPHER_SUITE; } cipher_suites_size = ret; /* Data length should be zero mod 2 since * every ciphersuite is 2 bytes. (this check is needed * see below). */ if (datalen % 2 != 0) { gnutls_assert(); return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; } memset(session->security_parameters.cipher_suite, 0, 2); retval = GNUTLS_E_UNKNOWN_CIPHER_SUITE; _gnutls_handshake_log ("HSK[%p]: Requested cipher suites[size: %d]: \n", session, (int) datalen); if (session->internals.priorities.server_precedence == 0) { for (j = 0; j < datalen; j += 2) { _gnutls_handshake_log("\t0x%.2x, 0x%.2x %s\n", data[j], data[j + 1], _gnutls_cipher_suite_get_name (&data[j])); for (i = 0; i < cipher_suites_size; i += 2) { if (memcmp(&cipher_suites[i], &data[j], 2) == 0) { _gnutls_handshake_log ("HSK[%p]: Selected cipher suite: %s\n", session, _gnutls_cipher_suite_get_name (&data[j])); memcpy(session-> security_parameters. cipher_suite, &cipher_suites[i], 2); _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT, session->security_parameters. cipher_suite); retval = 0; goto finish; } } } } else { /* server selects */ for (i = 0; i < cipher_suites_size; i += 2) { for (j = 0; j < datalen; j += 2) { if (memcmp(&cipher_suites[i], &data[j], 2) == 0) { _gnutls_handshake_log ("HSK[%p]: Selected cipher suite: %s\n", session, _gnutls_cipher_suite_get_name (&data[j])); memcpy(session-> security_parameters. cipher_suite, &cipher_suites[i], 2); _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT, session->security_parameters. cipher_suite); retval = 0; goto finish; } } } } finish: if (retval != 0) { gnutls_assert(); return retval; } /* check if the credentials (username, public key etc.) are ok */ if (_gnutls_get_kx_cred (session, _gnutls_cipher_suite_get_kx_algo(session->security_parameters. cipher_suite)) == NULL) { gnutls_assert(); return GNUTLS_E_INSUFFICIENT_CREDENTIALS; } /* set the mod_auth_st to the appropriate struct * according to the KX algorithm. This is needed since all the * handshake functions are read from there; */ session->internals.auth_struct = _gnutls_kx_auth_struct(_gnutls_cipher_suite_get_kx_algo (session->security_parameters. cipher_suite)); if (session->internals.auth_struct == NULL) { _gnutls_handshake_log ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n", session); gnutls_assert(); return GNUTLS_E_INTERNAL_ERROR; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'handshake: check inappropriate fallback against the configured max version That allows to operate on a server which is explicitly configured to utilize earlier than TLS 1.2 versions.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, int clazz, int swap, size_t align, int *flags) { Elf32_Nhdr nh32; Elf64_Nhdr nh64; size_t noff, doff; #ifdef ELFCORE int os_style = -1; #endif uint32_t namesz, descsz; unsigned char *nbuf = CAST(unsigned char *, vbuf); (void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof); offset += xnh_sizeof; namesz = xnh_namesz; descsz = xnh_descsz; if ((namesz == 0) && (descsz == 0)) { /* * We're out of note headers. */ return (offset >= size) ? offset : size; } if (namesz & 0x80000000) { (void)file_printf(ms, ", bad note name size 0x%lx", (unsigned long)namesz); return offset; } if (descsz & 0x80000000) { (void)file_printf(ms, ", bad note description size 0x%lx", (unsigned long)descsz); return offset; } noff = offset; doff = ELF_ALIGN(offset + namesz); if (offset + namesz > size) { /* * We're past the end of the buffer. */ return doff; } offset = ELF_ALIGN(doff + descsz); if (doff + descsz > size) { /* * We're past the end of the buffer. */ return (offset >= size) ? offset : size; } if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) == (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) goto core; if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 && xnh_type == NT_GNU_VERSION && descsz == 2) { file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]); } if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && xnh_type == NT_GNU_VERSION && descsz == 16) { uint32_t desc[4]; (void)memcpy(desc, &nbuf[doff], sizeof(desc)); if (file_printf(ms, ", for GNU/") == -1) return size; switch (elf_getu32(swap, desc[0])) { case GNU_OS_LINUX: if (file_printf(ms, "Linux") == -1) return size; break; case GNU_OS_HURD: if (file_printf(ms, "Hurd") == -1) return size; break; case GNU_OS_SOLARIS: if (file_printf(ms, "Solaris") == -1) return size; break; case GNU_OS_KFREEBSD: if (file_printf(ms, "kFreeBSD") == -1) return size; break; case GNU_OS_KNETBSD: if (file_printf(ms, "kNetBSD") == -1) return size; break; default: if (file_printf(ms, "<unknown>") == -1) return size; } if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]), elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1) return size; *flags |= FLAGS_DID_NOTE; return size; } if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) { uint8_t desc[20]; uint32_t i; if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" : "sha1") == -1) return size; (void)memcpy(desc, &nbuf[doff], descsz); for (i = 0; i < descsz; i++) if (file_printf(ms, "%02x", desc[i]) == -1) return size; *flags |= FLAGS_DID_BUILD_ID; } if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 && xnh_type == NT_NETBSD_PAX && descsz == 4) { static const char *pax[] = { "+mprotect", "-mprotect", "+segvguard", "-segvguard", "+ASLR", "-ASLR", }; uint32_t desc; size_t i; int did = 0; (void)memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (desc && file_printf(ms, ", PaX: ") == -1) return size; for (i = 0; i < __arraycount(pax); i++) { if (((1 << i) & desc) == 0) continue; if (file_printf(ms, "%s%s", did++ ? "," : "", pax[i]) == -1) return size; } } if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) { switch (xnh_type) { case NT_NETBSD_VERSION: if (descsz == 4) { do_note_netbsd_version(ms, swap, &nbuf[doff]); *flags |= FLAGS_DID_NOTE; return size; } break; case NT_NETBSD_MARCH: if (file_printf(ms, ", compiled for: %.*s", (int)descsz, (const char *)&nbuf[doff]) == -1) return size; break; case NT_NETBSD_CMODEL: if (file_printf(ms, ", compiler model: %.*s", (int)descsz, (const char *)&nbuf[doff]) == -1) return size; break; default: if (file_printf(ms, ", note=%u", xnh_type) == -1) return size; break; } return size; } if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) { if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) { do_note_freebsd_version(ms, swap, &nbuf[doff]); *flags |= FLAGS_DID_NOTE; return size; } } if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 && xnh_type == NT_OPENBSD_VERSION && descsz == 4) { if (file_printf(ms, ", for OpenBSD") == -1) return size; /* Content of note is always 0 */ *flags |= FLAGS_DID_NOTE; return size; } if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 && xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) { uint32_t desc; if (file_printf(ms, ", for DragonFly") == -1) return size; (void)memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, " %d.%d.%d", desc / 100000, desc / 10000 % 10, desc % 10000) == -1) return size; *flags |= FLAGS_DID_NOTE; return size; } core: /* * Sigh. The 2.0.36 kernel in Debian 2.1, at * least, doesn't correctly implement name * sections, in core dumps, as specified by * the "Program Linking" section of "UNIX(R) System * V Release 4 Programmer's Guide: ANSI C and * Programming Support Tools", because my copy * clearly says "The first 'namesz' bytes in 'name' * contain a *null-terminated* [emphasis mine] * character representation of the entry's owner * or originator", but the 2.0.36 kernel code * doesn't include the terminating null in the * name.... */ if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) || (namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) { os_style = OS_STYLE_SVR4; } if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) { os_style = OS_STYLE_FREEBSD; } if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11) == 0)) { os_style = OS_STYLE_NETBSD; } #ifdef ELFCORE if ((*flags & FLAGS_DID_CORE) != 0) return size; if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { if (file_printf(ms, ", %s-style", os_style_names[os_style]) == -1) return size; *flags |= FLAGS_DID_CORE_STYLE; } switch (os_style) { case OS_STYLE_NETBSD: if (xnh_type == NT_NETBSD_CORE_PROCINFO) { uint32_t signo; /* * Extract the program name. It is at * offset 0x7c, and is up to 32-bytes, * including the terminating NUL. */ if (file_printf(ms, ", from '%.31s'", &nbuf[doff + 0x7c]) == -1) return size; /* * Extract the signal number. It is at * offset 0x08. */ (void)memcpy(&signo, &nbuf[doff + 0x08], sizeof(signo)); if (file_printf(ms, " (signal %u)", elf_getu32(swap, signo)) == -1) return size; *flags |= FLAGS_DID_CORE; return size; } break; default: if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t i, j; unsigned char c; /* * Extract the program name. We assume * it to be 16 characters (that's what it * is in SunOS 5.x and Linux). * * Unfortunately, it's at a different offset * in various OSes, so try multiple offsets. * If the characters aren't all printable, * reject it. */ for (i = 0; i < NOFFSETS; i++) { unsigned char *cname, *cp; size_t reloffset = prpsoffsets(i); size_t noffset = doff + reloffset; size_t k; for (j = 0; j < 16; j++, noffset++, reloffset++) { /* * Make sure we're not past * the end of the buffer; if * we are, just give up. */ if (noffset >= size) goto tryanother; /* * Make sure we're not past * the end of the contents; * if we are, this obviously * isn't the right offset. */ if (reloffset >= descsz) goto tryanother; c = nbuf[noffset]; if (c == '\0') { /* * A '\0' at the * beginning is * obviously wrong. * Any other '\0' * means we're done. */ if (j == 0) goto tryanother; else break; } else { /* * A nonprintable * character is also * wrong. */ if (!isprint(c) || isquote(c)) goto tryanother; } } /* * Well, that worked. */ /* * Try next offsets, in case this match is * in the middle of a string. */ for (k = i + 1 ; k < NOFFSETS ; k++) { size_t no; int adjust = 1; if (prpsoffsets(k) >= prpsoffsets(i)) continue; for (no = doff + prpsoffsets(k); no < doff + prpsoffsets(i); no++) adjust = adjust && isprint(nbuf[no]); if (adjust) i = k; } cname = (unsigned char *) &nbuf[doff + prpsoffsets(i)]; for (cp = cname; *cp && isprint(*cp); cp++) continue; /* * Linux apparently appends a space at the end * of the command line: remove it. */ while (cp > cname && isspace(cp[-1])) cp--; if (file_printf(ms, ", from '%.*s'", (int)(cp - cname), cname) == -1) return size; *flags |= FLAGS_DID_CORE; return size; tryanother: ; } } break; } #endif return offset; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix note bounds reading, Francisco Alonso / Red Hat'</s>
<s>[INST] Given the following code containing errors, provide 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 kvm_iommu_map_pages(struct kvm *kvm, struct kvm_memory_slot *slot) { gfn_t gfn, end_gfn; pfn_t pfn; int r = 0; struct iommu_domain *domain = kvm->arch.iommu_domain; int flags; /* check if iommu exists and in use */ if (!domain) return 0; gfn = slot->base_gfn; end_gfn = gfn + slot->npages; flags = IOMMU_READ; if (!(slot->flags & KVM_MEM_READONLY)) flags |= IOMMU_WRITE; if (!kvm->arch.iommu_noncoherent) flags |= IOMMU_CACHE; while (gfn < end_gfn) { unsigned long page_size; /* Check if already mapped */ if (iommu_iova_to_phys(domain, gfn_to_gpa(gfn))) { gfn += 1; continue; } /* Get the page size we could use to map */ page_size = kvm_host_page_size(kvm, gfn); /* Make sure the page_size does not exceed the memslot */ while ((gfn + (page_size >> PAGE_SHIFT)) > end_gfn) page_size >>= 1; /* Make sure gfn is aligned to the page size we want to map */ while ((gfn << PAGE_SHIFT) & (page_size - 1)) page_size >>= 1; /* Make sure hva is aligned to the page size we want to map */ while (__gfn_to_hva_memslot(slot, gfn) & (page_size - 1)) page_size >>= 1; /* * Pin all pages we are about to map in memory. This is * important because we unmap and unpin in 4kb steps later. */ pfn = kvm_pin_pages(slot, gfn, page_size); if (is_error_noslot_pfn(pfn)) { gfn += 1; continue; } /* Map into IO address space */ r = iommu_map(domain, gfn_to_gpa(gfn), pfn_to_hpa(pfn), page_size, flags); if (r) { printk(KERN_ERR "kvm_iommu_map_address:" "iommu failed to map pfn=%llx\n", pfn); kvm_unpin_pages(kvm, pfn, page_size); goto unmap_pages; } gfn += page_size >> PAGE_SHIFT; } return 0; unmap_pages: kvm_iommu_put_pages(kvm, slot->base_gfn, gfn - slot->base_gfn); return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'kvm: fix excessive pages un-pinning in kvm_iommu_map error path. The third parameter of kvm_unpin_pages() when called from kvm_iommu_map_pages() is wrong, it should be the number of pages to un-pin and not the page size. This error was facilitated with an inconsistent API: kvm_pin_pages() takes a size, but kvn_unpin_pages() takes a number of pages, so fix the problem by matching the two. This was introduced by commit 350b8bd ("kvm: iommu: fix the third parameter of kvm_iommu_put_pages (CVE-2014-3601)"), which fixes the lack of un-pinning for pages intended to be un-pinned (i.e. memory leak) but unfortunately potentially aggravated the number of pages we un-pin that should have stayed pinned. As far as I understand though, the same practical mitigations apply. This issue was found during review of Red Hat 6.6 patches to prepare Ksplice rebootless updates. Thanks to Vegard for his time on a late Friday evening to help me in understanding this code. Fixes: 350b8bd ("kvm: iommu: fix the third parameter of... (CVE-2014-3601)") Cc: stable@vger.kernel.org Signed-off-by: Quentin Casasnovas <quentin.casasnovas@oracle.com> Signed-off-by: Vegard Nossum <vegard.nossum@oracle.com> Signed-off-by: Jamie Iles <jamie.iles@oracle.com> Reviewed-by: Sasha Levin <sasha.levin@oracle.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int x509_get_name( unsigned char **p, const unsigned char *end, x509_name *cur ) { int ret; size_t len; const unsigned char *end2; x509_name *use; if( ( ret = asn1_get_tag( p, end, &len, ASN1_CONSTRUCTED | ASN1_SET ) ) != 0 ) return( POLARSSL_ERR_X509_INVALID_NAME + ret ); end2 = end; end = *p + len; use = cur; do { if( ( ret = x509_get_attr_type_value( p, end, use ) ) != 0 ) return( ret ); if( *p != end ) { use->next = (x509_name *) polarssl_malloc( sizeof( x509_name ) ); if( use->next == NULL ) return( POLARSSL_ERR_X509_MALLOC_FAILED ); memset( use->next, 0, sizeof( x509_name ) ); use = use->next; } } while( *p != end ); /* * recurse until end of SEQUENCE is reached */ if( *p == end2 ) return( 0 ); cur->next = (x509_name *) polarssl_malloc( sizeof( x509_name ) ); if( cur->next == NULL ) return( POLARSSL_ERR_X509_MALLOC_FAILED ); memset( cur->next, 0, sizeof( x509_name ) ); return( x509_get_name( p, end2, cur->next ) ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix memory leak while parsing some X.509 certs'</s>
<s>[INST] Given the following code containing errors, provide 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_file_splice_write( struct pipe_inode_info *pipe, struct file *outfilp, loff_t *ppos, size_t count, unsigned int flags) { struct inode *inode = outfilp->f_mapping->host; struct xfs_inode *ip = XFS_I(inode); int ioflags = 0; ssize_t ret; XFS_STATS_INC(xs_write_calls); if (outfilp->f_mode & FMODE_NOCMTIME) ioflags |= IO_INVIS; if (XFS_FORCED_SHUTDOWN(ip->i_mount)) return -EIO; xfs_ilock(ip, XFS_IOLOCK_EXCL); trace_xfs_file_splice_write(ip, count, *ppos, ioflags); ret = generic_file_splice_write(pipe, outfilp, ppos, count, flags); if (ret > 0) XFS_STATS_ADD(xs_write_bytes, ret); xfs_iunlock(ip, XFS_IOLOCK_EXCL); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': '->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] 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: dotraplinkage void do_stack_segment(struct pt_regs *regs, long error_code) { enum ctx_state prev_state; prev_state = exception_enter(); if (notify_die(DIE_TRAP, "stack segment", regs, error_code, X86_TRAP_SS, SIGBUS) != NOTIFY_STOP) { preempt_conditional_sti(regs); do_trap(X86_TRAP_SS, SIGBUS, "stack segment", regs, error_code, NULL); preempt_conditional_cli(regs); } exception_exit(prev_state); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'x86_64, traps: Stop using IST for #SS On a 32-bit kernel, this has no effect, since there are no IST stacks. On a 64-bit kernel, #SS can only happen in user code, on a failed iret to user space, a canonical violation on access via RSP or RBP, or a genuine stack segment violation in 32-bit kernel code. The first two cases don't need IST, and the latter two cases are unlikely fatal bugs, and promoting them to double faults would be fine. This fixes a bug in which the espfix64 code mishandles a stack segment violation. This saves 4k of memory per CPU and a tiny bit of code. Signed-off-by: Andy Lutomirski <luto@amacapital.net> Reviewed-by: Thomas Gleixner <tglx@linutronix.de> 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: main(int argc, char *argv[]) { int c; size_t i; int action = 0, didsomefiles = 0, errflg = 0; int flags = 0, e = 0; struct magic_set *magic = NULL; int longindex; const char *magicfile = NULL; /* where the magic is */ /* makes islower etc work for other langs */ #ifdef HAVE_SETLOCALE (void)setlocale(LC_CTYPE, ""); #endif #ifdef __EMX__ /* sh-like wildcard expansion! Shouldn't hurt at least ... */ _wildcard(&argc, &argv); #endif if ((progname = strrchr(argv[0], '/')) != NULL) progname++; else progname = argv[0]; #ifdef S_IFLNK flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0; #endif while ((c = getopt_long(argc, argv, OPTSTRING, long_options, &longindex)) != -1) switch (c) { case 0 : switch (longindex) { case 0: help(); break; case 10: flags |= MAGIC_APPLE; break; case 11: flags |= MAGIC_MIME_TYPE; break; case 12: flags |= MAGIC_MIME_ENCODING; break; } break; case '0': nulsep = 1; break; case 'b': bflag++; break; case 'c': action = FILE_CHECK; break; case 'C': action = FILE_COMPILE; break; case 'd': flags |= MAGIC_DEBUG|MAGIC_CHECK; break; case 'E': flags |= MAGIC_ERROR; break; case 'e': for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++) if (strcmp(nv[i].name, optarg) == 0) break; if (i == sizeof(nv) / sizeof(nv[0])) errflg++; else flags |= nv[i].value; break; case 'f': if(action) usage(); if (magic == NULL) if ((magic = load(magicfile, flags)) == NULL) return 1; e |= unwrap(magic, optarg); ++didsomefiles; break; case 'F': separator = optarg; break; case 'i': flags |= MAGIC_MIME; break; case 'k': flags |= MAGIC_CONTINUE; break; case 'l': action = FILE_LIST; break; case 'm': magicfile = optarg; break; case 'n': ++nobuffer; break; case 'N': ++nopad; break; #if defined(HAVE_UTIME) || defined(HAVE_UTIMES) case 'p': flags |= MAGIC_PRESERVE_ATIME; break; #endif case 'r': flags |= MAGIC_RAW; break; case 's': flags |= MAGIC_DEVICES; break; case 'v': if (magicfile == NULL) magicfile = magic_getpath(magicfile, action); (void)fprintf(stdout, "%s-%s\n", progname, VERSION); (void)fprintf(stdout, "magic file from %s\n", magicfile); return 0; case 'z': flags |= MAGIC_COMPRESS; break; #ifdef S_IFLNK case 'L': flags |= MAGIC_SYMLINK; break; case 'h': flags &= ~MAGIC_SYMLINK; break; #endif case '?': default: errflg++; break; } if (errflg) { usage(); } if (e) return e; if (MAGIC_VERSION != magic_version()) (void)fprintf(stderr, "%s: compiled magic version [%d] " "does not match with shared library magic version [%d]\n", progname, MAGIC_VERSION, magic_version()); switch(action) { case FILE_CHECK: case FILE_COMPILE: case FILE_LIST: /* * Don't try to check/compile ~/.magic unless we explicitly * ask for it. */ magic = magic_open(flags|MAGIC_CHECK); if (magic == NULL) { (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno)); return 1; } switch(action) { case FILE_CHECK: c = magic_check(magic, magicfile); break; case FILE_COMPILE: c = magic_compile(magic, magicfile); break; case FILE_LIST: c = magic_list(magic, magicfile); break; default: abort(); } if (c == -1) { (void)fprintf(stderr, "%s: %s\n", progname, magic_error(magic)); return 1; } return 0; default: if (magic == NULL) if ((magic = load(magicfile, flags)) == NULL) return 1; break; } if (optind == argc) { if (!didsomefiles) usage(); } else { size_t j, wid, nw; for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) { nw = file_mbswidth(argv[j]); if (nw > wid) wid = nw; } /* * If bflag is only set twice, set it depending on * number of files [this is undocumented, and subject to change] */ if (bflag == 2) { bflag = optind >= argc - 1; } for (; optind < argc; optind++) e |= process(magic, argv[optind], wid); } if (magic) magic_close(magic); return e; } ; 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: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, int clazz, int swap, size_t align, int *flags) { Elf32_Nhdr nh32; Elf64_Nhdr nh64; size_t noff, doff; #ifdef ELFCORE int os_style = -1; #endif uint32_t namesz, descsz; unsigned char *nbuf = CAST(unsigned char *, vbuf); char sbuf[512]; if (xnh_sizeof + offset > size) { /* * We're out of note headers. */ return xnh_sizeof + offset; } (void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof); offset += xnh_sizeof; namesz = xnh_namesz; descsz = xnh_descsz; if ((namesz == 0) && (descsz == 0)) { /* * We're out of note headers. */ return (offset >= size) ? offset : size; } if (namesz & 0x80000000) { (void)file_printf(ms, ", bad note name size 0x%lx", (unsigned long)namesz); return 0; } if (descsz & 0x80000000) { (void)file_printf(ms, ", bad note description size 0x%lx", (unsigned long)descsz); return 0; } noff = offset; doff = ELF_ALIGN(offset + namesz); if (offset + namesz > size) { /* * We're past the end of the buffer. */ return doff; } offset = ELF_ALIGN(doff + descsz); if (doff + descsz > size) { /* * We're past the end of the buffer. */ return (offset >= size) ? offset : size; } if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) == (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) goto core; if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 && xnh_type == NT_GNU_VERSION && descsz == 2) { file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]); } if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && xnh_type == NT_GNU_VERSION && descsz == 16) { uint32_t desc[4]; (void)memcpy(desc, &nbuf[doff], sizeof(desc)); if (file_printf(ms, ", for GNU/") == -1) return size; switch (elf_getu32(swap, desc[0])) { case GNU_OS_LINUX: if (file_printf(ms, "Linux") == -1) return size; break; case GNU_OS_HURD: if (file_printf(ms, "Hurd") == -1) return size; break; case GNU_OS_SOLARIS: if (file_printf(ms, "Solaris") == -1) return size; break; case GNU_OS_KFREEBSD: if (file_printf(ms, "kFreeBSD") == -1) return size; break; case GNU_OS_KNETBSD: if (file_printf(ms, "kNetBSD") == -1) return size; break; default: if (file_printf(ms, "<unknown>") == -1) return size; } if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]), elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1) return size; *flags |= FLAGS_DID_NOTE; return size; } if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) { uint8_t desc[20]; uint32_t i; if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" : "sha1") == -1) return size; (void)memcpy(desc, &nbuf[doff], descsz); for (i = 0; i < descsz; i++) if (file_printf(ms, "%02x", desc[i]) == -1) return size; *flags |= FLAGS_DID_BUILD_ID; } if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 && xnh_type == NT_NETBSD_PAX && descsz == 4) { static const char *pax[] = { "+mprotect", "-mprotect", "+segvguard", "-segvguard", "+ASLR", "-ASLR", }; uint32_t desc; size_t i; int did = 0; (void)memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (desc && file_printf(ms, ", PaX: ") == -1) return size; for (i = 0; i < __arraycount(pax); i++) { if (((1 << i) & desc) == 0) continue; if (file_printf(ms, "%s%s", did++ ? "," : "", pax[i]) == -1) return size; } } if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) { switch (xnh_type) { case NT_NETBSD_VERSION: if (descsz == 4) { do_note_netbsd_version(ms, swap, &nbuf[doff]); *flags |= FLAGS_DID_NOTE; return size; } break; case NT_NETBSD_MARCH: if (file_printf(ms, ", compiled for: %.*s", (int)descsz, (const char *)&nbuf[doff]) == -1) return size; break; case NT_NETBSD_CMODEL: if (file_printf(ms, ", compiler model: %.*s", (int)descsz, (const char *)&nbuf[doff]) == -1) return size; break; default: if (file_printf(ms, ", note=%u", xnh_type) == -1) return size; break; } return size; } if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) { if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) { do_note_freebsd_version(ms, swap, &nbuf[doff]); *flags |= FLAGS_DID_NOTE; return size; } } if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 && xnh_type == NT_OPENBSD_VERSION && descsz == 4) { if (file_printf(ms, ", for OpenBSD") == -1) return size; /* Content of note is always 0 */ *flags |= FLAGS_DID_NOTE; return size; } if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 && xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) { uint32_t desc; if (file_printf(ms, ", for DragonFly") == -1) return size; (void)memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (file_printf(ms, " %d.%d.%d", desc / 100000, desc / 10000 % 10, desc % 10000) == -1) return size; *flags |= FLAGS_DID_NOTE; return size; } core: /* * Sigh. The 2.0.36 kernel in Debian 2.1, at * least, doesn't correctly implement name * sections, in core dumps, as specified by * the "Program Linking" section of "UNIX(R) System * V Release 4 Programmer's Guide: ANSI C and * Programming Support Tools", because my copy * clearly says "The first 'namesz' bytes in 'name' * contain a *null-terminated* [emphasis mine] * character representation of the entry's owner * or originator", but the 2.0.36 kernel code * doesn't include the terminating null in the * name.... */ if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) || (namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) { os_style = OS_STYLE_SVR4; } if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) { os_style = OS_STYLE_FREEBSD; } if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11) == 0)) { os_style = OS_STYLE_NETBSD; } #ifdef ELFCORE if ((*flags & FLAGS_DID_CORE) != 0) return size; if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { if (file_printf(ms, ", %s-style", os_style_names[os_style]) == -1) return size; *flags |= FLAGS_DID_CORE_STYLE; } switch (os_style) { case OS_STYLE_NETBSD: if (xnh_type == NT_NETBSD_CORE_PROCINFO) { uint32_t signo; /* * Extract the program name. It is at * offset 0x7c, and is up to 32-bytes, * including the terminating NUL. */ if (file_printf(ms, ", from '%.31s'", file_printable(sbuf, sizeof(sbuf), (const char *)&nbuf[doff + 0x7c])) == -1) return size; /* * Extract the signal number. It is at * offset 0x08. */ (void)memcpy(&signo, &nbuf[doff + 0x08], sizeof(signo)); if (file_printf(ms, " (signal %u)", elf_getu32(swap, signo)) == -1) return size; *flags |= FLAGS_DID_CORE; return size; } break; default: if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t i, j; unsigned char c; /* * Extract the program name. We assume * it to be 16 characters (that's what it * is in SunOS 5.x and Linux). * * Unfortunately, it's at a different offset * in various OSes, so try multiple offsets. * If the characters aren't all printable, * reject it. */ for (i = 0; i < NOFFSETS; i++) { unsigned char *cname, *cp; size_t reloffset = prpsoffsets(i); size_t noffset = doff + reloffset; size_t k; for (j = 0; j < 16; j++, noffset++, reloffset++) { /* * Make sure we're not past * the end of the buffer; if * we are, just give up. */ if (noffset >= size) goto tryanother; /* * Make sure we're not past * the end of the contents; * if we are, this obviously * isn't the right offset. */ if (reloffset >= descsz) goto tryanother; c = nbuf[noffset]; if (c == '\0') { /* * A '\0' at the * beginning is * obviously wrong. * Any other '\0' * means we're done. */ if (j == 0) goto tryanother; else break; } else { /* * A nonprintable * character is also * wrong. */ if (!isprint(c) || isquote(c)) goto tryanother; } } /* * Well, that worked. */ /* * Try next offsets, in case this match is * in the middle of a string. */ for (k = i + 1 ; k < NOFFSETS ; k++) { size_t no; int adjust = 1; if (prpsoffsets(k) >= prpsoffsets(i)) continue; for (no = doff + prpsoffsets(k); no < doff + prpsoffsets(i); no++) adjust = adjust && isprint(nbuf[no]); if (adjust) i = k; } cname = (unsigned char *) &nbuf[doff + prpsoffsets(i)]; for (cp = cname; *cp && isprint(*cp); cp++) continue; /* * Linux apparently appends a space at the end * of the command line: remove it. */ while (cp > cname && isspace(cp[-1])) cp--; if (file_printf(ms, ", from '%.*s'", (int)(cp - cname), cname) == -1) return size; *flags |= FLAGS_DID_CORE; return size; tryanother: ; } } break; } #endif return offset; } ; 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_col(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]; #else jpc_fix_t joinbuf[bufsize]; #endif jpc_fix_t *buf = joinbuf; register jpc_fix_t *srcptr; register jpc_fix_t *dstptr; register int n; int hstartcol; #if !defined(HAVE_VLA) /* Allocate memory for the join buffer from the heap. */ if (bufsize > QMFB_JOINBUFSIZE) { if (!(buf = jas_malloc(bufsize * 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) { *dstptr = *srcptr; srcptr += stride; ++dstptr; } /* Copy the samples from the highpass channel into place. */ srcptr = &a[hstartcol * stride]; dstptr = &a[(1 - parity) * stride]; n = numrows - hstartcol; while (n-- > 0) { *dstptr = *srcptr; 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) { *dstptr = *srcptr; dstptr += 2 * stride; ++srcptr; } #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: kg_unseal(minor_status, context_handle, input_token_buffer, message_buffer, conf_state, qop_state, toktype) OM_uint32 *minor_status; gss_ctx_id_t context_handle; gss_buffer_t input_token_buffer; gss_buffer_t message_buffer; int *conf_state; gss_qop_t *qop_state; int toktype; { krb5_gss_ctx_id_rec *ctx; unsigned char *ptr; unsigned int bodysize; int err; int toktype2; int vfyflags = 0; OM_uint32 ret; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } /* parse the token, leave the data in message_buffer, setting conf_state */ /* verify the header */ ptr = (unsigned char *) input_token_buffer->value; err = g_verify_token_header(ctx->mech_used, &bodysize, &ptr, -1, input_token_buffer->length, vfyflags); if (err) { *minor_status = err; return GSS_S_DEFECTIVE_TOKEN; } if (bodysize < 2) { *minor_status = (OM_uint32)G_BAD_TOK_HEADER; return GSS_S_DEFECTIVE_TOKEN; } toktype2 = load_16_be(ptr); ptr += 2; bodysize -= 2; switch (toktype2) { case KG2_TOK_MIC_MSG: case KG2_TOK_WRAP_MSG: case KG2_TOK_DEL_CTX: ret = gss_krb5int_unseal_token_v3(&ctx->k5_context, minor_status, ctx, ptr, bodysize, message_buffer, conf_state, qop_state, toktype); break; case KG_TOK_MIC_MSG: case KG_TOK_WRAP_MSG: case KG_TOK_DEL_CTX: ret = kg_unseal_v1(ctx->k5_context, minor_status, ctx, ptr, bodysize, message_buffer, conf_state, qop_state, toktype); break; default: *minor_status = (OM_uint32)G_BAD_TOK_HEADER; ret = GSS_S_DEFECTIVE_TOKEN; break; } if (ret != 0) save_error_info (*minor_status, ctx->k5_context); return ret; } ; 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: kg_seal_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count, int toktype) { krb5_gss_ctx_id_rec *ctx; krb5_error_code code; krb5_context context; if (qop_req != 0) { *minor_status = (OM_uint32)G_UNKNOWN_QOP; return GSS_S_FAILURE; } ctx = (krb5_gss_ctx_id_rec *)context_handle; if (!ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return GSS_S_NO_CONTEXT; } if (conf_req_flag && kg_integ_only_iov(iov, iov_count)) { /* may be more sensible to return an error here */ conf_req_flag = FALSE; } context = ctx->k5_context; switch (ctx->proto) { case 0: code = make_seal_token_v1_iov(context, ctx, conf_req_flag, conf_state, iov, iov_count, toktype); break; case 1: code = gss_krb5int_make_seal_token_v3_iov(context, ctx, conf_req_flag, conf_state, iov, iov_count, toktype); break; default: code = G_UNKNOWN_QOP; break; } if (code != 0) { *minor_status = code; save_error_info(*minor_status, context); return GSS_S_FAILURE; } *minor_status = 0; return 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: _bt_check_unique(Relation rel, IndexTuple itup, Relation heapRel, Buffer buf, OffsetNumber offset, ScanKey itup_scankey, IndexUniqueCheck checkUnique, bool *is_unique) { TupleDesc itupdesc = RelationGetDescr(rel); int natts = rel->rd_rel->relnatts; SnapshotData SnapshotDirty; OffsetNumber maxoff; Page page; BTPageOpaque opaque; Buffer nbuf = InvalidBuffer; bool found = false; /* Assume unique until we find a duplicate */ *is_unique = true; InitDirtySnapshot(SnapshotDirty); page = BufferGetPage(buf); opaque = (BTPageOpaque) PageGetSpecialPointer(page); maxoff = PageGetMaxOffsetNumber(page); /* * Scan over all equal tuples, looking for live conflicts. */ for (;;) { ItemId curitemid; IndexTuple curitup; BlockNumber nblkno; /* * make sure the offset points to an actual item before trying to * examine it... */ if (offset <= maxoff) { curitemid = PageGetItemId(page, offset); /* * We can skip items that are marked killed. * * Formerly, we applied _bt_isequal() before checking the kill * flag, so as to fall out of the item loop as soon as possible. * However, in the presence of heavy update activity an index may * contain many killed items with the same key; running * _bt_isequal() on each killed item gets expensive. Furthermore * it is likely that the non-killed version of each key appears * first, so that we didn't actually get to exit any sooner * anyway. So now we just advance over killed items as quickly as * we can. We only apply _bt_isequal() when we get to a non-killed * item or the end of the page. */ if (!ItemIdIsDead(curitemid)) { ItemPointerData htid; bool all_dead; /* * _bt_compare returns 0 for (1,NULL) and (1,NULL) - this's * how we handling NULLs - and so we must not use _bt_compare * in real comparison, but only for ordering/finding items on * pages. - vadim 03/24/97 */ if (!_bt_isequal(itupdesc, page, offset, natts, itup_scankey)) break; /* we're past all the equal tuples */ /* okay, we gotta fetch the heap tuple ... */ curitup = (IndexTuple) PageGetItem(page, curitemid); htid = curitup->t_tid; /* * If we are doing a recheck, we expect to find the tuple we * are rechecking. It's not a duplicate, but we have to keep * scanning. */ if (checkUnique == UNIQUE_CHECK_EXISTING && ItemPointerCompare(&htid, &itup->t_tid) == 0) { found = true; } /* * We check the whole HOT-chain to see if there is any tuple * that satisfies SnapshotDirty. This is necessary because we * have just a single index entry for the entire chain. */ else if (heap_hot_search(&htid, heapRel, &SnapshotDirty, &all_dead)) { TransactionId xwait; /* * It is a duplicate. If we are only doing a partial * check, then don't bother checking if the tuple is being * updated in another transaction. Just return the fact * that it is a potential conflict and leave the full * check till later. */ if (checkUnique == UNIQUE_CHECK_PARTIAL) { if (nbuf != InvalidBuffer) _bt_relbuf(rel, nbuf); *is_unique = false; return InvalidTransactionId; } /* * If this tuple is being updated by other transaction * then we have to wait for its commit/abort. */ xwait = (TransactionIdIsValid(SnapshotDirty.xmin)) ? SnapshotDirty.xmin : SnapshotDirty.xmax; if (TransactionIdIsValid(xwait)) { if (nbuf != InvalidBuffer) _bt_relbuf(rel, nbuf); /* Tell _bt_doinsert to wait... */ return xwait; } /* * Otherwise we have a definite conflict. But before * complaining, look to see if the tuple we want to insert * is itself now committed dead --- if so, don't complain. * This is a waste of time in normal scenarios but we must * do it to support CREATE INDEX CONCURRENTLY. * * We must follow HOT-chains here because during * concurrent index build, we insert the root TID though * the actual tuple may be somewhere in the HOT-chain. * While following the chain we might not stop at the * exact tuple which triggered the insert, but that's OK * because if we find a live tuple anywhere in this chain, * we have a unique key conflict. The other live tuple is * not part of this chain because it had a different index * entry. */ htid = itup->t_tid; if (heap_hot_search(&htid, heapRel, SnapshotSelf, NULL)) { /* Normal case --- it's still live */ } else { /* * It's been deleted, so no error, and no need to * continue searching */ break; } /* * This is a definite conflict. Break the tuple down into * datums and report the error. But first, make sure we * release the buffer locks we're holding --- * BuildIndexValueDescription could make catalog accesses, * which in the worst case might touch this same index and * cause deadlocks. */ if (nbuf != InvalidBuffer) _bt_relbuf(rel, nbuf); _bt_relbuf(rel, buf); { Datum values[INDEX_MAX_KEYS]; bool isnull[INDEX_MAX_KEYS]; index_deform_tuple(itup, RelationGetDescr(rel), values, isnull); ereport(ERROR, (errcode(ERRCODE_UNIQUE_VIOLATION), errmsg("duplicate key value violates unique constraint \"%s\"", RelationGetRelationName(rel)), errdetail("Key %s already exists.", BuildIndexValueDescription(rel, values, isnull)), errtableconstraint(heapRel, RelationGetRelationName(rel)))); } } else if (all_dead) { /* * The conflicting tuple (or whole HOT chain) is dead to * everyone, so we may as well mark the index entry * killed. */ ItemIdMarkDead(curitemid); opaque->btpo_flags |= BTP_HAS_GARBAGE; /* * Mark buffer with a dirty hint, since state is not * crucial. Be sure to mark the proper buffer dirty. */ if (nbuf != InvalidBuffer) MarkBufferDirtyHint(nbuf, true); else MarkBufferDirtyHint(buf, true); } } } /* * Advance to next tuple to continue checking. */ if (offset < maxoff) offset = OffsetNumberNext(offset); else { /* If scankey == hikey we gotta check the next page too */ if (P_RIGHTMOST(opaque)) break; if (!_bt_isequal(itupdesc, page, P_HIKEY, natts, itup_scankey)) break; /* Advance to next non-dead page --- there must be one */ for (;;) { nblkno = opaque->btpo_next; nbuf = _bt_relandgetbuf(rel, nbuf, nblkno, BT_READ); page = BufferGetPage(nbuf); opaque = (BTPageOpaque) PageGetSpecialPointer(page); if (!P_IGNORE(opaque)) break; if (P_RIGHTMOST(opaque)) elog(ERROR, "fell off the end of index \"%s\"", RelationGetRelationName(rel)); } maxoff = PageGetMaxOffsetNumber(page); offset = P_FIRSTDATAKEY(opaque); } } /* * If we are doing a recheck then we should have found the tuple we are * checking. Otherwise there's something very wrong --- probably, the * index is on a non-immutable expression. */ if (checkUnique == UNIQUE_CHECK_EXISTING && !found) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("failed to re-find tuple within index \"%s\"", RelationGetRelationName(rel)), errhint("This may be because of a non-immutable index expression."), errtableconstraint(heapRel, RelationGetRelationName(rel)))); if (nbuf != InvalidBuffer) _bt_relbuf(rel, nbuf); return InvalidTransactionId; } ; 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: ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, HeapTuple violator, TupleDesc tupdesc, int queryno, bool spi_err) { StringInfoData key_names; StringInfoData key_values; bool onfk; const int16 *attnums; int idx; if (spi_err) ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("referential integrity query on \"%s\" from constraint \"%s\" on \"%s\" gave unexpected result", RelationGetRelationName(pk_rel), NameStr(riinfo->conname), RelationGetRelationName(fk_rel)), errhint("This is most likely due to a rule having rewritten the query."))); /* * Determine which relation to complain about. If tupdesc wasn't passed * by caller, assume the violator tuple came from there. */ onfk = (queryno == RI_PLAN_CHECK_LOOKUPPK); if (onfk) { attnums = riinfo->fk_attnums; if (tupdesc == NULL) tupdesc = fk_rel->rd_att; } else { attnums = riinfo->pk_attnums; if (tupdesc == NULL) tupdesc = pk_rel->rd_att; } /* Get printable versions of the keys involved */ initStringInfo(&key_names); initStringInfo(&key_values); for (idx = 0; idx < riinfo->nkeys; idx++) { int fnum = attnums[idx]; char *name, *val; name = SPI_fname(tupdesc, fnum); val = SPI_getvalue(violator, tupdesc, fnum); if (!val) val = "null"; if (idx > 0) { appendStringInfoString(&key_names, ", "); appendStringInfoString(&key_values, ", "); } appendStringInfoString(&key_names, name); appendStringInfoString(&key_values, val); } if (onfk) ereport(ERROR, (errcode(ERRCODE_FOREIGN_KEY_VIOLATION), errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"", RelationGetRelationName(fk_rel), NameStr(riinfo->conname)), errdetail("Key (%s)=(%s) is not present in table \"%s\".", key_names.data, key_values.data, RelationGetRelationName(pk_rel)), errtableconstraint(fk_rel, NameStr(riinfo->conname)))); else ereport(ERROR, (errcode(ERRCODE_FOREIGN_KEY_VIOLATION), errmsg("update or delete on table \"%s\" violates foreign key constraint \"%s\" on table \"%s\"", RelationGetRelationName(pk_rel), NameStr(riinfo->conname), RelationGetRelationName(fk_rel)), errdetail("Key (%s)=(%s) is still referenced from table \"%s\".", key_names.data, key_values.data, RelationGetRelationName(fk_rel)), errtableconstraint(fk_rel, NameStr(riinfo->conname)))); } ; 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: set_hunkmax (void) { if (!p_line) p_line = (char **) malloc (hunkmax * sizeof *p_line); if (!p_len) p_len = (size_t *) malloc (hunkmax * sizeof *p_len); if (!p_Char) p_Char = malloc (hunkmax * sizeof *p_Char); } ; 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: static int em_sysenter(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; ops->get_msr(ctxt, MSR_EFER, &efer); /* inject #GP if in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL) return emulate_gp(ctxt, 0); /* * Not recognized on AMD in compat mode (but is recognized in legacy * mode). */ if ((ctxt->mode == X86EMUL_MODE_PROT32) && (efer & EFER_LMA) && !vendor_intel(ctxt)) return emulate_ud(ctxt); /* sysenter/sysexit have not been tested in 64bit mode. */ if (ctxt->mode == X86EMUL_MODE_PROT64) return X86EMUL_UNHANDLEABLE; setup_syscalls_segments(ctxt, &cs, &ss); ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data); switch (ctxt->mode) { case X86EMUL_MODE_PROT32: if ((msr_data & 0xfffc) == 0x0) return emulate_gp(ctxt, 0); break; case X86EMUL_MODE_PROT64: if (msr_data == 0x0) return emulate_gp(ctxt, 0); break; default: break; } ctxt->eflags &= ~(EFLG_VM | EFLG_IF); cs_sel = (u16)msr_data; cs_sel &= ~SELECTOR_RPL_MASK; ss_sel = cs_sel + 8; ss_sel &= ~SELECTOR_RPL_MASK; if (ctxt->mode == X86EMUL_MODE_PROT64 || (efer & EFER_LMA)) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data); ctxt->_eip = msr_data; ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data); *reg_write(ctxt, VCPU_REGS_RSP) = msr_data; return X86EMUL_CONTINUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-269'], 'message': 'KVM: x86: SYSENTER emulation is broken SYSENTER emulation is broken in several ways: 1. It misses the case of 16-bit code segments completely (CVE-2015-0239). 2. MSR_IA32_SYSENTER_CS is checked in 64-bit mode incorrectly (bits 0 and 1 can still be set without causing #GP). 3. MSR_IA32_SYSENTER_EIP and MSR_IA32_SYSENTER_ESP are not masked in legacy-mode. 4. There is some unneeded code. Fix it. Cc: stable@vger.linux.org 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: fmtfloat(double value, char type, int forcesign, int leftjust, int minlen, int zpad, int precision, int pointflag, PrintfTarget *target) { int signvalue = 0; int vallen; char fmt[32]; char convert[512]; int padlen = 0; /* amount to pad */ /* we rely on regular C library's sprintf to do the basic conversion */ if (pointflag) sprintf(fmt, "%%.%d%c", precision, type); else sprintf(fmt, "%%%c", type); if (adjust_sign((value < 0), forcesign, &signvalue)) value = -value; vallen = sprintf(convert, fmt, value); adjust_padlen(minlen, vallen, leftjust, &padlen); leading_pad(zpad, &signvalue, &padlen, target); dostr(convert, vallen, target); trailing_pad(&padlen, target); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'port/snprintf(): fix overflow and do padding Prevent port/snprintf() from overflowing its local fixed-size buffer and pad to the desired number of digits with zeros, even if the precision is beyond the ability of the native sprintf(). port/snprintf() is only used on systems that lack a native snprintf(). Reported by Bruce Momjian. Patch by Tom Lane. Backpatch to all supported versions. Security: CVE-2015-0242'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pg_GSS_recvauth(Port *port) { OM_uint32 maj_stat, min_stat, lmin_s, gflags; int mtype; int ret; StringInfoData buf; gss_buffer_desc gbuf; /* * GSS auth is not supported for protocol versions before 3, because it * relies on the overall message length word to determine the GSS payload * size in AuthenticationGSSContinue and PasswordMessage messages. (This * is, in fact, a design error in our GSS support, because protocol * messages are supposed to be parsable without relying on the length * word; but it's not worth changing it now.) */ if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3) ereport(FATAL, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("GSSAPI is not supported in protocol version 2"))); if (pg_krb_server_keyfile && strlen(pg_krb_server_keyfile) > 0) { /* * Set default Kerberos keytab file for the Krb5 mechanism. * * setenv("KRB5_KTNAME", pg_krb_server_keyfile, 0); except setenv() * not always available. */ if (getenv("KRB5_KTNAME") == NULL) { size_t kt_len = strlen(pg_krb_server_keyfile) + 14; char *kt_path = malloc(kt_len); if (!kt_path) { ereport(LOG, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory"))); return STATUS_ERROR; } snprintf(kt_path, kt_len, "KRB5_KTNAME=%s", pg_krb_server_keyfile); putenv(kt_path); } } /* * We accept any service principal that's present in our keytab. This * increases interoperability between kerberos implementations that see * for example case sensitivity differently, while not really opening up * any vector of attack. */ port->gss->cred = GSS_C_NO_CREDENTIAL; /* * Initialize sequence with an empty context */ port->gss->ctx = GSS_C_NO_CONTEXT; /* * Loop through GSSAPI message exchange. This exchange can consist of * multiple messags sent in both directions. First message is always from * the client. All messages from client to server are password packets * (type 'p'). */ do { mtype = pq_getbyte(); if (mtype != 'p') { /* Only log error if client didn't disconnect. */ if (mtype != EOF) ereport(COMMERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("expected GSS response, got message type %d", mtype))); return STATUS_ERROR; } /* Get the actual GSS token */ initStringInfo(&buf); if (pq_getmessage(&buf, PG_MAX_AUTH_TOKEN_LENGTH)) { /* EOF - pq_getmessage already logged error */ pfree(buf.data); return STATUS_ERROR; } /* Map to GSSAPI style buffer */ gbuf.length = buf.len; gbuf.value = buf.data; elog(DEBUG4, "Processing received GSS token of length %u", (unsigned int) gbuf.length); maj_stat = gss_accept_sec_context( &min_stat, &port->gss->ctx, port->gss->cred, &gbuf, GSS_C_NO_CHANNEL_BINDINGS, &port->gss->name, NULL, &port->gss->outbuf, &gflags, NULL, NULL); /* gbuf no longer used */ pfree(buf.data); elog(DEBUG5, "gss_accept_sec_context major: %d, " "minor: %d, outlen: %u, outflags: %x", maj_stat, min_stat, (unsigned int) port->gss->outbuf.length, gflags); if (port->gss->outbuf.length != 0) { /* * Negotiation generated data to be sent to the client. */ elog(DEBUG4, "sending GSS response token of length %u", (unsigned int) port->gss->outbuf.length); sendAuthRequest(port, AUTH_REQ_GSS_CONT); gss_release_buffer(&lmin_s, &port->gss->outbuf); } if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED) { gss_delete_sec_context(&lmin_s, &port->gss->ctx, GSS_C_NO_BUFFER); pg_GSS_error(ERROR, gettext_noop("accepting GSS security context failed"), maj_stat, min_stat); } if (maj_stat == GSS_S_CONTINUE_NEEDED) elog(DEBUG4, "GSS continue needed"); } while (maj_stat == GSS_S_CONTINUE_NEEDED); if (port->gss->cred != GSS_C_NO_CREDENTIAL) { /* * Release service principal credentials */ gss_release_cred(&min_stat, &port->gss->cred); } /* * GSS_S_COMPLETE indicates that authentication is now complete. * * Get the name of the user that authenticated, and compare it to the pg * username that was specified for the connection. */ maj_stat = gss_display_name(&min_stat, port->gss->name, &gbuf, NULL); if (maj_stat != GSS_S_COMPLETE) pg_GSS_error(ERROR, gettext_noop("retrieving GSS user name failed"), maj_stat, min_stat); /* * Split the username at the realm separator */ if (strchr(gbuf.value, '@')) { char *cp = strchr(gbuf.value, '@'); /* * If we are not going to include the realm in the username that is * passed to the ident map, destructively modify it here to remove the * realm. Then advance past the separator to check the realm. */ if (!port->hba->include_realm) *cp = '\0'; cp++; if (port->hba->krb_realm != NULL && strlen(port->hba->krb_realm)) { /* * Match the realm part of the name first */ if (pg_krb_caseins_users) ret = pg_strcasecmp(port->hba->krb_realm, cp); else ret = strcmp(port->hba->krb_realm, cp); if (ret) { /* GSS realm does not match */ elog(DEBUG2, "GSSAPI realm (%s) and configured realm (%s) don't match", cp, port->hba->krb_realm); gss_release_buffer(&lmin_s, &gbuf); return STATUS_ERROR; } } } else if (port->hba->krb_realm && strlen(port->hba->krb_realm)) { elog(DEBUG2, "GSSAPI did not return realm but realm matching was requested"); gss_release_buffer(&lmin_s, &gbuf); return STATUS_ERROR; } ret = check_usermap(port->hba->usermap, port->user_name, gbuf.value, pg_krb_caseins_users); gss_release_buffer(&lmin_s, &gbuf); return ret; } ; 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: CopyGetData(CopyState cstate, void *databuf, int minread, int maxread) { int bytesread = 0; switch (cstate->copy_dest) { case COPY_FILE: bytesread = fread(databuf, 1, maxread, cstate->copy_file); if (ferror(cstate->copy_file)) ereport(ERROR, (errcode_for_file_access(), errmsg("could not read from COPY file: %m"))); break; case COPY_OLD_FE: /* * We cannot read more than minread bytes (which in practice is 1) * because old protocol doesn't have any clear way of separating * the COPY stream from following data. This is slow, but not any * slower than the code path was originally, and we don't care * much anymore about the performance of old protocol. */ if (pq_getbytes((char *) databuf, minread)) { /* Only a \. terminator is legal EOF in old protocol */ ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("unexpected EOF on client connection with an open transaction"))); } bytesread = minread; break; case COPY_NEW_FE: while (maxread > 0 && bytesread < minread && !cstate->fe_eof) { int avail; while (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len) { /* Try to receive another message */ int mtype; readmessage: mtype = pq_getbyte(); if (mtype == EOF) ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("unexpected EOF on client connection with an open transaction"))); if (pq_getmessage(cstate->fe_msgbuf, 0)) ereport(ERROR, (errcode(ERRCODE_CONNECTION_FAILURE), errmsg("unexpected EOF on client connection with an open transaction"))); switch (mtype) { case 'd': /* CopyData */ break; case 'c': /* CopyDone */ /* COPY IN correctly terminated by frontend */ cstate->fe_eof = true; return bytesread; case 'f': /* CopyFail */ ereport(ERROR, (errcode(ERRCODE_QUERY_CANCELED), errmsg("COPY from stdin failed: %s", pq_getmsgstring(cstate->fe_msgbuf)))); break; case 'H': /* Flush */ case 'S': /* Sync */ /* * Ignore Flush/Sync for the convenience of client * libraries (such as libpq) that may send those * without noticing that the command they just * sent was COPY. */ goto readmessage; default: ereport(ERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), errmsg("unexpected message type 0x%02X during COPY from stdin", mtype))); break; } } avail = cstate->fe_msgbuf->len - cstate->fe_msgbuf->cursor; if (avail > maxread) avail = maxread; pq_copymsgbytes(cstate->fe_msgbuf, databuf, avail); databuf = (void *) ((char *) databuf + avail); maxread -= avail; bytesread += avail; } break; } return bytesread; } ; 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_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int sh_num) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = "statically"; const char *interp = ""; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) == -1) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = "dynamically"; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, ", invalid note alignment 0x%lx", (unsigned long)align) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } break; default: if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } /* Things we can determine when we seek */ switch (xph_type) { case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\0'; interp = (const char *)nbuf; } else interp = "*empty*"; break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, align, flags); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, ", %s linked", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, ", interpreter %s", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; 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: v3_keyid (gcry_mpi_t a, u32 *ki) { byte *buffer, *p; size_t nbytes; if (gcry_mpi_print (GCRYMPI_FMT_USG, NULL, 0, &nbytes, a )) BUG (); /* fixme: allocate it on the stack */ buffer = xmalloc (nbytes); if (gcry_mpi_print( GCRYMPI_FMT_USG, buffer, nbytes, NULL, a )) BUG (); if (nbytes < 8) /* oops */ ki[0] = ki[1] = 0; else { p = buffer + nbytes - 8; ki[0] = (p[0] << 24) | (p[1] <<16) | (p[2] << 8) | p[3]; p += 4; ki[1] = (p[0] << 24) | (p[1] <<16) | (p[2] << 8) | p[3]; } xfree (buffer); return ki[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: parse (IOBUF inp, PACKET * pkt, int onlykeypkts, off_t * retpos, int *skip, IOBUF out, int do_skip #ifdef DEBUG_PARSE_PACKET , const char *dbg_w, const char *dbg_f, int dbg_l #endif ) { int rc = 0, c, ctb, pkttype, lenbytes; unsigned long pktlen; byte hdr[8]; int hdrlen; int new_ctb = 0, partial = 0; int with_uid = (onlykeypkts == 2); off_t pos; *skip = 0; assert (!pkt->pkt.generic); if (retpos || list_mode) { pos = iobuf_tell (inp); if (retpos) *retpos = pos; } else pos = 0; /* (silence compiler warning) */ if ((ctb = iobuf_get (inp)) == -1) { rc = -1; goto leave; } hdrlen = 0; hdr[hdrlen++] = ctb; if (!(ctb & 0x80)) { log_error ("%s: invalid packet (ctb=%02x)\n", iobuf_where (inp), ctb); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } pktlen = 0; new_ctb = !!(ctb & 0x40); if (new_ctb) { pkttype = ctb & 0x3f; if ((c = iobuf_get (inp)) == -1) { log_error ("%s: 1st length byte missing\n", iobuf_where (inp)); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } hdr[hdrlen++] = c; if (c < 192) pktlen = c; else if (c < 224) { pktlen = (c - 192) * 256; if ((c = iobuf_get (inp)) == -1) { log_error ("%s: 2nd length byte missing\n", iobuf_where (inp)); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } hdr[hdrlen++] = c; pktlen += c + 192; } else if (c == 255) { pktlen = (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 24; pktlen |= (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 16; pktlen |= (hdr[hdrlen++] = iobuf_get_noeof (inp)) << 8; if ((c = iobuf_get (inp)) == -1) { log_error ("%s: 4 byte length invalid\n", iobuf_where (inp)); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } pktlen |= (hdr[hdrlen++] = c); } else /* Partial body length. */ { switch (pkttype) { case PKT_PLAINTEXT: case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: case PKT_COMPRESSED: iobuf_set_partial_block_mode (inp, c & 0xff); pktlen = 0; /* To indicate partial length. */ partial = 1; break; default: log_error ("%s: partial length for invalid" " packet type %d\n", iobuf_where (inp), pkttype); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } } } else { pkttype = (ctb >> 2) & 0xf; lenbytes = ((ctb & 3) == 3) ? 0 : (1 << (ctb & 3)); if (!lenbytes) { pktlen = 0; /* Don't know the value. */ /* This isn't really partial, but we can treat it the same in a "read until the end" sort of way. */ partial = 1; if (pkttype != PKT_ENCRYPTED && pkttype != PKT_PLAINTEXT && pkttype != PKT_COMPRESSED) { log_error ("%s: indeterminate length for invalid" " packet type %d\n", iobuf_where (inp), pkttype); rc = gpg_error (GPG_ERR_INV_PACKET); goto leave; } } else { for (; lenbytes; lenbytes--) { pktlen <<= 8; pktlen |= hdr[hdrlen++] = iobuf_get_noeof (inp); } } } if (pktlen == (unsigned long) (-1)) { /* With some probability this is caused by a problem in the * the uncompressing layer - in some error cases it just loops * and spits out 0xff bytes. */ log_error ("%s: garbled packet detected\n", iobuf_where (inp)); g10_exit (2); } if (out && pkttype) { rc = iobuf_write (out, hdr, hdrlen); if (!rc) rc = copy_packet (inp, out, pkttype, pktlen, partial); goto leave; } if (with_uid && pkttype == PKT_USER_ID) ; else if (do_skip || !pkttype || (onlykeypkts && pkttype != PKT_PUBLIC_SUBKEY && pkttype != PKT_PUBLIC_KEY && pkttype != PKT_SECRET_SUBKEY && pkttype != PKT_SECRET_KEY)) { iobuf_skip_rest (inp, pktlen, partial); *skip = 1; rc = 0; goto leave; } if (DBG_PACKET) { #ifdef DEBUG_PARSE_PACKET log_debug ("parse_packet(iob=%d): type=%d length=%lu%s (%s.%s.%d)\n", iobuf_id (inp), pkttype, pktlen, new_ctb ? " (new_ctb)" : "", dbg_w, dbg_f, dbg_l); #else log_debug ("parse_packet(iob=%d): type=%d length=%lu%s\n", iobuf_id (inp), pkttype, pktlen, new_ctb ? " (new_ctb)" : ""); #endif } if (list_mode) es_fprintf (listfp, "# off=%lu ctb=%02x tag=%d hlen=%d plen=%lu%s%s\n", (unsigned long)pos, ctb, pkttype, hdrlen, pktlen, partial? " partial":"", new_ctb? " new-ctb":""); pkt->pkttype = pkttype; rc = GPG_ERR_UNKNOWN_PACKET; /* default error */ switch (pkttype) { case PKT_PUBLIC_KEY: case PKT_PUBLIC_SUBKEY: case PKT_SECRET_KEY: case PKT_SECRET_SUBKEY: pkt->pkt.public_key = xmalloc_clear (sizeof *pkt->pkt.public_key); rc = parse_key (inp, pkttype, pktlen, hdr, hdrlen, pkt); break; case PKT_SYMKEY_ENC: rc = parse_symkeyenc (inp, pkttype, pktlen, pkt); break; case PKT_PUBKEY_ENC: rc = parse_pubkeyenc (inp, pkttype, pktlen, pkt); break; case PKT_SIGNATURE: pkt->pkt.signature = xmalloc_clear (sizeof *pkt->pkt.signature); rc = parse_signature (inp, pkttype, pktlen, pkt->pkt.signature); break; case PKT_ONEPASS_SIG: pkt->pkt.onepass_sig = xmalloc_clear (sizeof *pkt->pkt.onepass_sig); rc = parse_onepass_sig (inp, pkttype, pktlen, pkt->pkt.onepass_sig); break; case PKT_USER_ID: rc = parse_user_id (inp, pkttype, pktlen, pkt); break; case PKT_ATTRIBUTE: pkt->pkttype = pkttype = PKT_USER_ID; /* we store it in the userID */ rc = parse_attribute (inp, pkttype, pktlen, pkt); break; case PKT_OLD_COMMENT: case PKT_COMMENT: rc = parse_comment (inp, pkttype, pktlen, pkt); break; case PKT_RING_TRUST: parse_trust (inp, pkttype, pktlen, pkt); rc = 0; break; case PKT_PLAINTEXT: rc = parse_plaintext (inp, pkttype, pktlen, pkt, new_ctb, partial); break; case PKT_COMPRESSED: rc = parse_compressed (inp, pkttype, pktlen, pkt, new_ctb); break; case PKT_ENCRYPTED: case PKT_ENCRYPTED_MDC: rc = parse_encrypted (inp, pkttype, pktlen, pkt, new_ctb, partial); break; case PKT_MDC: rc = parse_mdc (inp, pkttype, pktlen, pkt, new_ctb); break; case PKT_GPG_CONTROL: rc = parse_gpg_control (inp, pkttype, pktlen, pkt, partial); break; case PKT_MARKER: rc = parse_marker (inp, pkttype, pktlen); break; default: skip_packet (inp, pkttype, pktlen, partial); break; } leave: /* FIXME: Do we leak in case of an error? */ if (!rc && iobuf_error (inp)) rc = GPG_ERR_INV_KEYRING; /* FIXME: We use only the error code for now to avoid problems with callers which have not been checked to always use gpg_err_code() when comparing error codes. */ return rc == -1? -1 : gpg_err_code (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: control_pcsc_wrapped (int slot, pcsc_dword_t ioctl_code, const unsigned char *cntlbuf, size_t len, unsigned char *buffer, pcsc_dword_t *buflen) { long err = PCSC_E_NOT_TRANSACTED; reader_table_t slotp; unsigned char msgbuf[9]; int i, n; size_t full_len; slotp = reader_table + slot; msgbuf[0] = 0x06; /* CONTROL command. */ msgbuf[1] = ((len + 4) >> 24); msgbuf[2] = ((len + 4) >> 16); msgbuf[3] = ((len + 4) >> 8); msgbuf[4] = ((len + 4) ); msgbuf[5] = (ioctl_code >> 24); msgbuf[6] = (ioctl_code >> 16); msgbuf[7] = (ioctl_code >> 8); msgbuf[8] = (ioctl_code ); if ( writen (slotp->pcsc.req_fd, msgbuf, 9) || writen (slotp->pcsc.req_fd, cntlbuf, len)) { log_error ("error sending PC/SC CONTROL request: %s\n", strerror (errno)); goto command_failed; } /* Read the response. */ if ((i=readn (slotp->pcsc.rsp_fd, msgbuf, 9, &len)) || len != 9) { log_error ("error receiving PC/SC CONTROL response: %s\n", i? strerror (errno) : "premature EOF"); goto command_failed; } len = (msgbuf[1] << 24) | (msgbuf[2] << 16) | (msgbuf[3] << 8 ) | msgbuf[4]; if (msgbuf[0] != 0x81 || len < 4) { log_error ("invalid response header from PC/SC received\n"); goto command_failed; } len -= 4; /* Already read the error code. */ err = PCSC_ERR_MASK ((msgbuf[5] << 24) | (msgbuf[6] << 16) | (msgbuf[7] << 8 ) | msgbuf[8]); if (err) { log_error ("pcsc_control failed: %s (0x%lx)\n", pcsc_error_string (err), err); return pcsc_error_to_sw (err); } full_len = len; n = *buflen < len ? *buflen : len; if ((i=readn (slotp->pcsc.rsp_fd, buffer, n, &len)) || len != n) { log_error ("error receiving PC/SC CONTROL response: %s\n", i? strerror (errno) : "premature EOF"); goto command_failed; } *buflen = n; full_len -= len; if (full_len) { log_error ("pcsc_send_apdu: provided buffer too short - truncated\n"); err = PCSC_E_INVALID_VALUE; } /* We need to read any rest of the response, to keep the protocol running. */ while (full_len) { unsigned char dummybuf[128]; n = full_len < DIM (dummybuf) ? full_len : DIM (dummybuf); if ((i=readn (slotp->pcsc.rsp_fd, dummybuf, n, &len)) || len != n) { log_error ("error receiving PC/SC CONTROL response: %s\n", i? strerror (errno) : "premature EOF"); goto command_failed; } full_len -= n; } if (!err) return 0; command_failed: close (slotp->pcsc.req_fd); close (slotp->pcsc.rsp_fd); slotp->pcsc.req_fd = -1; slotp->pcsc.rsp_fd = -1; if (slotp->pcsc.pid != -1) kill (slotp->pcsc.pid, SIGTERM); slotp->pcsc.pid = (pid_t)(-1); slotp->used = 0; return pcsc_error_to_sw (err); } ; 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: get16 (const byte *buffer) { ulong a; a = *buffer << 8; a |= buffer[1]; return a; } ; 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: buffer_to_u32( const byte *buffer ) { unsigned long a; a = *buffer << 24; a |= buffer[1] << 16; a |= buffer[2] << 8; a |= buffer[3]; return a; } ; 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_attr3_leaf_list_int( struct xfs_buf *bp, struct xfs_attr_list_context *context) { struct attrlist_cursor_kern *cursor; struct xfs_attr_leafblock *leaf; struct xfs_attr3_icleaf_hdr ichdr; struct xfs_attr_leaf_entry *entries; struct xfs_attr_leaf_entry *entry; int retval; int i; trace_xfs_attr_list_leaf(context); leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf); entries = xfs_attr3_leaf_entryp(leaf); cursor = context->cursor; cursor->initted = 1; /* * Re-find our place in the leaf block if this is a new syscall. */ if (context->resynch) { entry = &entries[0]; for (i = 0; i < ichdr.count; entry++, i++) { if (be32_to_cpu(entry->hashval) == cursor->hashval) { if (cursor->offset == context->dupcnt) { context->dupcnt = 0; break; } context->dupcnt++; } else if (be32_to_cpu(entry->hashval) > cursor->hashval) { context->dupcnt = 0; break; } } if (i == ichdr.count) { trace_xfs_attr_list_notfound(context); return 0; } } else { entry = &entries[0]; i = 0; } context->resynch = 0; /* * We have found our place, start copying out the new attributes. */ retval = 0; for (; i < ichdr.count; entry++, i++) { if (be32_to_cpu(entry->hashval) != cursor->hashval) { cursor->hashval = be32_to_cpu(entry->hashval); cursor->offset = 0; } if (entry->flags & XFS_ATTR_INCOMPLETE) continue; /* skip incomplete entries */ if (entry->flags & XFS_ATTR_LOCAL) { xfs_attr_leaf_name_local_t *name_loc = xfs_attr3_leaf_name_local(leaf, i); retval = context->put_listent(context, entry->flags, name_loc->nameval, (int)name_loc->namelen, be16_to_cpu(name_loc->valuelen), &name_loc->nameval[name_loc->namelen]); if (retval) return retval; } else { xfs_attr_leaf_name_remote_t *name_rmt = xfs_attr3_leaf_name_remote(leaf, i); int valuelen = be32_to_cpu(name_rmt->valuelen); if (context->put_value) { xfs_da_args_t args; memset((char *)&args, 0, sizeof(args)); args.dp = context->dp; args.whichfork = XFS_ATTR_FORK; args.valuelen = valuelen; args.value = kmem_alloc(valuelen, KM_SLEEP | KM_NOFS); args.rmtblkno = be32_to_cpu(name_rmt->valueblk); args.rmtblkcnt = xfs_attr3_rmt_blocks( args.dp->i_mount, valuelen); retval = xfs_attr_rmtval_get(&args); if (retval) return retval; retval = context->put_listent(context, entry->flags, name_rmt->name, (int)name_rmt->namelen, valuelen, args.value); kmem_free(args.value); } else { retval = context->put_listent(context, entry->flags, name_rmt->name, (int)name_rmt->namelen, valuelen, NULL); } if (retval) return retval; } if (context->seen_enough) break; cursor->offset++; } trace_xfs_attr_list_leaf_end(context); return retval; } ; 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: static Image *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception) { char format[MaxTextExtent], keyword[MaxTextExtent], tag[MaxTextExtent], value[MaxTextExtent]; double gamma; Image *image; int c; MagickBooleanType status, value_expected; register Quantum *q; register ssize_t i, x; register unsigned char *p; ssize_t count, y; unsigned char *end, pixel[4], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Decode image header. */ image->columns=0; image->rows=0; *format='\0'; c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } while (isgraph(c) && (image->columns == 0) && (image->rows == 0)) { if (c == (int) '#') { char *comment; register char *p; size_t length; /* Read comment-- any text between # and end-of-line. */ length=MaxTextExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if ((c == EOF) || (c == (int) '\n')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MaxTextExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) == MagickFalse) c=ReadBlobByte(image); else { register char *p; /* Determine a keyword and its value. */ p=keyword; do { if ((size_t) (p-keyword) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } while (isalnum(c) || (c == '_')); *p='\0'; value_expected=MagickFalse; while ((isspace((int) ((unsigned char) c)) != 0) || (c == '=')) { if (c == '=') value_expected=MagickTrue; c=ReadBlobByte(image); } if (LocaleCompare(keyword,"Y") == 0) value_expected=MagickTrue; if (value_expected == MagickFalse) continue; p=value; while ((c != '\n') && (c != '\0')) { if ((size_t) (p-value) < (MaxTextExtent-1)) *p++=c; c=ReadBlobByte(image); } *p='\0'; /* Assign a value to the specified keyword. */ switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"format") == 0) { (void) CopyMagickString(format,value,MaxTextExtent); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(value,(char **) NULL); break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"primaries") == 0) { float chromaticity[6], white_point[2]; (void) sscanf(value,"%g %g %g %g %g %g %g %g", &chromaticity[0],&chromaticity[1],&chromaticity[2], &chromaticity[3],&chromaticity[4],&chromaticity[5], &white_point[0],&white_point[1]); image->chromaticity.red_primary.x=chromaticity[0]; image->chromaticity.red_primary.y=chromaticity[1]; image->chromaticity.green_primary.x=chromaticity[2]; image->chromaticity.green_primary.y=chromaticity[3]; image->chromaticity.blue_primary.x=chromaticity[4]; image->chromaticity.blue_primary.y=chromaticity[5]; image->chromaticity.white_point.x=white_point[0], image->chromaticity.white_point.y=white_point[1]; break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } case 'Y': case 'y': { char target[] = "Y"; if (strcmp(keyword,target) == 0) { int height, width; (void) sscanf(value,"%d +X %d",&height,&width); image->columns=(size_t) width; image->rows=(size_t) height; break; } (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } default: { (void) FormatLocaleString(tag,MaxTextExtent,"hdr:%s",keyword); (void) SetImageProperty(image,tag,value,exception); break; } } } if ((image->columns == 0) && (image->rows == 0)) while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) && (LocaleCompare(format,"32-bit_rle_xyze") != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); (void) SetImageColorspace(image,RGBColorspace,exception); if (LocaleCompare(format,"32-bit_rle_xyze") == 0) (void) SetImageColorspace(image,XYZColorspace,exception); image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ? NoCompression : RLECompression; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Read RGBE (red+green+blue+exponent) pixels. */ pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4* sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (y=0; y < (ssize_t) image->rows; y++) { if (image->compression != RLECompression) { count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels); if (count != (ssize_t) (4*image->columns*sizeof(*pixels))) break; } else { count=ReadBlob(image,4*sizeof(*pixel),pixel); if (count != 4) break; if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns) { (void) memcpy(pixels,pixel,4*sizeof(*pixel)); count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4); image->compression=NoCompression; } else { p=pixels; for (i=0; i < 4; i++) { end=&pixels[(i+1)*image->columns]; while (p < end) { count=ReadBlob(image,2*sizeof(*pixel),pixel); if (count < 1) break; if (pixel[0] > 128) { count=(ssize_t) pixel[0]-128; if ((count == 0) || (count > (ssize_t) (end-p))) break; while (count-- > 0) *p++=pixel[1]; } else { count=(ssize_t) pixel[0]; if ((count == 0) || (count > (ssize_t) (end-p))) break; *p++=pixel[1]; if (--count > 0) { count=ReadBlob(image,(size_t) count*sizeof(*p),p); if (count < 1) break; p+=count; } } } } } } q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; i=0; for (x=0; x < (ssize_t) image->columns; x++) { if (image->compression == RLECompression) { pixel[0]=pixels[x]; pixel[1]=pixels[x+image->columns]; pixel[2]=pixels[x+2*image->columns]; pixel[3]=pixels[x+3*image->columns]; } else { pixel[0]=pixels[i++]; pixel[1]=pixels[i++]; pixel[2]=pixels[i++]; pixel[3]=pixels[i++]; } SetPixelRed(image,0,q); SetPixelGreen(image,0,q); SetPixelBlue(image,0,q); if (pixel[3] != 0) { gamma=pow(2.0,pixel[3]-(128.0+8.0)); SetPixelRed(image,ClampToQuantum(QuantumRange*gamma*pixel[0]),q); SetPixelGreen(image,ClampToQuantum(QuantumRange*gamma*pixel[1]),q); SetPixelBlue(image,ClampToQuantum(QuantumRange*gamma*pixel[2]),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-703', 'CWE-835'], 'message': 'Fixed infinite loop and added checks for the sscanf result.'</s>
<s>[INST] Given the following code containing errors, provide 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 file_list_cpu(struct file *file) { #ifdef CONFIG_SMP return file->f_sb_list_cpu; #else return smp_processor_id(); #endif } ; 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: void file_sb_list_del(struct file *file) { if (!list_empty(&file->f_u.fu_list)) { lg_local_lock_cpu(&files_lglock, file_list_cpu(file)); list_del_init(&file->f_u.fu_list); lg_local_unlock_cpu(&files_lglock, file_list_cpu(file)); } } ; 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: pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len, int atomic) { unsigned long copy; while (len > 0) { while (!iov->iov_len) iov++; copy = min_t(unsigned long, len, iov->iov_len); if (atomic) { if (__copy_from_user_inatomic(to, iov->iov_base, copy)) return -EFAULT; } else { if (copy_from_user(to, iov->iov_base, copy)) return -EFAULT; } to += copy; len -= copy; iov->iov_base += copy; iov->iov_len -= copy; } return 0; } ; 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 xsave_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:"XSAVES"\n\t" "2:\n\t" : : "D" (fx), "m" (*fx), "a" (lmask), "d" (hmask) : "memory"); else asm volatile("1:"XSAVE"\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: static encodePtr get_array_type(xmlNodePtr node, zval *array, smart_str *type TSRMLS_DC) { HashTable *ht; int i, count, cur_type, prev_type, different; zval **tmp; char *prev_stype = NULL, *cur_stype = NULL, *prev_ns = NULL, *cur_ns = NULL; if (!array || Z_TYPE_P(array) != IS_ARRAY) { smart_str_appendl(type, "xsd:anyType", sizeof("xsd:anyType")-1); return get_conversion(XSD_ANYTYPE); } different = FALSE; cur_type = prev_type = 0; ht = HASH_OF(array); count = zend_hash_num_elements(ht); zend_hash_internal_pointer_reset(ht); for (i = 0;i < count;i++) { zend_hash_get_current_data(ht, (void **)&tmp); if (Z_TYPE_PP(tmp) == IS_OBJECT && Z_OBJCE_PP(tmp) == soap_var_class_entry) { zval **ztype; if (zend_hash_find(Z_OBJPROP_PP(tmp), "enc_type", sizeof("enc_type"), (void **)&ztype) == FAILURE) { soap_error0(E_ERROR, "Encoding: SoapVar has no 'enc_type' property"); } cur_type = Z_LVAL_PP(ztype); if (zend_hash_find(Z_OBJPROP_PP(tmp), "enc_stype", sizeof("enc_stype"), (void **)&ztype) == SUCCESS) { cur_stype = Z_STRVAL_PP(ztype); } else { cur_stype = NULL; } if (zend_hash_find(Z_OBJPROP_PP(tmp), "enc_ns", sizeof("enc_ns"), (void **)&ztype) == SUCCESS) { cur_ns = Z_STRVAL_PP(ztype); } else { cur_ns = NULL; } } else if (Z_TYPE_PP(tmp) == IS_ARRAY && is_map(*tmp)) { cur_type = APACHE_MAP; cur_stype = NULL; cur_ns = NULL; } else { cur_type = Z_TYPE_PP(tmp); cur_stype = NULL; cur_ns = NULL; } if (i > 0) { if ((cur_type != prev_type) || (cur_stype != NULL && prev_stype != NULL && strcmp(cur_stype,prev_stype) != 0) || (cur_stype == NULL && cur_stype != prev_stype) || (cur_ns != NULL && prev_ns != NULL && strcmp(cur_ns,prev_ns) != 0) || (cur_ns == NULL && cur_ns != prev_ns)) { different = TRUE; break; } } prev_type = cur_type; prev_stype = cur_stype; prev_ns = cur_ns; zend_hash_move_forward(ht); } if (different || count == 0) { smart_str_appendl(type, "xsd:anyType", sizeof("xsd:anyType")-1); return get_conversion(XSD_ANYTYPE); } else { encodePtr enc; if (cur_stype != NULL) { smart_str array_type = {0}; if (cur_ns) { xmlNsPtr ns = encode_add_ns(node, cur_ns); smart_str_appends(type, (char*)ns->prefix); smart_str_appendc(type, ':'); smart_str_appends(&array_type, cur_ns); smart_str_appendc(&array_type, ':'); } smart_str_appends(type, cur_stype); smart_str_0(type); smart_str_appends(&array_type, cur_stype); smart_str_0(&array_type); enc = get_encoder_ex(SOAP_GLOBAL(sdl), array_type.c, array_type.len); smart_str_free(&array_type); return enc; } else { enc = get_conversion(cur_type); get_type_str(node, enc->details.ns, enc->details.type_str, type); return enc; } } } ; 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_gid_request(enum request_types request_type, gid_t gid, const char *domain_name, struct berval **berval) { int ret; struct group grp; struct group *grp_result = NULL; char *sid_str = NULL; enum sss_id_type id_type; size_t buf_len; char *buf = NULL; struct sss_nss_kv *kv_list = NULL; ret = get_buffer(&buf_len, &buf); if (ret != LDAP_SUCCESS) { return ret; } if (request_type == REQ_SIMPLE) { ret = sss_nss_getsidbyid(gid, &sid_str, &id_type); if (ret != 0 || id_type != SSS_ID_TYPE_GID) { if (ret == ENOENT) { ret = LDAP_NO_SUCH_OBJECT; } else { ret = LDAP_OPERATIONS_ERROR; } goto done; } ret = pack_ber_sid(sid_str, berval); } else { ret = getgrgid_r(gid, &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); } done: sss_nss_free_kv(kv_list); free(sid_str); 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: SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; if (size > INT_MAX) size = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; iov.iov_len = size; iov.iov_base = ubuf; iov_iter_init(&msg.msg_iter, READ, &iov, 1, size); /* Save some cycles and don't copy the address if not needed */ msg.msg_name = addr ? (struct sockaddr *)&address : NULL; /* We assume all kernel code knows the size of sockaddr_storage */ msg.msg_namelen = 0; if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, size, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom Cc: stable@vger.kernel.org # v3.19 Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xmlNewTextReader(xmlParserInputBufferPtr input, const char *URI) { xmlTextReaderPtr ret; if (input == NULL) return(NULL); ret = xmlMalloc(sizeof(xmlTextReader)); if (ret == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlNewTextReader : malloc failed\n"); return(NULL); } memset(ret, 0, sizeof(xmlTextReader)); ret->doc = NULL; ret->entTab = NULL; ret->entMax = 0; ret->entNr = 0; ret->input = input; ret->buffer = xmlBufCreateSize(100); if (ret->buffer == NULL) { xmlFree(ret); xmlGenericError(xmlGenericErrorContext, "xmlNewTextReader : malloc failed\n"); return(NULL); } ret->sax = (xmlSAXHandler *) xmlMalloc(sizeof(xmlSAXHandler)); if (ret->sax == NULL) { xmlBufFree(ret->buffer); xmlFree(ret); xmlGenericError(xmlGenericErrorContext, "xmlNewTextReader : malloc failed\n"); return(NULL); } xmlSAXVersion(ret->sax, 2); ret->startElement = ret->sax->startElement; ret->sax->startElement = xmlTextReaderStartElement; ret->endElement = ret->sax->endElement; ret->sax->endElement = xmlTextReaderEndElement; #ifdef LIBXML_SAX1_ENABLED if (ret->sax->initialized == XML_SAX2_MAGIC) { #endif /* LIBXML_SAX1_ENABLED */ ret->startElementNs = ret->sax->startElementNs; ret->sax->startElementNs = xmlTextReaderStartElementNs; ret->endElementNs = ret->sax->endElementNs; ret->sax->endElementNs = xmlTextReaderEndElementNs; #ifdef LIBXML_SAX1_ENABLED } else { ret->startElementNs = NULL; ret->endElementNs = NULL; } #endif /* LIBXML_SAX1_ENABLED */ ret->characters = ret->sax->characters; ret->sax->characters = xmlTextReaderCharacters; ret->sax->ignorableWhitespace = xmlTextReaderCharacters; ret->cdataBlock = ret->sax->cdataBlock; ret->sax->cdataBlock = xmlTextReaderCDataBlock; ret->mode = XML_TEXTREADER_MODE_INITIAL; ret->node = NULL; ret->curnode = NULL; if (xmlBufUse(ret->input->buffer) < 4) { xmlParserInputBufferRead(input, 4); } if (xmlBufUse(ret->input->buffer) >= 4) { ret->ctxt = xmlCreatePushParserCtxt(ret->sax, NULL, (const char *) xmlBufContent(ret->input->buffer), 4, URI); ret->base = 0; ret->cur = 4; } else { ret->ctxt = xmlCreatePushParserCtxt(ret->sax, NULL, NULL, 0, URI); ret->base = 0; ret->cur = 0; } if (ret->ctxt == NULL) { xmlGenericError(xmlGenericErrorContext, "xmlNewTextReader : malloc failed\n"); xmlBufFree(ret->buffer); xmlFree(ret->sax); xmlFree(ret); return(NULL); } ret->ctxt->parseMode = XML_PARSE_READER; ret->ctxt->_private = ret; ret->ctxt->linenumbers = 1; ret->ctxt->dictNames = 1; ret->allocs = XML_TEXTREADER_CTXT; /* * use the parser dictionnary to allocate all elements and attributes names */ ret->ctxt->docdict = 1; ret->dict = ret->ctxt->dict; #ifdef LIBXML_XINCLUDE_ENABLED ret->xinclude = 0; #endif #ifdef LIBXML_PATTERN_ENABLED ret->patternMax = 0; ret->patternTab = NULL; #endif return(ret); } ; 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: static int SavePackageDescriptionToDebugDump(const char *dump_dir_name) { struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0); if (!dd) return 1; char *analyzer = dd_load_text(dd, FILENAME_ANALYZER); if (!strcmp(analyzer, "Kerneloops")) { dd_save_text(dd, FILENAME_PACKAGE, "kernel"); dd_save_text(dd, FILENAME_COMPONENT, "kernel"); dd_close(dd); free(analyzer); return 0; } free(analyzer); char *cmdline = NULL; char *executable = NULL; char *rootdir = NULL; char *package_short_name = NULL; struct pkg_envra *pkg_name = NULL; char *component = NULL; int error = 1; /* note: "goto ret" statements below free all the above variables, * but they don't dd_close(dd) */ cmdline = dd_load_text_ext(dd, FILENAME_CMDLINE, DD_FAIL_QUIETLY_ENOENT); executable = dd_load_text(dd, FILENAME_EXECUTABLE); rootdir = dd_load_text_ext(dd, FILENAME_ROOTDIR, DD_FAIL_QUIETLY_ENOENT | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE); /* Close dd while we query package database. It can take some time, * don't want to keep dd locked longer than necessary */ dd_close(dd); if (is_path_blacklisted(executable)) { log("Blacklisted executable '%s'", executable); goto ret; /* return 1 (failure) */ } pkg_name = rpm_get_package_nvr(executable, rootdir); if (!pkg_name) { if (settings_bProcessUnpackaged) { log_info("Crash in unpackaged executable '%s', " "proceeding without packaging information", executable); goto ret0; /* no error */ } log("Executable '%s' doesn't belong to any package" " and ProcessUnpackaged is set to 'no'", executable ); goto ret; /* return 1 (failure) */ } /* Check well-known interpreter names */ const char *basename = strrchr(executable, '/'); if (basename) basename++; else basename = executable; /* if basename is known interpreter, we want to blame the running script * not the interpreter */ if (g_list_find_custom(settings_Interpreters, basename, (GCompareFunc)g_strcmp0)) { struct pkg_envra *script_pkg = get_script_name(cmdline, &executable); /* executable may have changed, check it again */ if (is_path_blacklisted(executable)) { log("Blacklisted executable '%s'", executable); goto ret; /* return 1 (failure) */ } if (!script_pkg) { /* Script name is not absolute, or it doesn't * belong to any installed package. */ if (!settings_bProcessUnpackaged) { log("Interpreter crashed, but no packaged script detected: '%s'", cmdline); goto ret; /* return 1 (failure) */ } /* Unpackaged script, but the settings says we want to keep it. * BZ plugin wont allow to report this anyway, because component * is missing, so there is no reason to mark it as not_reportable. * Someone might want to use abrt to report it using ftp. */ goto ret0; } free_pkg_envra(pkg_name); pkg_name = script_pkg; } package_short_name = xasprintf("%s", pkg_name->p_name); log_info("Package:'%s' short:'%s'", pkg_name->p_nvr, package_short_name); if (g_list_find_custom(settings_setBlackListedPkgs, package_short_name, (GCompareFunc)g_strcmp0)) { log("Blacklisted package '%s'", package_short_name); goto ret; /* return 1 (failure) */ } if (settings_bOpenGPGCheck) { if (!rpm_chk_fingerprint(package_short_name)) { log("Package '%s' isn't signed with proper key", package_short_name); goto ret; /* return 1 (failure) */ } /* We used to also check the integrity of the executable here: * if (!CheckHash(package_short_name.c_str(), executable)) BOOM(); * Checking the MD5 sum requires to run prelink to "un-prelink" the * binaries - this is considered potential security risk so we don't * do it now, until we find some non-intrusive way. */ } component = rpm_get_component(executable, rootdir); dd = dd_opendir(dump_dir_name, /*flags:*/ 0); if (!dd) goto ret; /* return 1 (failure) */ if (pkg_name) { dd_save_text(dd, FILENAME_PACKAGE, pkg_name->p_nvr); dd_save_text(dd, FILENAME_PKG_EPOCH, pkg_name->p_epoch); dd_save_text(dd, FILENAME_PKG_NAME, pkg_name->p_name); dd_save_text(dd, FILENAME_PKG_VERSION, pkg_name->p_version); dd_save_text(dd, FILENAME_PKG_RELEASE, pkg_name->p_release); dd_save_text(dd, FILENAME_PKG_ARCH, pkg_name->p_arch); } if (component) dd_save_text(dd, FILENAME_COMPONENT, component); dd_close(dd); ret0: error = 0; ret: free(cmdline); free(executable); free(rootdir); free(package_short_name); free_pkg_envra(pkg_name); free(component); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59'], 'message': 'a-a-save-package-data: turn off reading data from root directories Making copies of files from arbitrary root directories is not secure. Related: #1211835 Signed-off-by: Jakub Filak <jfilak@redhat.com>'</s>