text
stringlengths
486
228k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: R_API bool r_io_bank_map_add_top(RIO *io, const ut32 bankid, const ut32 mapid) { RIOBank *bank = r_io_bank_get (io, bankid); RIOMap *map = r_io_map_get (io, mapid); r_return_val_if_fail (io && bank && map, false); RIOMapRef *mapref = _mapref_from_map (map); if (!mapref) { return false; } RIOSubMap *sm = r_io_submap_new (io, mapref); if (!sm) { free (mapref); return false; } RRBNode *entry = _find_entry_submap_node (bank, sm); if (!entry) { // no intersection with any submap, so just insert if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; } bank->last_used = NULL; RIOSubMap *bd = (RIOSubMap *)entry->data; if (r_io_submap_to (bd) == r_io_submap_to (sm) && r_io_submap_from (bd) >= r_io_submap_from (sm)) { // _find_entry_submap_node guarantees, that there is no submap // prior to bd in the range of sm, so instead of deleting and inserting // we can just memcpy memcpy (bd, sm, sizeof (RIOSubMap)); free (sm); r_list_append (bank->maprefs, mapref); return true; } if (r_io_submap_from (bd) < r_io_submap_from (sm) && r_io_submap_to (sm) < r_io_submap_to (bd)) { // split bd into 2 maps => bd and bdsm RIOSubMap *bdsm = R_NEWCOPY (RIOSubMap, bd); if (!bdsm) { free (sm); free (mapref); return false; } r_io_submap_set_from (bdsm, r_io_submap_to (sm) + 1); r_io_submap_set_to (bd, r_io_submap_from (sm) - 1); // TODO: insert and check return value, before adjusting sm size if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (bdsm); free (mapref); return false; } if (!r_crbtree_insert (bank->submaps, bdsm, _find_sm_by_from_vaddr_cb, NULL)) { r_crbtree_delete (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL); free (sm); free (bdsm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; } // guaranteed intersection if (r_io_submap_from (bd) < r_io_submap_from (sm)) { r_io_submap_set_to (bd, r_io_submap_from (sm) - 1); entry = r_rbnode_next (entry); } ut64 smto = r_io_submap_to (sm); while (entry && r_io_submap_to (((RIOSubMap *)entry->data)) <= smto) { //delete all submaps that are completly included in sm RRBNode *next = r_rbnode_next (entry); // this can be optimized, there is no need to do search here // XXX this is a workaround to avoid an UAF in Reproducer: iobank-crash void *smfree = bank->submaps->free; bank->submaps->free = NULL; bool a = r_crbtree_delete (bank->submaps, entry->data, _find_sm_by_from_vaddr_cb, NULL); bank->submaps->free = smfree; if (!a) { entry = NULL; break; } entry = next; } if (entry && r_io_submap_from (((RIOSubMap *)entry->data)) <= r_io_submap_to (sm)) { bd = (RIOSubMap *)entry->data; r_io_submap_set_from (bd, r_io_submap_to (sm) + 1); } if (!r_crbtree_insert (bank->submaps, sm, _find_sm_by_from_vaddr_cb, NULL)) { free (sm); free (mapref); return false; } r_list_append (bank->maprefs, mapref); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Properly fix the UAF in r_io_bank_map_add_top ##crash * Associated with the CVE-2022-0559 * Reported by alkyne Choi via huntr.dev'</s>
<s>[INST] Given the following code containing errors, provide 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 filter_frame(AVFilterLink *inlink, AVFrame *frame) { AVFilterContext *ctx = inlink->dst; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); uint32_t plane_checksum[4] = {0}, checksum = 0; int i, plane, vsub = desc->log2_chroma_h; for (plane = 0; plane < 4 && frame->data[plane]; plane++) { int64_t linesize = av_image_get_linesize(frame->format, frame->width, plane); uint8_t *data = frame->data[plane]; int h = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(inlink->h, vsub) : inlink->h; if (linesize < 0) return linesize; for (i = 0; i < h; i++) { plane_checksum[plane] = av_adler32_update(plane_checksum[plane], data, linesize); checksum = av_adler32_update(checksum, data, linesize); data += frame->linesize[plane]; } } av_log(ctx, AV_LOG_INFO, "n:%"PRId64" pts:%s pts_time:%s pos:%"PRId64" " "fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c " "checksum:%08X plane_checksum:[%08X", inlink->frame_count, av_ts2str(frame->pts), av_ts2timestr(frame->pts, &inlink->time_base), av_frame_get_pkt_pos(frame), desc->name, frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den, frame->width, frame->height, !frame->interlaced_frame ? 'P' : /* Progressive */ frame->top_field_first ? 'T' : 'B', /* Top / Bottom */ frame->key_frame, av_get_picture_type_char(frame->pict_type), checksum, plane_checksum[0]); for (plane = 1; plane < 4 && frame->data[plane]; plane++) av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]); av_log(ctx, AV_LOG_INFO, "]\n"); return ff_filter_frame(inlink->dst->outputs[0], frame); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <michaelni@gmx.at>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parseNormalModeParameters(IsoPresentation* self, uint8_t* buffer, int totalLength, int bufPos) { int endPos = bufPos + totalLength; self->calledPresentationSelector.size = 0; self->callingPresentationSelector.size = 0; bool hasUserData = false; while (bufPos < endPos) { uint8_t tag = buffer[bufPos++]; int len; if (bufPos == endPos) { if (DEBUG_PRES) printf("PRES: invalid message\n"); return -1; } bufPos = BerDecoder_decodeLength(buffer, &len, bufPos, endPos); if (bufPos < 0) { if (DEBUG_PRES) printf("PRES: wrong parameter length\n"); return -1; } switch (tag) { case 0x81: /* calling-presentation-selector */ if (len > 16) { if (DEBUG_PRES) printf("PRES: calling-presentation-sel too large\n"); } else { self->callingPresentationSelector.size = len; int i; for (i = 0; i < len; i++) self->callingPresentationSelector.value[i] = buffer[bufPos + i]; } bufPos += len; break; case 0x82: /* called-presentation-selector */ if (len > 16) { if (DEBUG_PRES) printf("PRES: called-presentation-sel too large\n"); } else { self->calledPresentationSelector.size = len; int i; for (i = 0; i < len; i++) self->calledPresentationSelector.value[i] = buffer[bufPos + i]; } bufPos += len; break; case 0x83: /* responding-presentation-selector */ if (len > 16) { if (DEBUG_PRES) printf("PRES: responding-presentation-sel too large\n"); } bufPos += len; break; case 0xa4: /* presentation-context-definition list */ if (DEBUG_PRES) printf("PRES: pcd list\n"); bufPos = parsePresentationContextDefinitionList(self, buffer, len, bufPos); break; case 0xa5: /* context-definition-result-list */ bufPos += len; break; case 0x61: /* user data */ if (DEBUG_PRES) printf("PRES: user-data\n"); bufPos = parseFullyEncodedData(self, buffer, len, bufPos); if (bufPos < 0) return -1; if (self->nextPayload.size > 0) hasUserData = true; break; case 0x00: /* indefinite length end tag -> ignore */ break; default: if (DEBUG_PRES) printf("PRES: unknown tag in normal-mode\n"); bufPos += len; break; } } if (hasUserData == false) { if (DEBUG_PRES) printf("PRES: user-data is missing\n"); return -1; } return bufPos; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': '- fixed - Bug in presentation layer parser can cause infinite loop (LIB61850-302)'</s>
<s>[INST] Given the following code containing errors, provide 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 RList *relocs(RBinFile *arch) { struct r_bin_bflt_obj *obj = (struct r_bin_bflt_obj*)arch->o->bin_obj; RList *list = r_list_newf ((RListFree)free); int i, len, n_got, amount; if (!list || !obj) { r_list_free (list); return NULL; } if (obj->hdr->flags & FLAT_FLAG_GOTPIC) { n_got = get_ngot_entries (obj); if (n_got) { amount = n_got * sizeof (ut32); if (amount < n_got || amount > UT32_MAX) { goto out_error; } struct reloc_struct_t *got_table = calloc (1, n_got * sizeof (ut32)); if (got_table) { ut32 offset = 0; for (i = 0; i < n_got ; offset += 4, i++) { ut32 got_entry; if (obj->hdr->data_start + offset + 4 > obj->size || obj->hdr->data_start + offset + 4 < offset) { break; } len = r_buf_read_at (obj->b, obj->hdr->data_start + offset, (ut8 *)&got_entry, sizeof (ut32)); if (!VALID_GOT_ENTRY (got_entry) || len != sizeof (ut32)) { break; } got_table[i].addr_to_patch = got_entry; got_table[i].data_offset = got_entry + BFLT_HDR_SIZE; } obj->n_got = n_got; obj->got_table = got_table; } } } if (obj->hdr->reloc_count > 0) { int n_reloc = obj->hdr->reloc_count; amount = n_reloc * sizeof (struct reloc_struct_t); if (amount < n_reloc || amount > UT32_MAX) { goto out_error; } struct reloc_struct_t *reloc_table = calloc (1, amount + 1); if (!reloc_table) { goto out_error; } amount = n_reloc * sizeof (ut32); if (amount < n_reloc || amount > UT32_MAX) { free (reloc_table); goto out_error; } ut32 *reloc_pointer_table = calloc (1, amount + 1); if (!reloc_pointer_table) { free (reloc_table); goto out_error; } if (obj->hdr->reloc_start + amount > obj->size || obj->hdr->reloc_start + amount < amount) { free (reloc_table); free (reloc_pointer_table); goto out_error; } len = r_buf_read_at (obj->b, obj->hdr->reloc_start, (ut8 *)reloc_pointer_table, amount); if (len != amount) { free (reloc_table); free (reloc_pointer_table); goto out_error; } for (i = 0; i < obj->hdr->reloc_count; i++) { //XXX it doesn't take endian as consideration when swapping ut32 reloc_offset = r_swap_ut32 (reloc_pointer_table[i]) + BFLT_HDR_SIZE; if (reloc_offset < obj->hdr->bss_end && reloc_offset < obj->size) { ut32 reloc_fixed, reloc_data_offset; if (reloc_offset + sizeof (ut32) > obj->size || reloc_offset + sizeof (ut32) < reloc_offset) { free (reloc_table); free (reloc_pointer_table); goto out_error; } len = r_buf_read_at (obj->b, reloc_offset, (ut8 *)&reloc_fixed, sizeof (ut32)); if (len != sizeof (ut32)) { eprintf ("problem while reading relocation entries\n"); free (reloc_table); free (reloc_pointer_table); goto out_error; } reloc_data_offset = r_swap_ut32 (reloc_fixed) + BFLT_HDR_SIZE; reloc_table[i].addr_to_patch = reloc_offset; reloc_table[i].data_offset = reloc_data_offset; RBinReloc *reloc = R_NEW0 (RBinReloc); if (reloc) { reloc->type = R_BIN_RELOC_32; reloc->paddr = reloc_table[i].addr_to_patch; reloc->vaddr = reloc->paddr; r_list_append (list, reloc); } } } free (reloc_pointer_table); obj->reloc_table = reloc_table; } return list; out_error: r_list_free (list); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fix #6829 oob write because of using wrong struct'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: interp_reply(netdissect_options *ndo, const struct sunrpc_msg *rp, uint32_t proc, uint32_t vers, int length) { register const uint32_t *dp; register int v3; int er; v3 = (vers == NFS_VER3); if (!v3 && proc < NFS_NPROCS) proc = nfsv3_procid[proc]; ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc))); switch (proc) { case NFSPROC_GETATTR: dp = parserep(ndo, rp, length); if (dp != NULL && parseattrstat(ndo, dp, !ndo->ndo_qflag, v3) != 0) return; break; case NFSPROC_SETATTR: if (!(dp = parserep(ndo, rp, length))) return; if (v3) { if (parsewccres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parseattrstat(ndo, dp, !ndo->ndo_qflag, 0) != 0) return; } break; case NFSPROC_LOOKUP: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (er) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " post dattr:")); dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag); } } else { if (!(dp = parsefh(ndo, dp, v3))) break; if ((dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)) && ndo->ndo_vflag > 1) { ND_PRINT((ndo, " post dattr:")); dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag); } } if (dp) return; } else { if (parsediropres(ndo, dp) != 0) return; } break; case NFSPROC_ACCESS: if (!(dp = parserep(ndo, rp, length))) break; if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) ND_PRINT((ndo, " attr:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; if (!er) ND_PRINT((ndo, " c %04x", EXTRACT_32BITS(&dp[0]))); return; case NFSPROC_READLINK: dp = parserep(ndo, rp, length); if (dp != NULL && parselinkres(ndo, dp, v3) != 0) return; break; case NFSPROC_READ: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; if (er) return; if (ndo->ndo_vflag) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0]))); if (EXTRACT_32BITS(&dp[1])) ND_PRINT((ndo, " EOF")); } return; } else { if (parseattrstat(ndo, dp, ndo->ndo_vflag, 0) != 0) return; } break; case NFSPROC_WRITE: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; if (er) return; if (ndo->ndo_vflag) { ND_TCHECK(dp[0]); ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0]))); if (ndo->ndo_vflag > 1) { ND_TCHECK(dp[1]); ND_PRINT((ndo, " <%s>", tok2str(nfsv3_writemodes, NULL, EXTRACT_32BITS(&dp[1])))); } return; } } else { if (parseattrstat(ndo, dp, ndo->ndo_vflag, v3) != 0) return; } break; case NFSPROC_CREATE: case NFSPROC_MKDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; } else { if (parsediropres(ndo, dp) != 0) return; } break; case NFSPROC_SYMLINK: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_MKNOD: if (!(dp = parserep(ndo, rp, length))) break; if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL) return; break; case NFSPROC_REMOVE: case NFSPROC_RMDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsewccres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_RENAME: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) { ND_PRINT((ndo, " from:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; ND_PRINT((ndo, " to:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; } return; } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_LINK: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (!(dp = parsestatus(ndo, dp, &er))) break; if (ndo->ndo_vflag) { ND_PRINT((ndo, " file POST:")); if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag))) break; ND_PRINT((ndo, " dir:")); if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag))) break; return; } } else { if (parsestatus(ndo, dp, &er) != NULL) return; } break; case NFSPROC_READDIR: if (!(dp = parserep(ndo, rp, length))) break; if (v3) { if (parsev3rddirres(ndo, dp, ndo->ndo_vflag)) return; } else { if (parserddires(ndo, dp) != 0) return; } break; case NFSPROC_READDIRPLUS: if (!(dp = parserep(ndo, rp, length))) break; if (parsev3rddirres(ndo, dp, ndo->ndo_vflag)) return; break; case NFSPROC_FSSTAT: dp = parserep(ndo, rp, length); if (dp != NULL && parsestatfs(ndo, dp, v3) != 0) return; break; case NFSPROC_FSINFO: dp = parserep(ndo, rp, length); if (dp != NULL && parsefsinfo(ndo, dp) != 0) return; break; case NFSPROC_PATHCONF: dp = parserep(ndo, rp, length); if (dp != NULL && parsepathconf(ndo, dp) != 0) return; break; case NFSPROC_COMMIT: dp = parserep(ndo, rp, length); if (dp != NULL && parsewccres(ndo, dp, ndo->ndo_vflag) != 0) return; break; default: return; } trunc: if (!nfserr) ND_PRINT((ndo, "%s", tstr)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-12898/NFS: Fix bounds checking. Fix the bounds checking for the NFSv3 WRITE procedure to check whether the length of the opaque data being written is present in the captured data, not just whether the byte count is present in the captured data. furthest forward in the packet, not the item before it. (This also lets us eliminate the check for the "stable" argument being present in the captured data; rewrite the code to print that to make it a bit clearer.) Check that the entire ar_stat field is present in the capture. Note that parse_wcc_attr() is called after we've already checked whether the wcc_data is present. Check before fetching the "access" part of the NFSv3 ACCESS results. This fixes a buffer over-read discovered by Kamil Frankowicz. Include a test for the "check before fetching the "access" part..." fix, using the capture supplied by the reporter(s).'</s>
<s>[INST] Given the following code containing errors, provide 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 bad_flp_intr(void) { int err_count; if (probing) { drive_state[current_drive].probed_format++; if (!next_valid_format(current_drive)) return; } err_count = ++(*errors); INFBOUND(write_errors[current_drive].badness, err_count); if (err_count > drive_params[current_drive].max_errors.abort) cont->done(0); if (err_count > drive_params[current_drive].max_errors.reset) fdc_state[current_fdc].reset = 1; else if (err_count > drive_params[current_drive].max_errors.recal) drive_state[current_drive].track = NEED_2_RECAL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'floppy: use a statically allocated error counter Interrupt handler bad_flp_intr() may cause a UAF on the recently freed request just to increment the error count. There's no point keeping that one in the request anyway, and since the interrupt handler uses a static pointer to the error which cannot be kept in sync with the pending request, better make it use a static error counter that's reset for each new request. This reset now happens when entering redo_fd_request() for a new request via set_next_request(). One initial concern about a single error counter was that errors on one floppy drive could be reported on another one, but this problem is not real given that the driver uses a single drive at a time, as that PC-compatible controllers also have this limitation by using shared signals. As such the error count is always for the "current" drive. Reported-by: Minh Yuan <yuanmingbuaa@gmail.com> Suggested-by: Linus Torvalds <torvalds@linuxfoundation.org> Tested-by: Denis Efremov <efremov@linux.com> Signed-off-by: Willy Tarreau <w@1wt.eu> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p, StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq) { if (ssn == NULL) return -1; SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ? "toclient":"toserver"); /* RST */ if (p->tcph->th_flags & TH_RST) { if (!StreamTcpValidateRst(ssn, p)) return -1; if (PKT_IS_TOSERVER(p)) { if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) && SEQ_EQ(TCP_GET_WINDOW(p), 0) && SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1))) { SCLogDebug("ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV"); ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV; StreamTcpPacketSetState(p, ssn, TCP_CLOSED); SCLogDebug("ssn %p: Reset received and state changed to " "TCP_CLOSED", ssn); } } else { ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV; SCLogDebug("ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV"); StreamTcpPacketSetState(p, ssn, TCP_CLOSED); SCLogDebug("ssn %p: Reset received and state changed to " "TCP_CLOSED", ssn); } /* FIN */ } else if (p->tcph->th_flags & TH_FIN) { /** \todo */ /* SYN/ACK */ } else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) { if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn); /* Check if the SYN/ACK packet ack's the earlier * received SYN packet. */ if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) { StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK); SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32"" " != %" PRIu32 " from stream", ssn, TCP_GET_ACK(p), ssn->server.isn + 1); return -1; } /* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN * packet. */ if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) { StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN); SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32"" " != %" PRIu32 " from *first* SYN pkt", ssn, TCP_GET_SEQ(p), ssn->client.isn); return -1; } /* update state */ StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV); SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn); /* sequence number & window */ ssn->client.isn = TCP_GET_SEQ(p); STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn); ssn->client.next_seq = ssn->client.isn + 1; ssn->server.window = TCP_GET_WINDOW(p); SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn, ssn->client.window); /* Set the timestamp values used to validate the timestamp of * received packets. */ if ((TCP_HAS_TS(p)) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP)) { ssn->client.last_ts = TCP_GET_TSVAL(p); SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" " "ssn->server.last_ts %" PRIu32"", ssn, ssn->client.last_ts, ssn->server.last_ts); ssn->flags |= STREAMTCP_FLAG_TIMESTAMP; ssn->client.last_pkt_ts = p->ts.tv_sec; if (ssn->client.last_ts == 0) ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP; } else { ssn->server.last_ts = 0; ssn->client.last_ts = 0; ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP; } ssn->server.last_ack = TCP_GET_ACK(p); ssn->client.last_ack = ssn->client.isn + 1; /** check for the presense of the ws ptr to determine if we * support wscale at all */ if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) && (TCP_HAS_WSCALE(p))) { ssn->server.wscale = TCP_GET_WSCALE(p); } else { ssn->server.wscale = 0; } if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) && TCP_GET_SACKOK(p) == 1) { ssn->flags |= STREAMTCP_FLAG_SACKOK; SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn); } ssn->client.next_win = ssn->client.last_ack + ssn->client.window; ssn->server.next_win = ssn->server.last_ack + ssn->server.window; SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn, ssn->client.next_win); SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn, ssn->server.next_win); SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", " "ssn->client.next_seq %" PRIu32 ", " "ssn->client.last_ack %" PRIu32 " " "(ssn->server.last_ack %" PRIu32 ")", ssn, ssn->client.isn, ssn->client.next_seq, ssn->client.last_ack, ssn->server.last_ack); /* done here */ return 0; } if (PKT_IS_TOSERVER(p)) { StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION); SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn); return -1; } if (!(TCP_HAS_TFO(p) || (ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN))) { /* Check if the SYN/ACK packet ack's the earlier * received SYN packet. */ if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) { StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK); SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != " "%" PRIu32 " from stream", ssn, TCP_GET_ACK(p), ssn->client.isn + 1); return -1; } } else { if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.next_seq))) { StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK); SCLogDebug("ssn %p: (TFO) ACK mismatch, packet ACK %" PRIu32 " != " "%" PRIu32 " from stream", ssn, TCP_GET_ACK(p), ssn->client.next_seq); return -1; } SCLogDebug("ssn %p: (TFO) ACK match, packet ACK %" PRIu32 " == " "%" PRIu32 " from stream", ssn, TCP_GET_ACK(p), ssn->client.next_seq); ssn->flags |= STREAMTCP_FLAG_TCP_FAST_OPEN; StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED); } StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL); } else if (p->tcph->th_flags & TH_SYN) { SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn); if (ssn->flags & STREAMTCP_FLAG_4WHS) { SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of " "4WHS SYN", ssn); } if (PKT_IS_TOCLIENT(p)) { /** a SYN only packet in the opposite direction could be: * http://www.breakingpointsystems.com/community/blog/tcp- * portals-the-three-way-handshake-is-a-lie * * \todo improve resetting the session */ /* indicate that we're dealing with 4WHS here */ ssn->flags |= STREAMTCP_FLAG_4WHS; SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn); /* set the sequence numbers and window for server * We leave the ssn->client.isn in place as we will * check the SYN/ACK pkt with that. */ ssn->server.isn = TCP_GET_SEQ(p); STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn); ssn->server.next_seq = ssn->server.isn + 1; /* Set the stream timestamp value, if packet has timestamp * option enabled. */ if (TCP_HAS_TS(p)) { ssn->server.last_ts = TCP_GET_TSVAL(p); SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts); if (ssn->server.last_ts == 0) ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP; ssn->server.last_pkt_ts = p->ts.tv_sec; ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP; } ssn->server.window = TCP_GET_WINDOW(p); if (TCP_HAS_WSCALE(p)) { ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE; ssn->server.wscale = TCP_GET_WSCALE(p); } else { ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE; ssn->server.wscale = 0; } if (TCP_GET_SACKOK(p) == 1) { ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK; } else { ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK; } SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", " "ssn->server.next_seq %" PRIu32 ", " "ssn->server.last_ack %"PRIu32"", ssn, ssn->server.isn, ssn->server.next_seq, ssn->server.last_ack); SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", " "ssn->client.next_seq %" PRIu32 ", " "ssn->client.last_ack %"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq, ssn->client.last_ack); } /** \todo check if it's correct or set event */ } else if (p->tcph->th_flags & TH_ACK) { /* Handle the asynchronous stream, when we receive a SYN packet and now istead of receving a SYN/ACK we receive a ACK from the same host, which sent the SYN, this suggests the ASNYC streams.*/ if (stream_config.async_oneside == FALSE) return 0; /* we are in AYNC (one side) mode now. */ /* one side async means we won't see a SYN/ACK, so we can * only check the SYN. */ if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) { StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ); SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != " "%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p), ssn->client.next_seq); return -1; } ssn->flags |= STREAMTCP_FLAG_ASYNC; StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED); SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn); ssn->client.window = TCP_GET_WINDOW(p); ssn->client.last_ack = TCP_GET_SEQ(p); ssn->client.next_win = ssn->client.last_ack + ssn->client.window; /* Set the server side parameters */ ssn->server.isn = TCP_GET_ACK(p) - 1; STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn); ssn->server.next_seq = ssn->server.isn + 1; ssn->server.last_ack = ssn->server.next_seq; ssn->server.next_win = ssn->server.last_ack; SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ" " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " "ssn->client.next_seq %" PRIu32 "" ,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_seq); /* if SYN had wscale, assume it to be supported. Otherwise * we know it not to be supported. */ if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) { ssn->client.wscale = TCP_WSCALE_MAX; } /* Set the timestamp values used to validate the timestamp of * received packets.*/ if (TCP_HAS_TS(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP)) { ssn->flags |= STREAMTCP_FLAG_TIMESTAMP; ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP; ssn->client.last_pkt_ts = p->ts.tv_sec; } else { ssn->client.last_ts = 0; ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP; } if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) { ssn->flags |= STREAMTCP_FLAG_SACKOK; } StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq); } else { SCLogDebug("ssn %p: default case", ssn); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-74'], 'message': 'stream: fix SYN_SENT RST/FIN injection RST injection during the SYN_SENT state could trick Suricata into marking a session as CLOSED. The way this was done is: using invalid TSECR value in RST+ACK packet. The ACK was needed to force Linux into considering the TSECR value and compare it to the TSVAL from the SYN packet. The second works only against Windows. The client would not use a TSVAL but the RST packet would. Windows will reject this, but Suricata considered the RST valid and triggered the CLOSED logic. This patch addresses both. When the SYN packet used timestamp support the timestamp of incoming packet is validated. Otherwise, packet responding should not have a timestamp. Bug #3286 Reported-by: Nicolas Adba'</s>
<s>[INST] Given the following code containing errors, provide 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 initiate_stratum(struct pool *pool) { char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid; json_t *val = NULL, *res_val, *err_val; bool ret = false, recvd = false; json_error_t err; int n2size; if (!setup_stratum_curl(pool)) goto out; resend: if (pool->sessionid) sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\"%s\"]}", swork_id++, pool->sessionid); else sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++); if (!__stratum_send(pool, s, strlen(s))) { applog(LOG_DEBUG, "Failed to send s in initiate_stratum"); goto out; } if (!socket_full(pool, true)) { applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum"); goto out; } sret = recv_line(pool); if (!sret) goto out; recvd = true; val = JSON_LOADS(sret, &err); free(sret); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); goto out; } res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val || json_is_null(res_val) || (err_val && !json_is_null(err_val))) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC decode failed: %s", ss); free(ss); goto out; } sessionid = json_array_string(json_array_get(res_val, 0), 1); if (!sessionid) { applog(LOG_INFO, "Failed to get sessionid in initiate_stratum"); goto out; } nonce1 = json_array_string(res_val, 1); if (!nonce1) { applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum"); free(sessionid); goto out; } n2size = json_integer_value(json_array_get(res_val, 2)); if (!n2size) { applog(LOG_INFO, "Failed to get n2size in initiate_stratum"); free(sessionid); free(nonce1); goto out; } mutex_lock(&pool->pool_lock); pool->sessionid = sessionid; free(pool->nonce1); pool->nonce1 = nonce1; pool->n1_len = strlen(nonce1) / 2; pool->n2size = n2size; mutex_unlock(&pool->pool_lock); applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid); ret = true; out: if (val) json_decref(val); if (ret) { if (!pool->stratum_url) pool->stratum_url = pool->sockaddr_url; pool->stratum_active = true; pool->swork.diff = 1; if (opt_protocol) { applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d", pool->pool_no, pool->nonce1, pool->n2size); } } else { if (recvd && pool->sessionid) { /* Reset the sessionid used for stratum resuming in case the pool * does not support it, or does not know how to respond to the * presence of the sessionid parameter. */ mutex_lock(&pool->pool_lock); free(pool->sessionid); free(pool->nonce1); pool->sessionid = pool->nonce1 = NULL; mutex_unlock(&pool->pool_lock); applog(LOG_DEBUG, "Failed to resume stratum, trying afresh"); goto resend; } applog(LOG_DEBUG, "Initiate stratum failed"); if (pool->sock != INVSOCK) { shutdown(pool->sock, SHUT_RDWR); pool->sock = INVSOCK; } } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Bugfix: initiate_stratum: Ensure extranonce2 size is not negative (which could lead to exploits later as too little memory gets allocated) Thanks to Mick Ayzenberg <mick@dejavusecurity.com> for finding this!'</s>
<s>[INST] Given the following code containing errors, provide 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 mobj *alloc_ta_mem(size_t size) { #ifdef CFG_PAGED_USER_TA return mobj_paged_alloc(size); #else struct mobj *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr); if (mobj) memset(mobj_get_va(mobj, 0), 0, size); return mobj; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'core: clear the entire TA area Previously we cleared (memset to zero) the size corresponding to code and data segments, however the allocation for the TA is made on the granularity of the memory pool, meaning that we did not clear all memory and because of that we could potentially leak code and data of a previous loaded TA. Fixes: OP-TEE-2018-0006: "Potential disclosure of previously loaded TA code and data" Signed-off-by: Joakim Bech <joakim.bech@linaro.org> Tested-by: Joakim Bech <joakim.bech@linaro.org> (QEMU v7, v8) Suggested-by: Jens Wiklander <jens.wiklander@linaro.org> Reviewed-by: Jens Wiklander <jens.wiklander@linaro.org> Reported-by: Riscure <inforequest@riscure.com> Reported-by: Alyssa Milburn <a.a.milburn@vu.nl> Acked-by: Etienne Carriere <etienne.carriere@linaro.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: isis_print_id(const uint8_t *cp, int id_len) { int i; static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")]; char *pos = id; for (i = 1; i <= SYSTEM_ID_LEN; i++) { snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++); pos += strlen(pos); if (i == 2 || i == 4) *pos++ = '.'; } if (id_len >= NODE_ID_LEN) { snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++); pos += strlen(pos); } if (id_len == LSP_ID_LEN) snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp); return (id); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'CVE-2017-13035/Properly handle IS-IS IDs shorter than a system ID (MAC address). Some of them are variable-length, with a field giving the total length, and therefore they can be shorter than 6 octets. If one is, don't run past the end. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent, uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto, PacketQueue *pq) { int ret; SCEnter(); /* get us a packet */ Packet *p = PacketGetFromQueueOrAlloc(); if (unlikely(p == NULL)) { SCReturnPtr(NULL, "Packet"); } /* copy packet and set lenght, proto */ PacketCopyData(p, pkt, len); p->recursion_level = parent->recursion_level + 1; p->ts.tv_sec = parent->ts.tv_sec; p->ts.tv_usec = parent->ts.tv_usec; p->datalink = DLT_RAW; p->tenant_id = parent->tenant_id; /* set the root ptr to the lowest layer */ if (parent->root != NULL) p->root = parent->root; else p->root = parent; /* tell new packet it's part of a tunnel */ SET_TUNNEL_PKT(p); ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), pq, proto); if (unlikely(ret != TM_ECODE_OK)) { /* Not a tunnel packet, just a pseudo packet */ p->root = NULL; UNSET_TUNNEL_PKT(p); TmqhOutputPacketpool(tv, p); SCReturnPtr(NULL, "Packet"); } /* tell parent packet it's part of a tunnel */ SET_TUNNEL_PKT(parent); /* increment tunnel packet refcnt in the root packet */ TUNNEL_INCR_PKT_TPR(p); /* disable payload (not packet) inspection on the parent, as the payload * is the packet we will now run through the system separately. We do * check it against the ip/port/other header checks though */ DecodeSetNoPayloadInspectionFlag(parent); SCReturnPtr(p, "Packet"); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'teredo: be stricter on what to consider valid teredo Invalid Teredo can lead to valid DNS traffic (or other UDP traffic) being misdetected as Teredo. This leads to false negatives in the UDP payload inspection. Make the teredo code only consider a packet teredo if the encapsulated data was decoded without any 'invalid' events being set. Bug #2736.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mountpoint_last(struct nameidata *nd, struct path *path) { int error = 0; struct dentry *dentry; struct dentry *dir = nd->path.dentry; /* If we're in rcuwalk, drop out of it to handle last component */ if (nd->flags & LOOKUP_RCU) { if (unlazy_walk(nd, NULL)) { error = -ECHILD; goto out; } } nd->flags &= ~LOOKUP_PARENT; if (unlikely(nd->last_type != LAST_NORM)) { error = handle_dots(nd, nd->last_type); if (error) goto out; dentry = dget(nd->path.dentry); goto done; } mutex_lock(&dir->d_inode->i_mutex); dentry = d_lookup(dir, &nd->last); if (!dentry) { /* * No cached dentry. Mounted dentries are pinned in the cache, * so that means that this dentry is probably a symlink or the * path doesn't actually point to a mounted dentry. */ dentry = d_alloc(dir, &nd->last); if (!dentry) { error = -ENOMEM; mutex_unlock(&dir->d_inode->i_mutex); goto out; } dentry = lookup_real(dir->d_inode, dentry, nd->flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) { mutex_unlock(&dir->d_inode->i_mutex); goto out; } } mutex_unlock(&dir->d_inode->i_mutex); done: if (!dentry->d_inode || d_is_negative(dentry)) { error = -ENOENT; dput(dentry); goto out; } path->dentry = dentry; path->mnt = mntget(nd->path.mnt); if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW)) return 1; follow_mount(path); error = 0; out: terminate_walk(nd); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'fs: umount on symlink leaks mnt count Currently umount on symlink blocks following umount: /vz is separate mount # ls /vz/ -al | grep test drwxr-xr-x. 2 root root 4096 Jul 19 01:14 testdir lrwxrwxrwx. 1 root root 11 Jul 19 01:16 testlink -> /vz/testdir # umount -l /vz/testlink umount: /vz/testlink: not mounted (expected) # lsof /vz # umount /vz umount: /vz: device is busy. (unexpected) In this case mountpoint_last() gets an extra refcount on path->mnt Signed-off-by: Vasily Averin <vvs@openvz.org> Acked-by: Ian Kent <raven@themaw.net> Acked-by: Jeff Layton <jlayton@primarydata.com> Cc: stable@vger.kernel.org Signed-off-by: Christoph Hellwig <hch@lst.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: const char *nghttp2_strerror(int error_code) { switch (error_code) { case 0: return "Success"; case NGHTTP2_ERR_INVALID_ARGUMENT: return "Invalid argument"; case NGHTTP2_ERR_BUFFER_ERROR: return "Out of buffer space"; case NGHTTP2_ERR_UNSUPPORTED_VERSION: return "Unsupported SPDY version"; case NGHTTP2_ERR_WOULDBLOCK: return "Operation would block"; case NGHTTP2_ERR_PROTO: return "Protocol error"; case NGHTTP2_ERR_INVALID_FRAME: return "Invalid frame octets"; case NGHTTP2_ERR_EOF: return "EOF"; case NGHTTP2_ERR_DEFERRED: return "Data transfer deferred"; case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE: return "No more Stream ID available"; case NGHTTP2_ERR_STREAM_CLOSED: return "Stream was already closed or invalid"; case NGHTTP2_ERR_STREAM_CLOSING: return "Stream is closing"; case NGHTTP2_ERR_STREAM_SHUT_WR: return "The transmission is not allowed for this stream"; case NGHTTP2_ERR_INVALID_STREAM_ID: return "Stream ID is invalid"; case NGHTTP2_ERR_INVALID_STREAM_STATE: return "Invalid stream state"; case NGHTTP2_ERR_DEFERRED_DATA_EXIST: return "Another DATA frame has already been deferred"; case NGHTTP2_ERR_START_STREAM_NOT_ALLOWED: return "request HEADERS is not allowed"; case NGHTTP2_ERR_GOAWAY_ALREADY_SENT: return "GOAWAY has already been sent"; case NGHTTP2_ERR_INVALID_HEADER_BLOCK: return "Invalid header block"; case NGHTTP2_ERR_INVALID_STATE: return "Invalid state"; case NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE: return "The user callback function failed due to the temporal error"; case NGHTTP2_ERR_FRAME_SIZE_ERROR: return "The length of the frame is invalid"; case NGHTTP2_ERR_HEADER_COMP: return "Header compression/decompression error"; case NGHTTP2_ERR_FLOW_CONTROL: return "Flow control error"; case NGHTTP2_ERR_INSUFF_BUFSIZE: return "Insufficient buffer size given to function"; case NGHTTP2_ERR_PAUSE: return "Callback was paused by the application"; case NGHTTP2_ERR_TOO_MANY_INFLIGHT_SETTINGS: return "Too many inflight SETTINGS"; case NGHTTP2_ERR_PUSH_DISABLED: return "Server push is disabled by peer"; case NGHTTP2_ERR_DATA_EXIST: return "DATA or HEADERS frame has already been submitted for the stream"; case NGHTTP2_ERR_SESSION_CLOSING: return "The current session is closing"; case NGHTTP2_ERR_HTTP_HEADER: return "Invalid HTTP header field was received"; case NGHTTP2_ERR_HTTP_MESSAGING: return "Violation in HTTP messaging rule"; case NGHTTP2_ERR_REFUSED_STREAM: return "Stream was refused"; case NGHTTP2_ERR_INTERNAL: return "Internal error"; case NGHTTP2_ERR_CANCEL: return "Cancel"; case NGHTTP2_ERR_SETTINGS_EXPECTED: return "When a local endpoint expects to receive SETTINGS frame, it " "receives an other type of frame"; case NGHTTP2_ERR_NOMEM: return "Out of memory"; case NGHTTP2_ERR_CALLBACK_FAILURE: return "The user callback function failed"; case NGHTTP2_ERR_BAD_CLIENT_MAGIC: return "Received bad client magic byte string"; case NGHTTP2_ERR_FLOODED: return "Flooding was detected in this HTTP/2 session, and it must be " "closed"; default: return "Unknown error code"; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-707'], 'message': 'Implement max settings option'</s>
<s>[INST] Given the following code containing errors, provide 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 streamGetEdgeID(stream *s, int first, int skip_tombstones, streamID *edge_id) { streamIterator si; int64_t numfields; streamIteratorStart(&si,s,NULL,NULL,!first); si.skip_tombstones = skip_tombstones; int found = streamIteratorGetID(&si,edge_id,&numfields); if (!found) { streamID min_id = {0, 0}, max_id = {UINT64_MAX, UINT64_MAX}; *edge_id = first ? max_id : min_id; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-401'], 'message': 'Fix memory leak in streamGetEdgeID (#10753) si is initialized by streamIteratorStart(), we should call streamIteratorStop() on it when done. regression introduced in #9127 (redis 7.0)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEE_Result syscall_authenc_update_aad(unsigned long state, const void *aad_data, size_t aad_data_len) { TEE_Result res; struct tee_cryp_state *cs; struct tee_ta_session *sess; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; res = tee_mmu_check_access_rights(to_user_ta_ctx(sess->ctx), TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t) aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_AE) return TEE_ERROR_BAD_STATE; res = crypto_authenc_update_aad(cs->ctx, cs->algo, cs->mode, aad_data, aad_data_len); if (res != TEE_SUCCESS) return res; return TEE_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-327'], 'message': 'cryp: prevent direct calls to update and final functions With inconsistent or malformed data it has been possible to call "update" and "final" crypto functions directly. Using a fuzzer tool [1] we have seen that this results in asserts, i.e., a crash that potentially could leak sensitive information. By setting the state (initialized) in the crypto context (i.e., the tee_cryp_state) at the end of all syscall_*_init functions and then add a check of the state at the beginning of all update and final functions, we prevent direct entrance to the "update" and "final" functions. [1] https://github.com/MartijnB/optee_fuzzer Fixes: OP-TEE-2019-0021 Signed-off-by: Joakim Bech <joakim.bech@linaro.org> Reported-by: Martijn Bogaard <bogaard@riscure.com> Acked-by: Jerome Forissier <jerome.forissier@linaro.org> Reviewed-by: Jens Wiklander <jens.wiklander@linaro.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void OAuth2Filter::finishFlow() { // We have fully completed the entire OAuth flow, whether through Authorization header or from // user redirection to the auth server. if (found_bearer_token_) { if (config_->forwardBearerToken()) { setBearerToken(*request_headers_, access_token_); } config_->stats().oauth_success_.inc(); decoder_callbacks_->continueDecoding(); return; } std::string token_payload; if (config_->forwardBearerToken()) { token_payload = absl::StrCat(host_, new_expires_, access_token_, id_token_, refresh_token_); } else { token_payload = absl::StrCat(host_, new_expires_); } auto& crypto_util = Envoy::Common::Crypto::UtilitySingleton::get(); auto token_secret = config_->tokenSecret(); std::vector<uint8_t> token_secret_vec(token_secret.begin(), token_secret.end()); const std::string pre_encoded_token = Hex::encode(crypto_util.getSha256Hmac(token_secret_vec, token_payload)); std::string encoded_token; absl::Base64Escape(pre_encoded_token, &encoded_token); // We use HTTP Only cookies for the HMAC and Expiry. const std::string cookie_tail = fmt::format(CookieTailFormatString, new_expires_); const std::string cookie_tail_http_only = fmt::format(CookieTailHttpOnlyFormatString, new_expires_); // At this point we have all of the pieces needed to authorize a user that did not originally // have a bearer access token. Now, we construct a redirect request to return the user to their // previous state and additionally set the OAuth cookies in browser. // The redirection should result in successfully passing this filter. Http::ResponseHeaderMapPtr response_headers{Http::createHeaderMap<Http::ResponseHeaderMapImpl>( {{Http::Headers::get().Status, std::to_string(enumToInt(Http::Code::Found))}})}; const CookieNames& cookie_names = config_->cookieNames(); response_headers->addReferenceKey( Http::Headers::get().SetCookie, absl::StrCat(cookie_names.oauth_hmac_, "=", encoded_token, cookie_tail_http_only)); response_headers->addReferenceKey( Http::Headers::get().SetCookie, absl::StrCat(cookie_names.oauth_expires_, "=", new_expires_, cookie_tail_http_only)); // If opted-in, we also create a new Bearer cookie for the authorization token provided by the // auth server. if (config_->forwardBearerToken()) { response_headers->addReferenceKey( Http::Headers::get().SetCookie, absl::StrCat(cookie_names.bearer_token_, "=", access_token_, cookie_tail)); if (id_token_ != EMPTY_STRING) { response_headers->addReferenceKey(Http::Headers::get().SetCookie, absl::StrCat("IdToken=", id_token_, cookie_tail)); } if (refresh_token_ != EMPTY_STRING) { response_headers->addReferenceKey(Http::Headers::get().SetCookie, absl::StrCat("RefreshToken=", refresh_token_, cookie_tail)); } } response_headers->setLocation(state_); decoder_callbacks_->encodeHeaders(std::move(response_headers), true, REDIRECT_LOGGED_IN); config_->stats().oauth_success_.inc(); decoder_callbacks_->continueDecoding(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'oauth2: do not blindly accept requests with a token in the Authorization headera (781) The logic was broken because it assumed an additional call would be performed to the auth server, which isn't the case. Per the filter documentation, a request is only considered subsequently authenticated if there's valid cookie that was set after the access token was received from the auth server: https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/oauth2_filter More info about how to validate an access token (which we don't do, per above): https://www.oauth.com/oauth2-servers/token-introspection-endpoint/ https://datatracker.ietf.org/doc/html/rfc7662 Also fix the fact that ee shouldn't be calling continueDecoding() after decoder_callbacks_->encodeHeaders(). Signed-off-by: Raul Gutierrez Segales <rgs@pinterest.com> Signed-off-by: Matt Klein <mklein@lyft.com> Signed-off-by: Pradeep Rao <pcrao@google.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int pop_fetch_headers(struct Context *ctx) { struct PopData *pop_data = (struct PopData *) ctx->data; struct Progress progress; #ifdef USE_HCACHE header_cache_t *hc = pop_hcache_open(pop_data, ctx->path); #endif time(&pop_data->check_time); pop_data->clear_cache = false; for (int i = 0; i < ctx->msgcount; i++) ctx->hdrs[i]->refno = -1; const int old_count = ctx->msgcount; int ret = pop_fetch_data(pop_data, "UIDL\r\n", NULL, fetch_uidl, ctx); const int new_count = ctx->msgcount; ctx->msgcount = old_count; if (pop_data->cmd_uidl == 2) { if (ret == 0) { pop_data->cmd_uidl = 1; mutt_debug(1, "set UIDL capability\n"); } if (ret == -2 && pop_data->cmd_uidl == 2) { pop_data->cmd_uidl = 0; mutt_debug(1, "unset UIDL capability\n"); snprintf(pop_data->err_msg, sizeof(pop_data->err_msg), "%s", _("Command UIDL is not supported by server.")); } } if (!ctx->quiet) { mutt_progress_init(&progress, _("Fetching message headers..."), MUTT_PROGRESS_MSG, ReadInc, new_count - old_count); } if (ret == 0) { int i, deleted; for (i = 0, deleted = 0; i < old_count; i++) { if (ctx->hdrs[i]->refno == -1) { ctx->hdrs[i]->deleted = true; deleted++; } } if (deleted > 0) { mutt_error( ngettext("%d message has been lost. Try reopening the mailbox.", "%d messages have been lost. Try reopening the mailbox.", deleted), deleted); } bool hcached = false; for (i = old_count; i < new_count; i++) { if (!ctx->quiet) mutt_progress_update(&progress, i + 1 - old_count, -1); #ifdef USE_HCACHE void *data = mutt_hcache_fetch(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data)); if (data) { char *uidl = mutt_str_strdup(ctx->hdrs[i]->data); int refno = ctx->hdrs[i]->refno; int index = ctx->hdrs[i]->index; /* * - POP dynamically numbers headers and relies on h->refno * to map messages; so restore header and overwrite restored * refno with current refno, same for index * - h->data needs to a separate pointer as it's driver-specific * data freed separately elsewhere * (the old h->data should point inside a malloc'd block from * hcache so there shouldn't be a memleak here) */ struct Header *h = mutt_hcache_restore((unsigned char *) data); mutt_hcache_free(hc, &data); mutt_header_free(&ctx->hdrs[i]); ctx->hdrs[i] = h; ctx->hdrs[i]->refno = refno; ctx->hdrs[i]->index = index; ctx->hdrs[i]->data = uidl; ret = 0; hcached = true; } else #endif if ((ret = pop_read_header(pop_data, ctx->hdrs[i])) < 0) break; #ifdef USE_HCACHE else { mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data), ctx->hdrs[i], 0); } #endif /* * faked support for flags works like this: * - if 'hcached' is true, we have the message in our hcache: * - if we also have a body: read * - if we don't have a body: old * (if $mark_old is set which is maybe wrong as * $mark_old should be considered for syncing the * folder and not when opening it XXX) * - if 'hcached' is false, we don't have the message in our hcache: * - if we also have a body: read * - if we don't have a body: new */ const bool bcached = (mutt_bcache_exists(pop_data->bcache, ctx->hdrs[i]->data) == 0); ctx->hdrs[i]->old = false; ctx->hdrs[i]->read = false; if (hcached) { if (bcached) ctx->hdrs[i]->read = true; else if (MarkOld) ctx->hdrs[i]->old = true; } else { if (bcached) ctx->hdrs[i]->read = true; } ctx->msgcount++; } if (i > old_count) mx_update_context(ctx, i - old_count); } #ifdef USE_HCACHE mutt_hcache_close(hc); #endif if (ret < 0) { for (int i = ctx->msgcount; i < new_count; i++) mutt_header_free(&ctx->hdrs[i]); return ret; } /* after putting the result into our structures, * clean up cache, i.e. wipe messages deleted outside * the availability of our cache */ if (MessageCacheClean) mutt_bcache_list(pop_data->bcache, msg_cache_check, (void *) ctx); mutt_clear_error(); return (new_count - old_count); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-241', 'CWE-119', 'CWE-22'], 'message': 'sanitise cache paths Co-authored-by: JerikoOne <jeriko.one@gmx.us>'</s>
<s>[INST] Given the following code containing errors, provide 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 add_post_vars(zval *arr, post_var_data_t *vars, zend_bool eof TSRMLS_DC) { uint64_t max_vars = PG(max_input_vars); vars->ptr = vars->str.c; vars->end = vars->str.c + vars->str.len; while (add_post_var(arr, vars, eof TSRMLS_CC)) { if (++vars->cnt > max_vars) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variables exceeded %" PRIu64 ". " "To increase the limit change max_input_vars in php.ini.", max_vars); return FAILURE; } } if (!eof) { memmove(vars->str.c, vars->ptr, vars->str.len = vars->end - vars->ptr); } return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'Fix bug #73807'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inline void GatherNd(const RuntimeShape& params_shape, const ParamsT* params_data, const RuntimeShape& indices_shape, const IndicesT* indices_data, const RuntimeShape& output_shape, ParamsT* output_data) { ruy::profiler::ScopeLabel label("GatherNd"); const GatherNdHelperResult res = GatherNdHelper(params_shape, indices_shape); for (int i = 0; i < res.n_slices; ++i) { int from_pos = 0; for (int j = 0; j < res.indices_nd; ++j) { from_pos += indices_data[i * res.indices_nd + j] * res.dims_to_count[j]; } std::memcpy(output_data + i * res.slice_size, params_data + from_pos, sizeof(ParamsT) * res.slice_size); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Return a TFLite error if gather_nd will result in reading invalid memory PiperOrigin-RevId: 463054033'</s>
<s>[INST] Given the following code containing errors, provide 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 xmlrpc_char_encode(char *outbuffer, const char *s1) { long unsigned int i; unsigned char c; char buf2[15]; mowgli_string_t *s = mowgli_string_create(); *buf2 = '\0'; *outbuffer = '\0'; if ((!(s1) || (*(s1) == '\0'))) { return; } for (i = 0; s1[i] != '\0'; i++) { c = s1[i]; if (c > 127) { snprintf(buf2, sizeof buf2, "&#%d;", c); s->append(s, buf2, strlen(buf2)); } else if (c == '&') { s->append(s, "&amp;", 5); } else if (c == '<') { s->append(s, "&lt;", 4); } else if (c == '>') { s->append(s, "&gt;", 4); } else if (c == '"') { s->append(s, "&quot;", 6); } else { s->append_char(s, c); } } memcpy(outbuffer, s->str, XMLRPC_BUFSIZE); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Do not copy more bytes than were allocated'</s>
<s>[INST] Given the following code containing errors, provide 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 __u32 dccp_v6_init_sequence(struct sk_buff *skb) { return secure_dccpv6_sequence_number(ipv6_hdr(skb)->daddr.s6_addr32, ipv6_hdr(skb)->saddr.s6_addr32, dccp_hdr(skb)->dccph_dport, dccp_hdr(skb)->dccph_sport ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <dan@doxpara.com> Tested-by: Willy Tarreau <w@1wt.eu> 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: Status TrySimplify(NodeDef* consumer, string* simplified_node_name) override { NodeDef* producer; TF_RETURN_IF_ERROR(GetInputNode(consumer->input(0), &producer)); const bool producer_is_cast = IsCastLike(*producer); const bool can_optimize = !IsCheckNumerics(*producer) && ((producer_is_cast && IsValuePreserving(*consumer)) || (IsValuePreserving(*producer) && IsCastLike(*consumer))); if (!can_optimize || IsControlFlow(*producer) || IsInPreserveSet(*producer) || producer->device() != consumer->device()) { return Status::OK(); } const NodeDef* cast_like_node = producer_is_cast ? producer : consumer; const OpDef* cast_like_op_def = nullptr; TF_RETURN_IF_ERROR(OpRegistry::Global()->LookUpOpDef(cast_like_node->op(), &cast_like_op_def)); DataType cast_src_type; TF_RETURN_IF_ERROR(InputTypeForNode(*cast_like_node, *cast_like_op_def, 0, &cast_src_type)); DataType cast_dst_type; TF_RETURN_IF_ERROR(OutputTypeForNode(*cast_like_node, *cast_like_op_def, 0, &cast_dst_type)); if (!IsFixedSizeType(cast_src_type) || !IsFixedSizeType(cast_dst_type)) { return Status::OK(); } else if (producer_is_cast && DataTypeSize(cast_dst_type) <= DataTypeSize(cast_src_type)) { return Status::OK(); } else if (!producer_is_cast && DataTypeSize(cast_dst_type) >= DataTypeSize(cast_src_type)) { return Status::OK(); } // Check that nodes were not already optimized. const string optimized_producer_name = OptimizedNodeName( ParseNodeScopeAndName(producer->name()), DataTypeString(cast_dst_type)); const string optimized_consumer_name = OptimizedNodeName( ParseNodeScopeAndName(consumer->name()), DataTypeString(cast_src_type)); const bool is_already_optimized = ctx().node_map->NodeExists(optimized_consumer_name) || ctx().node_map->NodeExists(optimized_producer_name); if (is_already_optimized) { return Status::OK(); } // Add copies of consumer and producer in reverse order. NodeDef* input; TF_RETURN_IF_ERROR(GetInputNode(producer->input(0), &input)); // Create new producer node. NodeDef* new_producer = AddCopyNode(optimized_consumer_name, consumer); new_producer->set_input(0, producer->input(0)); ctx().node_map->AddOutput(input->name(), new_producer->name()); // Create new consumer node. NodeDef* new_consumer = AddCopyNode(optimized_producer_name, producer); new_consumer->set_input(0, new_producer->name()); NodeDef* new_value_preserving = producer_is_cast ? new_producer : new_consumer; const DataType new_input_type = producer_is_cast ? cast_src_type : cast_dst_type; // Update the input type of the value-preserving node. The input and // output types of the cast-like nodes remain the same. TF_RETURN_IF_ERROR(SetInputType(new_input_type, new_value_preserving)); // Make sure there is a kernel registered for the value preserving op // with the new input type. TF_RETURN_IF_ERROR(IsKernelRegisteredForNode(*new_value_preserving)); ctx().node_map->AddOutput(new_producer->name(), new_consumer->name()); AddToOptimizationQueue(new_producer); *simplified_node_name = new_consumer->name(); return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Handle a special grappler case resulting in crash. It might happen that a malformed input could be used to trick Grappler into trying to optimize a node with no inputs. This, in turn, would produce a null pointer dereference and a segfault. PiperOrigin-RevId: 369242852 Change-Id: I2e5cbe7aec243d34a6d60220ac8ac9b16f136f6b'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum) { #define AlignedExtent(size,alignment) \ (((size)+((alignment)-1)) & ~((alignment)-1)) size_t alignment, extent, size; void *memory; if (CheckMemoryOverflow(count,quantum) != MagickFalse) return((void *) NULL); memory=NULL; alignment=CACHE_LINE_SIZE; size=count*quantum; extent=AlignedExtent(size,alignment); if ((size == 0) || (alignment < sizeof(void *)) || (extent < size)) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) if (posix_memalign(&memory,alignment,extent) != 0) memory=NULL; #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) memory=_aligned_malloc(extent,alignment); #else { void *p; extent=(size+alignment-1)+sizeof(void *); if (extent > size) { p=malloc(extent); if (p != NULL) { memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment); *((void **) memory-1)=p; } } } #endif return(memory); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Suspend exception processing if too many exceptions'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; if (caplen < CHDLC_HDRLEN) { ND_PRINT((ndo, "[|chdlc]")); return (caplen); } return (chdlc_print(ndo, p,length)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'CVE-2017-13687/CHDLC: Improve bounds and length checks. Prevent a possible buffer overread in chdlc_print() and replace the custom check in chdlc_if_print() with a standard check in chdlc_print() so that the latter certainly does not over-read even when reached via juniper_chdlc_print(). Add length 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: yyparse () #endif #endif { int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yytoken = 0; yyss = yyssa; yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yyn == YYPACT_NINF) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yyn == 0 || yyn == YYTABLE_NINF) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: /* Line 1455 of yacc.c */ #line 320 "ntp_parser.y" { /* I will need to incorporate much more fine grained * error messages. The following should suffice for * the time being. */ msyslog(LOG_ERR, "syntax error in %s line %d, column %d", ip_file->fname, ip_file->err_line_no, ip_file->err_col_no); } break; case 19: /* Line 1455 of yacc.c */ #line 354 "ntp_parser.y" { struct peer_node *my_node = create_peer_node((yyvsp[(1) - (3)].Integer), (yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue)); if (my_node) enqueue(cfgt.peers, my_node); } break; case 20: /* Line 1455 of yacc.c */ #line 360 "ntp_parser.y" { struct peer_node *my_node = create_peer_node((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Address_node), NULL); if (my_node) enqueue(cfgt.peers, my_node); } break; case 27: /* Line 1455 of yacc.c */ #line 377 "ntp_parser.y" { (yyval.Address_node) = create_address_node((yyvsp[(2) - (2)].String), AF_INET); } break; case 28: /* Line 1455 of yacc.c */ #line 378 "ntp_parser.y" { (yyval.Address_node) = create_address_node((yyvsp[(2) - (2)].String), AF_INET6); } break; case 29: /* Line 1455 of yacc.c */ #line 382 "ntp_parser.y" { (yyval.Address_node) = create_address_node((yyvsp[(1) - (1)].String), 0); } break; case 30: /* Line 1455 of yacc.c */ #line 386 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 31: /* Line 1455 of yacc.c */ #line 387 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 32: /* Line 1455 of yacc.c */ #line 391 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 33: /* Line 1455 of yacc.c */ #line 392 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 34: /* Line 1455 of yacc.c */ #line 393 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 35: /* Line 1455 of yacc.c */ #line 394 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 36: /* Line 1455 of yacc.c */ #line 395 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 37: /* Line 1455 of yacc.c */ #line 396 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 38: /* Line 1455 of yacc.c */ #line 397 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 39: /* Line 1455 of yacc.c */ #line 398 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 40: /* Line 1455 of yacc.c */ #line 399 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 41: /* Line 1455 of yacc.c */ #line 400 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 42: /* Line 1455 of yacc.c */ #line 401 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 43: /* Line 1455 of yacc.c */ #line 402 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 44: /* Line 1455 of yacc.c */ #line 403 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 45: /* Line 1455 of yacc.c */ #line 404 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 46: /* Line 1455 of yacc.c */ #line 405 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 47: /* Line 1455 of yacc.c */ #line 415 "ntp_parser.y" { struct unpeer_node *my_node = create_unpeer_node((yyvsp[(2) - (2)].Address_node)); if (my_node) enqueue(cfgt.unpeers, my_node); } break; case 50: /* Line 1455 of yacc.c */ #line 434 "ntp_parser.y" { cfgt.broadcastclient = 1; } break; case 51: /* Line 1455 of yacc.c */ #line 436 "ntp_parser.y" { append_queue(cfgt.manycastserver, (yyvsp[(2) - (2)].Queue)); } break; case 52: /* Line 1455 of yacc.c */ #line 438 "ntp_parser.y" { append_queue(cfgt.multicastclient, (yyvsp[(2) - (2)].Queue)); } break; case 53: /* Line 1455 of yacc.c */ #line 449 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer))); } break; case 54: /* Line 1455 of yacc.c */ #line 451 "ntp_parser.y" { cfgt.auth.control_key = (yyvsp[(2) - (2)].Integer); } break; case 55: /* Line 1455 of yacc.c */ #line 453 "ntp_parser.y" { cfgt.auth.cryptosw++; append_queue(cfgt.auth.crypto_cmd_list, (yyvsp[(2) - (2)].Queue)); } break; case 56: /* Line 1455 of yacc.c */ #line 458 "ntp_parser.y" { cfgt.auth.keys = (yyvsp[(2) - (2)].String); } break; case 57: /* Line 1455 of yacc.c */ #line 460 "ntp_parser.y" { cfgt.auth.keysdir = (yyvsp[(2) - (2)].String); } break; case 58: /* Line 1455 of yacc.c */ #line 462 "ntp_parser.y" { cfgt.auth.request_key = (yyvsp[(2) - (2)].Integer); } break; case 59: /* Line 1455 of yacc.c */ #line 464 "ntp_parser.y" { cfgt.auth.revoke = (yyvsp[(2) - (2)].Integer); } break; case 60: /* Line 1455 of yacc.c */ #line 466 "ntp_parser.y" { cfgt.auth.trusted_key_list = (yyvsp[(2) - (2)].Queue); } break; case 61: /* Line 1455 of yacc.c */ #line 468 "ntp_parser.y" { cfgt.auth.ntp_signd_socket = (yyvsp[(2) - (2)].String); } break; case 63: /* Line 1455 of yacc.c */ #line 474 "ntp_parser.y" { (yyval.Queue) = create_queue(); } break; case 64: /* Line 1455 of yacc.c */ #line 479 "ntp_parser.y" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 65: /* Line 1455 of yacc.c */ #line 486 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 66: /* Line 1455 of yacc.c */ #line 496 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 67: /* Line 1455 of yacc.c */ #line 498 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 68: /* Line 1455 of yacc.c */ #line 500 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 69: /* Line 1455 of yacc.c */ #line 502 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 70: /* Line 1455 of yacc.c */ #line 504 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 71: /* Line 1455 of yacc.c */ #line 506 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 72: /* Line 1455 of yacc.c */ #line 508 "ntp_parser.y" { (yyval.Attr_val) = NULL; cfgt.auth.revoke = (yyvsp[(2) - (2)].Integer); msyslog(LOG_WARNING, "'crypto revoke %d' is deprecated, " "please use 'revoke %d' instead.", cfgt.auth.revoke, cfgt.auth.revoke); } break; case 73: /* Line 1455 of yacc.c */ #line 525 "ntp_parser.y" { append_queue(cfgt.orphan_cmds,(yyvsp[(2) - (2)].Queue)); } break; case 74: /* Line 1455 of yacc.c */ #line 529 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 75: /* Line 1455 of yacc.c */ #line 530 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 76: /* Line 1455 of yacc.c */ #line 535 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 77: /* Line 1455 of yacc.c */ #line 537 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 78: /* Line 1455 of yacc.c */ #line 539 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 79: /* Line 1455 of yacc.c */ #line 541 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 80: /* Line 1455 of yacc.c */ #line 543 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 81: /* Line 1455 of yacc.c */ #line 545 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 82: /* Line 1455 of yacc.c */ #line 547 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 83: /* Line 1455 of yacc.c */ #line 549 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 84: /* Line 1455 of yacc.c */ #line 551 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 85: /* Line 1455 of yacc.c */ #line 553 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 86: /* Line 1455 of yacc.c */ #line 555 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (double)(yyvsp[(2) - (2)].Integer)); } break; case 87: /* Line 1455 of yacc.c */ #line 565 "ntp_parser.y" { append_queue(cfgt.stats_list, (yyvsp[(2) - (2)].Queue)); } break; case 88: /* Line 1455 of yacc.c */ #line 567 "ntp_parser.y" { if (input_from_file) cfgt.stats_dir = (yyvsp[(2) - (2)].String); else { free((yyvsp[(2) - (2)].String)); yyerror("statsdir remote configuration ignored"); } } break; case 89: /* Line 1455 of yacc.c */ #line 576 "ntp_parser.y" { enqueue(cfgt.filegen_opts, create_filegen_node((yyvsp[(2) - (3)].Integer), (yyvsp[(3) - (3)].Queue))); } break; case 90: /* Line 1455 of yacc.c */ #line 583 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 91: /* Line 1455 of yacc.c */ #line 584 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue(create_ival((yyvsp[(1) - (1)].Integer))); } break; case 100: /* Line 1455 of yacc.c */ #line 600 "ntp_parser.y" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 101: /* Line 1455 of yacc.c */ #line 607 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 102: /* Line 1455 of yacc.c */ #line 617 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); else { (yyval.Attr_val) = NULL; free((yyvsp[(2) - (2)].String)); yyerror("filegen file remote configuration ignored"); } } break; case 103: /* Line 1455 of yacc.c */ #line 627 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("filegen type remote configuration ignored"); } } break; case 104: /* Line 1455 of yacc.c */ #line 636 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("filegen link remote configuration ignored"); } } break; case 105: /* Line 1455 of yacc.c */ #line 645 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("filegen nolink remote configuration ignored"); } } break; case 106: /* Line 1455 of yacc.c */ #line 653 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 107: /* Line 1455 of yacc.c */ #line 654 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 115: /* Line 1455 of yacc.c */ #line 674 "ntp_parser.y" { append_queue(cfgt.discard_opts, (yyvsp[(2) - (2)].Queue)); } break; case 116: /* Line 1455 of yacc.c */ #line 678 "ntp_parser.y" { append_queue(cfgt.mru_opts, (yyvsp[(2) - (2)].Queue)); } break; case 117: /* Line 1455 of yacc.c */ #line 682 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node((yyvsp[(2) - (3)].Address_node), NULL, (yyvsp[(3) - (3)].Queue), ip_file->line_no)); } break; case 118: /* Line 1455 of yacc.c */ #line 687 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node((yyvsp[(2) - (5)].Address_node), (yyvsp[(4) - (5)].Address_node), (yyvsp[(5) - (5)].Queue), ip_file->line_no)); } break; case 119: /* Line 1455 of yacc.c */ #line 692 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node(NULL, NULL, (yyvsp[(3) - (3)].Queue), ip_file->line_no)); } break; case 120: /* Line 1455 of yacc.c */ #line 697 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node( create_address_node( estrdup("0.0.0.0"), AF_INET), create_address_node( estrdup("0.0.0.0"), AF_INET), (yyvsp[(4) - (4)].Queue), ip_file->line_no)); } break; case 121: /* Line 1455 of yacc.c */ #line 710 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node( create_address_node( estrdup("::"), AF_INET6), create_address_node( estrdup("::"), AF_INET6), (yyvsp[(4) - (4)].Queue), ip_file->line_no)); } break; case 122: /* Line 1455 of yacc.c */ #line 723 "ntp_parser.y" { enqueue(cfgt.restrict_opts, create_restrict_node( NULL, NULL, enqueue((yyvsp[(3) - (3)].Queue), create_ival((yyvsp[(2) - (3)].Integer))), ip_file->line_no)); } break; case 123: /* Line 1455 of yacc.c */ #line 734 "ntp_parser.y" { (yyval.Queue) = create_queue(); } break; case 124: /* Line 1455 of yacc.c */ #line 736 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 139: /* Line 1455 of yacc.c */ #line 758 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 140: /* Line 1455 of yacc.c */ #line 760 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 141: /* Line 1455 of yacc.c */ #line 764 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 142: /* Line 1455 of yacc.c */ #line 765 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 143: /* Line 1455 of yacc.c */ #line 766 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 144: /* Line 1455 of yacc.c */ #line 771 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 145: /* Line 1455 of yacc.c */ #line 773 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 146: /* Line 1455 of yacc.c */ #line 777 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 147: /* Line 1455 of yacc.c */ #line 778 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 148: /* Line 1455 of yacc.c */ #line 779 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 149: /* Line 1455 of yacc.c */ #line 780 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 150: /* Line 1455 of yacc.c */ #line 781 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 151: /* Line 1455 of yacc.c */ #line 782 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 152: /* Line 1455 of yacc.c */ #line 783 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 153: /* Line 1455 of yacc.c */ #line 784 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 154: /* Line 1455 of yacc.c */ #line 793 "ntp_parser.y" { enqueue(cfgt.fudge, create_addr_opts_node((yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue))); } break; case 155: /* Line 1455 of yacc.c */ #line 798 "ntp_parser.y" { enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 156: /* Line 1455 of yacc.c */ #line 800 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 157: /* Line 1455 of yacc.c */ #line 804 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 158: /* Line 1455 of yacc.c */ #line 805 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 159: /* Line 1455 of yacc.c */ #line 806 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 160: /* Line 1455 of yacc.c */ #line 807 "ntp_parser.y" { (yyval.Attr_val) = create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String)); } break; case 161: /* Line 1455 of yacc.c */ #line 808 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 162: /* Line 1455 of yacc.c */ #line 809 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 163: /* Line 1455 of yacc.c */ #line 810 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 164: /* Line 1455 of yacc.c */ #line 811 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 165: /* Line 1455 of yacc.c */ #line 820 "ntp_parser.y" { append_queue(cfgt.enable_opts, (yyvsp[(2) - (2)].Queue)); } break; case 166: /* Line 1455 of yacc.c */ #line 822 "ntp_parser.y" { append_queue(cfgt.disable_opts, (yyvsp[(2) - (2)].Queue)); } break; case 167: /* Line 1455 of yacc.c */ #line 827 "ntp_parser.y" { if ((yyvsp[(2) - (2)].Attr_val) != NULL) (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); else (yyval.Queue) = (yyvsp[(1) - (2)].Queue); } break; case 168: /* Line 1455 of yacc.c */ #line 834 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Attr_val) != NULL) (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); else (yyval.Queue) = create_queue(); } break; case 169: /* Line 1455 of yacc.c */ #line 843 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 170: /* Line 1455 of yacc.c */ #line 844 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 171: /* Line 1455 of yacc.c */ #line 845 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 172: /* Line 1455 of yacc.c */ #line 846 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 173: /* Line 1455 of yacc.c */ #line 847 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 174: /* Line 1455 of yacc.c */ #line 848 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); } break; case 175: /* Line 1455 of yacc.c */ #line 850 "ntp_parser.y" { if (input_from_file) (yyval.Attr_val) = create_attr_ival(T_Flag, (yyvsp[(1) - (1)].Integer)); else { (yyval.Attr_val) = NULL; yyerror("enable/disable stats remote configuration ignored"); } } break; case 176: /* Line 1455 of yacc.c */ #line 865 "ntp_parser.y" { append_queue(cfgt.tinker, (yyvsp[(2) - (2)].Queue)); } break; case 177: /* Line 1455 of yacc.c */ #line 869 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 178: /* Line 1455 of yacc.c */ #line 870 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 179: /* Line 1455 of yacc.c */ #line 874 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 180: /* Line 1455 of yacc.c */ #line 875 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 181: /* Line 1455 of yacc.c */ #line 876 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 182: /* Line 1455 of yacc.c */ #line 877 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 183: /* Line 1455 of yacc.c */ #line 878 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 184: /* Line 1455 of yacc.c */ #line 879 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 185: /* Line 1455 of yacc.c */ #line 880 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double)); } break; case 187: /* Line 1455 of yacc.c */ #line 891 "ntp_parser.y" { if (curr_include_level >= MAXINCLUDELEVEL) { fprintf(stderr, "getconfig: Maximum include file level exceeded.\n"); msyslog(LOG_ERR, "getconfig: Maximum include file level exceeded."); } else { fp[curr_include_level + 1] = F_OPEN(FindConfig((yyvsp[(2) - (3)].String)), "r"); if (fp[curr_include_level + 1] == NULL) { fprintf(stderr, "getconfig: Couldn't open <%s>\n", FindConfig((yyvsp[(2) - (3)].String))); msyslog(LOG_ERR, "getconfig: Couldn't open <%s>", FindConfig((yyvsp[(2) - (3)].String))); } else ip_file = fp[++curr_include_level]; } } break; case 188: /* Line 1455 of yacc.c */ #line 907 "ntp_parser.y" { while (curr_include_level != -1) FCLOSE(fp[curr_include_level--]); } break; case 189: /* Line 1455 of yacc.c */ #line 913 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double))); } break; case 190: /* Line 1455 of yacc.c */ #line 915 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer))); } break; case 191: /* Line 1455 of yacc.c */ #line 917 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_dval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Double))); } break; case 192: /* Line 1455 of yacc.c */ #line 919 "ntp_parser.y" { /* Null action, possibly all null parms */ } break; case 193: /* Line 1455 of yacc.c */ #line 921 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 194: /* Line 1455 of yacc.c */ #line 924 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 195: /* Line 1455 of yacc.c */ #line 926 "ntp_parser.y" { if (input_from_file) enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); else { free((yyvsp[(2) - (2)].String)); yyerror("logfile remote configuration ignored"); } } break; case 196: /* Line 1455 of yacc.c */ #line 937 "ntp_parser.y" { append_queue(cfgt.logconfig, (yyvsp[(2) - (2)].Queue)); } break; case 197: /* Line 1455 of yacc.c */ #line 939 "ntp_parser.y" { append_queue(cfgt.phone, (yyvsp[(2) - (2)].Queue)); } break; case 198: /* Line 1455 of yacc.c */ #line 941 "ntp_parser.y" { if (input_from_file) enqueue(cfgt.vars, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); else { free((yyvsp[(2) - (2)].String)); yyerror("saveconfigdir remote configuration ignored"); } } break; case 199: /* Line 1455 of yacc.c */ #line 951 "ntp_parser.y" { enqueue(cfgt.setvar, (yyvsp[(2) - (2)].Set_var)); } break; case 200: /* Line 1455 of yacc.c */ #line 953 "ntp_parser.y" { enqueue(cfgt.trap, create_addr_opts_node((yyvsp[(2) - (2)].Address_node), NULL)); } break; case 201: /* Line 1455 of yacc.c */ #line 955 "ntp_parser.y" { enqueue(cfgt.trap, create_addr_opts_node((yyvsp[(2) - (3)].Address_node), (yyvsp[(3) - (3)].Queue))); } break; case 202: /* Line 1455 of yacc.c */ #line 957 "ntp_parser.y" { append_queue(cfgt.ttl, (yyvsp[(2) - (2)].Queue)); } break; case 203: /* Line 1455 of yacc.c */ #line 959 "ntp_parser.y" { enqueue(cfgt.qos, create_attr_sval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].String))); } break; case 204: /* Line 1455 of yacc.c */ #line 964 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval(T_Driftfile, (yyvsp[(1) - (1)].String))); } break; case 205: /* Line 1455 of yacc.c */ #line 966 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_dval(T_WanderThreshold, (yyvsp[(2) - (2)].Double))); enqueue(cfgt.vars, create_attr_sval(T_Driftfile, (yyvsp[(1) - (2)].String))); } break; case 206: /* Line 1455 of yacc.c */ #line 969 "ntp_parser.y" { enqueue(cfgt.vars, create_attr_sval(T_Driftfile, "\0")); } break; case 207: /* Line 1455 of yacc.c */ #line 974 "ntp_parser.y" { (yyval.Set_var) = create_setvar_node((yyvsp[(1) - (4)].String), (yyvsp[(3) - (4)].String), (yyvsp[(4) - (4)].Integer)); } break; case 208: /* Line 1455 of yacc.c */ #line 976 "ntp_parser.y" { (yyval.Set_var) = create_setvar_node((yyvsp[(1) - (3)].String), (yyvsp[(3) - (3)].String), 0); } break; case 209: /* Line 1455 of yacc.c */ #line 981 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 210: /* Line 1455 of yacc.c */ #line 982 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 211: /* Line 1455 of yacc.c */ #line 986 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Integer)); } break; case 212: /* Line 1455 of yacc.c */ #line 987 "ntp_parser.y" { (yyval.Attr_val) = create_attr_pval((yyvsp[(1) - (2)].Integer), (yyvsp[(2) - (2)].Address_node)); } break; case 213: /* Line 1455 of yacc.c */ #line 991 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 214: /* Line 1455 of yacc.c */ #line 992 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 215: /* Line 1455 of yacc.c */ #line 997 "ntp_parser.y" { char prefix = (yyvsp[(1) - (1)].String)[0]; char *type = (yyvsp[(1) - (1)].String) + 1; if (prefix != '+' && prefix != '-' && prefix != '=') { yyerror("Logconfig prefix is not '+', '-' or '='\n"); } else (yyval.Attr_val) = create_attr_sval(prefix, estrdup(type)); YYFREE((yyvsp[(1) - (1)].String)); } break; case 216: /* Line 1455 of yacc.c */ #line 1012 "ntp_parser.y" { enqueue(cfgt.nic_rules, create_nic_rule_node((yyvsp[(3) - (3)].Integer), NULL, (yyvsp[(2) - (3)].Integer))); } break; case 217: /* Line 1455 of yacc.c */ #line 1017 "ntp_parser.y" { enqueue(cfgt.nic_rules, create_nic_rule_node(0, (yyvsp[(3) - (3)].String), (yyvsp[(2) - (3)].Integer))); } break; case 227: /* Line 1455 of yacc.c */ #line 1048 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_ival((yyvsp[(2) - (2)].Integer))); } break; case 228: /* Line 1455 of yacc.c */ #line 1049 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue(create_ival((yyvsp[(1) - (1)].Integer))); } break; case 229: /* Line 1455 of yacc.c */ #line 1054 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Attr_val)); } break; case 230: /* Line 1455 of yacc.c */ #line 1056 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Attr_val)); } break; case 231: /* Line 1455 of yacc.c */ #line 1061 "ntp_parser.y" { (yyval.Attr_val) = create_attr_ival('i', (yyvsp[(1) - (1)].Integer)); } break; case 233: /* Line 1455 of yacc.c */ #line 1067 "ntp_parser.y" { (yyval.Attr_val) = create_attr_shorts('-', (yyvsp[(2) - (5)].Integer), (yyvsp[(4) - (5)].Integer)); } break; case 234: /* Line 1455 of yacc.c */ #line 1071 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), create_pval((yyvsp[(2) - (2)].String))); } break; case 235: /* Line 1455 of yacc.c */ #line 1072 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue(create_pval((yyvsp[(1) - (1)].String))); } break; case 236: /* Line 1455 of yacc.c */ #line 1076 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Address_node)); } break; case 237: /* Line 1455 of yacc.c */ #line 1077 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Address_node)); } break; case 238: /* Line 1455 of yacc.c */ #line 1082 "ntp_parser.y" { if ((yyvsp[(1) - (1)].Integer) != 0 && (yyvsp[(1) - (1)].Integer) != 1) { yyerror("Integer value is not boolean (0 or 1). Assuming 1"); (yyval.Integer) = 1; } else (yyval.Integer) = (yyvsp[(1) - (1)].Integer); } break; case 239: /* Line 1455 of yacc.c */ #line 1090 "ntp_parser.y" { (yyval.Integer) = 1; } break; case 240: /* Line 1455 of yacc.c */ #line 1091 "ntp_parser.y" { (yyval.Integer) = 0; } break; case 241: /* Line 1455 of yacc.c */ #line 1095 "ntp_parser.y" { (yyval.Double) = (double)(yyvsp[(1) - (1)].Integer); } break; case 243: /* Line 1455 of yacc.c */ #line 1106 "ntp_parser.y" { cfgt.sim_details = create_sim_node((yyvsp[(3) - (5)].Queue), (yyvsp[(4) - (5)].Queue)); /* Reset the old_config_style variable */ old_config_style = 1; } break; case 244: /* Line 1455 of yacc.c */ #line 1120 "ntp_parser.y" { old_config_style = 0; } break; case 245: /* Line 1455 of yacc.c */ #line 1124 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (3)].Queue), (yyvsp[(2) - (3)].Attr_val)); } break; case 246: /* Line 1455 of yacc.c */ #line 1125 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (2)].Attr_val)); } break; case 247: /* Line 1455 of yacc.c */ #line 1129 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 248: /* Line 1455 of yacc.c */ #line 1130 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 249: /* Line 1455 of yacc.c */ #line 1134 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Sim_server)); } break; case 250: /* Line 1455 of yacc.c */ #line 1135 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Sim_server)); } break; case 251: /* Line 1455 of yacc.c */ #line 1140 "ntp_parser.y" { (yyval.Sim_server) = create_sim_server((yyvsp[(1) - (5)].Address_node), (yyvsp[(3) - (5)].Double), (yyvsp[(4) - (5)].Queue)); } break; case 252: /* Line 1455 of yacc.c */ #line 1144 "ntp_parser.y" { (yyval.Double) = (yyvsp[(3) - (4)].Double); } break; case 253: /* Line 1455 of yacc.c */ #line 1148 "ntp_parser.y" { (yyval.Address_node) = (yyvsp[(3) - (3)].Address_node); } break; case 254: /* Line 1455 of yacc.c */ #line 1152 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (2)].Queue), (yyvsp[(2) - (2)].Sim_script)); } break; case 255: /* Line 1455 of yacc.c */ #line 1153 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (1)].Sim_script)); } break; case 256: /* Line 1455 of yacc.c */ #line 1158 "ntp_parser.y" { (yyval.Sim_script) = create_sim_script_info((yyvsp[(3) - (6)].Double), (yyvsp[(5) - (6)].Queue)); } break; case 257: /* Line 1455 of yacc.c */ #line 1162 "ntp_parser.y" { (yyval.Queue) = enqueue((yyvsp[(1) - (3)].Queue), (yyvsp[(2) - (3)].Attr_val)); } break; case 258: /* Line 1455 of yacc.c */ #line 1163 "ntp_parser.y" { (yyval.Queue) = enqueue_in_new_queue((yyvsp[(1) - (2)].Attr_val)); } break; case 259: /* Line 1455 of yacc.c */ #line 1168 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 260: /* Line 1455 of yacc.c */ #line 1170 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 261: /* Line 1455 of yacc.c */ #line 1172 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 262: /* Line 1455 of yacc.c */ #line 1174 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; case 263: /* Line 1455 of yacc.c */ #line 1176 "ntp_parser.y" { (yyval.Attr_val) = create_attr_dval((yyvsp[(1) - (3)].Integer), (yyvsp[(3) - (3)].Double)); } break; /* Line 1455 of yacc.c */ #line 3826 "ntp_parser.c" default: break; } YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else { YYSIZE_T yysize = yysyntax_error (0, yystate, yychar); if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM) { YYSIZE_T yyalloc = 2 * yysize; if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM)) yyalloc = YYSTACK_ALLOC_MAXIMUM; if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yyalloc); if (yymsg) yymsg_alloc = yyalloc; else { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; } } if (0 < yysize && yysize <= yymsg_alloc) { (void) yysyntax_error (yymsg, yystate, yychar); yyerror (yymsg); } else { yyerror (YY_("syntax error")); if (yysize != 0) goto yyexhaustedlab; } } #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (yyn != YYPACT_NINF) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } *++yyvsp = yylval; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined(yyoverflow) || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': '[Bug 1593] ntpd abort in free() with logconfig syntax error.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ip_expire(unsigned long arg) { struct ipq *qp; struct net *net; qp = container_of((struct inet_frag_queue *) arg, struct ipq, q); net = container_of(qp->q.net, struct net, ipv4.frags); spin_lock(&qp->q.lock); if (qp->q.last_in & INET_FRAG_COMPLETE) goto out; ipq_kill(qp); IP_INC_STATS_BH(net, IPSTATS_MIB_REASMTIMEOUT); IP_INC_STATS_BH(net, IPSTATS_MIB_REASMFAILS); if ((qp->q.last_in & INET_FRAG_FIRST_IN) && qp->q.fragments != NULL) { struct sk_buff *head = qp->q.fragments; rcu_read_lock(); head->dev = dev_get_by_index_rcu(net, qp->iif); if (!head->dev) goto out_rcu_unlock; /* * Only search router table for the head fragment, * when defraging timeout at PRE_ROUTING HOOK. */ if (qp->user == IP_DEFRAG_CONNTRACK_IN && !skb_dst(head)) { const struct iphdr *iph = ip_hdr(head); int err = ip_route_input(head, iph->daddr, iph->saddr, iph->tos, head->dev); if (unlikely(err)) goto out_rcu_unlock; /* * Only an end host needs to send an ICMP * "Fragment Reassembly Timeout" message, per RFC792. */ if (skb_rtable(head)->rt_type != RTN_LOCAL) goto out_rcu_unlock; } /* Send an ICMP "Fragment Reassembly Timeout" message. */ icmp_send(head, ICMP_TIME_EXCEEDED, ICMP_EXC_FRAGTIME, 0); out_rcu_unlock: rcu_read_unlock(); } out: spin_unlock(&qp->q.lock); ipq_put(qp); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'net: ip_expire() must revalidate route Commit 4a94445c9a5c (net: Use ip_route_input_noref() in input path) added a bug in IP defragmentation handling, in case timeout is fired. When a frame is defragmented, we use last skb dst field when building final skb. Its dst is valid, since we are in rcu read section. But if a timeout occurs, we take first queued fragment to build one ICMP TIME EXCEEDED message. Problem is all queued skb have weak dst pointers, since we escaped RCU critical section after their queueing. icmp_send() might dereference a now freed (and possibly reused) part of memory. Calling skb_dst_drop() and ip_route_input_noref() to revalidate route is the only possible choice. Reported-by: Denys Fedoryshchenko <denys@visp.net.lb> Signed-off-by: Eric Dumazet <eric.dumazet@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pci_bus_configured(int bus) { assert(bus >= 0 && bus < MAXBUSES); return (pci_businfo[bus] != NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core Tracked-On: #3252 Signed-off-by: Shuo A Liu <shuo.a.liu@intel.com> Reviewed-by: Yonghua Huang <yonghua.huang@intel.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pci_set_cfgdata32(struct pci_vdev *dev, int offset, uint32_t val) { assert(offset <= (PCI_REGMAX - 3) && (offset & 3) == 0); *(uint32_t *)(dev->cfgdata + offset) = val; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core Tracked-On: #3252 Signed-off-by: Shuo A Liu <shuo.a.liu@intel.com> Reviewed-by: Yonghua Huang <yonghua.huang@intel.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: pci_emul_add_capability(struct pci_vdev *dev, u_char *capdata, int caplen) { int i, capoff, reallen; uint16_t sts; assert(caplen > 0); reallen = roundup2(caplen, 4); /* dword aligned */ sts = pci_get_cfgdata16(dev, PCIR_STATUS); if ((sts & PCIM_STATUS_CAPPRESENT) == 0) capoff = CAP_START_OFFSET; else capoff = dev->capend + 1; /* Check if we have enough space */ if (capoff + reallen > PCI_REGMAX + 1) return -1; /* Set the previous capability pointer */ if ((sts & PCIM_STATUS_CAPPRESENT) == 0) { pci_set_cfgdata8(dev, PCIR_CAP_PTR, capoff); pci_set_cfgdata16(dev, PCIR_STATUS, sts|PCIM_STATUS_CAPPRESENT); } else pci_set_cfgdata8(dev, dev->prevcap + 1, capoff); /* Copy the capability */ for (i = 0; i < caplen; i++) pci_set_cfgdata8(dev, capoff + i, capdata[i]); /* Set the next capability pointer */ pci_set_cfgdata8(dev, capoff + 1, 0); dev->prevcap = capoff; dev->capend = capoff + reallen - 1; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-703'], 'message': 'dm: pci: clean up assert() in pci core Tracked-On: #3252 Signed-off-by: Shuo A Liu <shuo.a.liu@intel.com> Reviewed-by: Yonghua Huang <yonghua.huang@intel.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void gen_prov_start(struct prov_rx *rx, struct net_buf_simple *buf) { uint8_t seg = SEG_NVAL; if (rx->xact_id == link.rx.id) { if (!link.rx.seg) { if (!ack_pending()) { BT_DBG("Resending ack"); gen_prov_ack_send(rx->xact_id); } return; } if (!(link.rx.seg & BIT(0))) { BT_DBG("Ignoring duplicate segment"); return; } } else if (rx->xact_id != next_transaction_id(link.rx.id)) { BT_WARN("Unexpected xact 0x%x, expected 0x%x", rx->xact_id, next_transaction_id(link.rx.id)); return; } net_buf_simple_reset(link.rx.buf); link.rx.buf->len = net_buf_simple_pull_be16(buf); link.rx.id = rx->xact_id; link.rx.fcs = net_buf_simple_pull_u8(buf); BT_DBG("len %u last_seg %u total_len %u fcs 0x%02x", buf->len, START_LAST_SEG(rx->gpc), link.rx.buf->len, link.rx.fcs); if (link.rx.buf->len < 1) { BT_ERR("Ignoring zero-length provisioning PDU"); prov_failed(PROV_ERR_NVAL_FMT); return; } if (link.rx.buf->len > link.rx.buf->size) { BT_ERR("Too large provisioning PDU (%u bytes)", link.rx.buf->len); prov_failed(PROV_ERR_NVAL_FMT); return; } if (START_LAST_SEG(rx->gpc) > 0 && link.rx.buf->len <= 20U) { BT_ERR("Too small total length for multi-segment PDU"); prov_failed(PROV_ERR_NVAL_FMT); return; } prov_clear_tx(); link.rx.last_seg = START_LAST_SEG(rx->gpc); if ((link.rx.seg & BIT(0)) && (find_msb_set((~link.rx.seg) & SEG_NVAL) - 1 > link.rx.last_seg)) { BT_ERR("Invalid segment index %u", seg); prov_failed(PROV_ERR_NVAL_FMT); return; } if (link.rx.seg) { seg = link.rx.seg; } link.rx.seg = seg & ((1 << (START_LAST_SEG(rx->gpc) + 1)) - 1); memcpy(link.rx.buf->data, buf->data, buf->len); XACT_SEG_RECV(0); if (!link.rx.seg) { prov_msg_recv(); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Bluetooth: Mesh: Check SegN when receiving Transaction Start PDU When receiving Transaction Start PDU, assure that number of segments needed to send a Provisioning PDU with TotalLength size is equal to SegN value provided in the Transaction Start PDU. Signed-off-by: Pavel Vasilyev <pavel.vasilyev@nordicsemi.no> (cherry picked from commit a63c51567991ded3939bbda4f82bcb8c44228331)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPM2B_PRIVATE_KEY_RSA_Marshal(TPM2B_PRIVATE_KEY_RSA *source, BYTE **buffer, INT32 *size) { UINT16 written = 0; written += TPM2B_Marshal(&source->b, buffer, size); return written; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Add maxSize parameter to TPM2B_Marshal for sanity checks Add maxSize parameter to TPM2B_Marshal and assert on it checking the size of the data intended to be marshaled versus the maximum buffer size. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TPM2B_NAME_Marshal(TPM2B_NAME *source, BYTE **buffer, INT32 *size) { UINT16 written = 0; written += TPM2B_Marshal(&source->b, buffer, size); return written; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tpm2: Add maxSize parameter to TPM2B_Marshal for sanity checks Add maxSize parameter to TPM2B_Marshal and assert on it checking the size of the data intended to be marshaled versus the maximum buffer size. Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void parse_content_range(URLContext *h, const char *p) { HTTPContext *s = h->priv_data; const char *slash; if (!strncmp(p, "bytes ", 6)) { p += 6; s->off = strtoll(p, NULL, 10); if ((slash = strchr(p, '/')) && strlen(slash) > 0) s->filesize = strtoll(slash + 1, NULL, 10); } if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647)) h->is_streamed = 0; /* we _can_ in fact seek */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <paulcher@icloud.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: GF_Err gf_hinter_finalize(GF_ISOFile *file, GF_SDP_IODProfile IOD_Profile, u32 bandwidth) { u32 i, sceneT, odT, descIndex, size, size64; GF_InitialObjectDescriptor *iod; GF_SLConfig slc; GF_ISOSample *samp; Bool remove_ocr; u8 *buffer; char buf64[5000], sdpLine[5100]; gf_isom_sdp_clean(file); if (bandwidth) { sprintf(buf64, "b=AS:%d", bandwidth); gf_isom_sdp_add_line(file, buf64); } //xtended attribute for copyright if (gf_sys_is_test_mode()) { sprintf(buf64, "a=x-copyright: %s", "MP4/3GP File hinted with GPAC - (c) Telecom ParisTech (http://gpac.io)"); } else { sprintf(buf64, "a=x-copyright: MP4/3GP File hinted with GPAC %s - %s", gf_gpac_version(), gf_gpac_copyright() ); } gf_isom_sdp_add_line(file, buf64); if (IOD_Profile == GF_SDP_IOD_NONE) return GF_OK; odT = sceneT = 0; for (i=0; i<gf_isom_get_track_count(file); i++) { if (!gf_isom_is_track_in_root_od(file, i+1)) continue; switch (gf_isom_get_media_type(file,i+1)) { case GF_ISOM_MEDIA_OD: odT = i+1; break; case GF_ISOM_MEDIA_SCENE: sceneT = i+1; break; } } remove_ocr = 0; if (IOD_Profile == GF_SDP_IOD_ISMA_STRICT) { IOD_Profile = GF_SDP_IOD_ISMA; remove_ocr = 1; } /*if we want ISMA like iods, we need at least BIFS */ if ( (IOD_Profile == GF_SDP_IOD_ISMA) && !sceneT ) return GF_BAD_PARAM; /*do NOT change PLs, we assume they are correct*/ iod = (GF_InitialObjectDescriptor *) gf_isom_get_root_od(file); if (!iod) return GF_NOT_SUPPORTED; /*rewrite an IOD with good SL config - embbed data if possible*/ if (IOD_Profile == GF_SDP_IOD_ISMA) { GF_ESD *esd; Bool is_ok = 1; while (gf_list_count(iod->ESDescriptors)) { esd = (GF_ESD*)gf_list_get(iod->ESDescriptors, 0); gf_odf_desc_del((GF_Descriptor *) esd); gf_list_rem(iod->ESDescriptors, 0); } /*get OD esd, and embbed stream data if possible*/ if (odT) { esd = gf_isom_get_esd(file, odT, 1); if (gf_isom_get_sample_count(file, odT)==1) { samp = gf_isom_get_sample(file, odT, 1, &descIndex); if (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_OD)) { InitSL_NULL(&slc); slc.predefined = 0; slc.hasRandomAccessUnitsOnlyFlag = 1; slc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, odT); slc.OCRResolution = 1000; slc.startCTS = samp->DTS+samp->CTS_Offset; slc.startDTS = samp->DTS; //set the SL for future extraction gf_isom_set_extraction_slc(file, odT, 1, &slc); size64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000); buf64[size64] = 0; sprintf(sdpLine, "data:application/mpeg4-od-au;base64,%s", buf64); if (esd->decoderConfig) { esd->decoderConfig->avgBitrate = 0; esd->decoderConfig->bufferSizeDB = samp->dataLength; esd->decoderConfig->maxBitrate = 0; } size64 = (u32) strlen(sdpLine)+1; esd->URLString = (char*)gf_malloc(sizeof(char) * size64); strcpy(esd->URLString, sdpLine); } else { GF_LOG(GF_LOG_WARNING, GF_LOG_RTP, ("[rtp hinter] OD sample too large to be embedded in IOD - ISMA disabled\n")); is_ok = 0; } gf_isom_sample_del(&samp); } if (remove_ocr) esd->OCRESID = 0; else if (esd->OCRESID == esd->ESID) esd->OCRESID = 0; //OK, add this to our IOD gf_list_add(iod->ESDescriptors, esd); } esd = gf_isom_get_esd(file, sceneT, 1); if (gf_isom_get_sample_count(file, sceneT)==1) { samp = gf_isom_get_sample(file, sceneT, 1, &descIndex); if (samp && gf_hinter_can_embbed_data(samp->data, samp->dataLength, GF_STREAM_SCENE)) { slc.timeScale = slc.timestampResolution = gf_isom_get_media_timescale(file, sceneT); slc.OCRResolution = 1000; slc.startCTS = samp->DTS+samp->CTS_Offset; slc.startDTS = samp->DTS; //set the SL for future extraction gf_isom_set_extraction_slc(file, sceneT, 1, &slc); //encode in Base64 the sample size64 = gf_base64_encode(samp->data, samp->dataLength, buf64, 2000); buf64[size64] = 0; sprintf(sdpLine, "data:application/mpeg4-bifs-au;base64,%s", buf64); if (esd->decoderConfig) { esd->decoderConfig->avgBitrate = 0; esd->decoderConfig->bufferSizeDB = samp->dataLength; esd->decoderConfig->maxBitrate = 0; } esd->URLString = (char*)gf_malloc(sizeof(char) * (strlen(sdpLine)+1)); strcpy(esd->URLString, sdpLine); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_RTP, ("[rtp hinter] Scene description sample too large to be embedded in IOD - ISMA disabled\n")); is_ok = 0; } gf_isom_sample_del(&samp); } if (remove_ocr) esd->OCRESID = 0; else if (esd->OCRESID == esd->ESID) esd->OCRESID = 0; gf_list_add(iod->ESDescriptors, esd); if (is_ok) { u32 has_a, has_v, has_i_a, has_i_v; has_a = has_v = has_i_a = has_i_v = 0; for (i=0; i<gf_isom_get_track_count(file); i++) { esd = gf_isom_get_esd(file, i+1, 1); if (!esd) continue; if (esd->decoderConfig) { if (esd->decoderConfig->streamType==GF_STREAM_VISUAL) { if (esd->decoderConfig->objectTypeIndication==GF_CODECID_MPEG4_PART2) has_i_v ++; else has_v++; } else if (esd->decoderConfig->streamType==GF_STREAM_AUDIO) { if (esd->decoderConfig->objectTypeIndication==GF_CODECID_AAC_MPEG4) has_i_a ++; else has_a++; } } gf_odf_desc_del((GF_Descriptor *)esd); } /*only 1 MPEG-4 visual max and 1 MPEG-4 audio max for ISMA compliancy*/ if (!has_v && !has_a && (has_i_v<=1) && (has_i_a<=1)) { sprintf(sdpLine, "a=isma-compliance:1,1.0,1"); gf_isom_sdp_add_line(file, sdpLine); } } } //encode the IOD buffer = NULL; size = 0; gf_odf_desc_write((GF_Descriptor *) iod, &buffer, &size); gf_odf_desc_del((GF_Descriptor *)iod); //encode in Base64 the iod size64 = gf_base64_encode(buffer, size, buf64, 2000); buf64[size64] = 0; gf_free(buffer); sprintf(sdpLine, "a=mpeg4-iod:\"data:application/mpeg4-iod;base64,%s\"", buf64); gf_isom_sdp_add_line(file, sdpLine); return GF_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'fixed #1885'</s>
<s>[INST] Given the following code containing errors, provide 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 ssl3_mac(SSL *ssl, unsigned char *md, int send) { SSL3_RECORD *rec; unsigned char *mac_sec,*seq; EVP_MD_CTX md_ctx; const EVP_MD *hash; unsigned char *p,rec_char; unsigned int md_size; int npad; if (send) { rec= &(ssl->s3->wrec); mac_sec= &(ssl->s3->write_mac_secret[0]); seq= &(ssl->s3->write_sequence[0]); hash=ssl->write_hash; } else { rec= &(ssl->s3->rrec); mac_sec= &(ssl->s3->read_mac_secret[0]); seq= &(ssl->s3->read_sequence[0]); hash=ssl->read_hash; } md_size=EVP_MD_size(hash); npad=(48/md_size)*md_size; /* Chop the digest off the end :-) */ EVP_MD_CTX_init(&md_ctx); EVP_DigestInit_ex( &md_ctx,hash, NULL); EVP_DigestUpdate(&md_ctx,mac_sec,md_size); EVP_DigestUpdate(&md_ctx,ssl3_pad_1,npad); EVP_DigestUpdate(&md_ctx,seq,8); rec_char=rec->type; EVP_DigestUpdate(&md_ctx,&rec_char,1); p=md; s2n(rec->length,p); EVP_DigestUpdate(&md_ctx,md,2); EVP_DigestUpdate(&md_ctx,rec->input,rec->length); EVP_DigestFinal_ex( &md_ctx,md,NULL); EVP_DigestInit_ex( &md_ctx,hash, NULL); EVP_DigestUpdate(&md_ctx,mac_sec,md_size); EVP_DigestUpdate(&md_ctx,ssl3_pad_2,npad); EVP_DigestUpdate(&md_ctx,md,md_size); EVP_DigestFinal_ex( &md_ctx,md,&md_size); EVP_MD_CTX_cleanup(&md_ctx); ssl3_record_sequence_update(seq); return(md_size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Make CBC decoding constant time. This patch makes the decoding of SSLv3 and TLS CBC records constant time. Without this, a timing side-channel can be used to build a padding oracle and mount Vaudenay's attack. This patch also disables the stitched AESNI+SHA mode pending a similar fix to that code. In order to be easy to backport, this change is implemented in ssl/, rather than as a generic AEAD mode. In the future this should be changed around so that HMAC isn't in ssl/, but crypto/ as FIPS expects. (cherry picked from commit e130841bccfc0bb9da254dc84e23bc6a1c78a64e) Conflicts: crypto/evp/c_allc.c ssl/ssl_algs.c ssl/ssl_locl.h ssl/t1_enc.c (cherry picked from commit 3622239826698a0e534dcf0473204c724bb9b4b4) Conflicts: ssl/d1_enc.c ssl/s3_enc.c ssl/s3_pkt.c ssl/ssl3.h ssl/ssl_algs.c ssl/t1_enc.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dtls1_process_record(SSL *s) { int al; int clear=0; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; int decryption_failed_or_bad_record_mac = 0; unsigned char *mac = NULL; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; enc_err = s->method->ssl3_enc->enc(s,0); if (enc_err <= 0) { /* To minimize information leaked via timing, we will always * perform all computations before discarding the message. */ decryption_failed_or_bad_record_mac = 1; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ( (sess == NULL) || (s->enc_read_ctx == NULL) || (s->read_hash == NULL)) clear=1; if (!clear) { mac_size=EVP_MD_size(s->read_hash); if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) { #if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */ al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG); goto f_err; #else decryption_failed_or_bad_record_mac = 1; #endif } /* check the MAC for rr->input (it's in mac_size bytes at the tail) */ if (rr->length >= mac_size) { rr->length -= mac_size; mac = &rr->data[rr->length]; } else rr->length = 0; i=s->method->ssl3_enc->mac(s,md,0); if (i < 0 || mac == NULL || CRYPTO_memcmp(md,mac,mac_size) != 0) { decryption_failed_or_bad_record_mac = 1; } } if (decryption_failed_or_bad_record_mac) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /* So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */ return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fixups.'</s>
<s>[INST] Given the following code containing errors, provide 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 dtls1_enc(SSL *s, int send) { SSL3_RECORD *rec; EVP_CIPHER_CTX *ds; unsigned long l; int bs,i,j,k,mac_size=0; const EVP_CIPHER *enc; if (send) { if (s->write_hash) { mac_size=EVP_MD_size(s->write_hash); if (mac_size < 0) return -1; } ds=s->enc_write_ctx; rec= &(s->s3->wrec); if (s->enc_write_ctx == NULL) enc=NULL; else { enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx); if ( rec->data != rec->input) /* we can't write into the input stream */ fprintf(stderr, "%s:%d: rec->data != rec->input\n", __FILE__, __LINE__); else if ( EVP_CIPHER_block_size(ds->cipher) > 1) { if (RAND_bytes(rec->input, EVP_CIPHER_block_size(ds->cipher)) <= 0) return -1; } } } else { if (s->read_hash) { mac_size=EVP_MD_size(s->read_hash); if (mac_size < 0) return -1; } ds=s->enc_read_ctx; rec= &(s->s3->rrec); if (s->enc_read_ctx == NULL) enc=NULL; else enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx); } #ifdef KSSL_DEBUG printf("dtls1_enc(%d)\n", send); #endif /* KSSL_DEBUG */ if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) { memmove(rec->data,rec->input,rec->length); rec->input=rec->data; } else { l=rec->length; bs=EVP_CIPHER_block_size(ds->cipher); if ((bs != 1) && send) { i=bs-((int)l%bs); /* Add weird padding of upto 256 bytes */ /* we need to add 'i' padding bytes of value j */ j=i-1; if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG) { if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) j++; } for (k=(int)l; k<(int)(l+i); k++) rec->input[k]=j; l+=i; rec->length+=i; } #ifdef KSSL_DEBUG { unsigned long ui; printf("EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n", (void *)ds,rec->data,rec->input,l); printf("\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%ld %ld], %d iv_len\n", ds->buf_len, ds->cipher->key_len, (unsigned long)DES_KEY_SZ, (unsigned long)DES_SCHEDULE_SZ, ds->cipher->iv_len); printf("\t\tIV: "); for (i=0; i<ds->cipher->iv_len; i++) printf("%02X", ds->iv[i]); printf("\n"); printf("\trec->input="); for (ui=0; ui<l; ui++) printf(" %02x", rec->input[ui]); printf("\n"); } #endif /* KSSL_DEBUG */ if (!send) { if (l == 0 || l%bs != 0) return -1; } EVP_Cipher(ds,rec->data,rec->input,l); #ifdef KSSL_DEBUG { unsigned long ki; printf("\trec->data="); for (ki=0; ki<l; ki++) printf(" %02x", rec->data[ki]); printf("\n"); } #endif /* KSSL_DEBUG */ rec->orig_len = rec->length; if ((bs != 1) && !send) return tls1_cbc_remove_padding(s, rec, bs, mac_size); } return(1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Don't crash when processing a zero-length, TLS >= 1.1 record. The previous CBC patch was bugged in that there was a path through enc() in s3_pkt.c/d1_pkt.c which didn't set orig_len. orig_len would be left at the previous value which could suggest that the packet was a sufficient length when it wasn't. (cherry picked from commit 6cb19b7681f600b2f165e4adc57547b097b475fd) (cherry picked from commit 2c948c1bb218f4ae126e14fd3453d42c62b93235) Conflicts: ssl/s3_enc.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void ssl3_cbc_digest_record( const EVP_MD *digest, unsigned char* md_out, size_t* md_out_size, const unsigned char header[13], const unsigned char *data, size_t data_plus_mac_size, size_t data_plus_mac_plus_padding_size, const unsigned char *mac_secret, unsigned mac_secret_length, char is_sslv3) { unsigned char md_state[sizeof(SHA512_CTX)]; void (*md_final_raw)(void *ctx, unsigned char *md_out); void (*md_transform)(void *ctx, const unsigned char *block); unsigned md_size, md_block_size = 64; unsigned sslv3_pad_length = 40, header_length, variance_blocks, len, max_mac_bytes, num_blocks, num_starting_blocks, k, mac_end_offset, c, index_a, index_b; uint64_t bits; unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES]; /* hmac_pad is the masked HMAC key. */ unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE]; unsigned char first_block[MAX_HASH_BLOCK_SIZE]; unsigned char mac_out[EVP_MAX_MD_SIZE]; unsigned i, j, md_out_size_u; EVP_MD_CTX md_ctx; /* mdLengthSize is the number of bytes in the length field that terminates * the hash. */ unsigned md_length_size = 8; /* This is a, hopefully redundant, check that allows us to forget about * many possible overflows later in this function. */ OPENSSL_assert(data_plus_mac_plus_padding_size < 1024*1024); switch (digest->type) { case NID_md5: MD5_Init((MD5_CTX*)md_state); md_final_raw = tls1_md5_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) MD5_Transform; md_size = 16; sslv3_pad_length = 48; break; case NID_sha1: SHA1_Init((SHA_CTX*)md_state); md_final_raw = tls1_sha1_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA1_Transform; md_size = 20; break; case NID_sha224: SHA224_Init((SHA256_CTX*)md_state); md_final_raw = tls1_sha256_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform; md_size = 224/8; break; case NID_sha256: SHA256_Init((SHA256_CTX*)md_state); md_final_raw = tls1_sha256_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform; md_size = 32; break; case NID_sha384: SHA384_Init((SHA512_CTX*)md_state); md_final_raw = tls1_sha512_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform; md_size = 384/8; md_block_size = 128; md_length_size = 16; break; case NID_sha512: SHA512_Init((SHA512_CTX*)md_state); md_final_raw = tls1_sha512_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform; md_size = 64; md_block_size = 128; md_length_size = 16; break; default: /* ssl3_cbc_record_digest_supported should have been * called first to check that the hash function is * supported. */ OPENSSL_assert(0); if (md_out_size) *md_out_size = -1; return; } OPENSSL_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES); OPENSSL_assert(md_block_size <= MAX_HASH_BLOCK_SIZE); OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE); header_length = 13; if (is_sslv3) { header_length = mac_secret_length + sslv3_pad_length + 8 /* sequence number */ + 1 /* record type */ + 2 /* record length */; } /* variance_blocks is the number of blocks of the hash that we have to * calculate in constant time because they could be altered by the * padding value. * * In SSLv3, the padding must be minimal so the end of the plaintext * varies by, at most, 15+20 = 35 bytes. (We conservatively assume that * the MAC size varies from 0..20 bytes.) In case the 9 bytes of hash * termination (0x80 + 64-bit length) don't fit in the final block, we * say that the final two blocks can vary based on the padding. * * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not * required to be minimal. Therefore we say that the final six blocks * can vary based on the padding. * * Later in the function, if the message is short and there obviously * cannot be this many blocks then variance_blocks can be reduced. */ variance_blocks = is_sslv3 ? 2 : 6; /* From now on we're dealing with the MAC, which conceptually has 13 * bytes of `header' before the start of the data (TLS) or 71/75 bytes * (SSLv3) */ len = data_plus_mac_plus_padding_size + header_length; /* max_mac_bytes contains the maximum bytes of bytes in the MAC, including * |header|, assuming that there's no padding. */ max_mac_bytes = len - md_size - 1; /* num_blocks is the maximum number of hash blocks. */ num_blocks = (max_mac_bytes + 1 + md_length_size + md_block_size - 1) / md_block_size; /* In order to calculate the MAC in constant time we have to handle * the final blocks specially because the padding value could cause the * end to appear somewhere in the final |variance_blocks| blocks and we * can't leak where. However, |num_starting_blocks| worth of data can * be hashed right away because no padding value can affect whether * they are plaintext. */ num_starting_blocks = 0; /* k is the starting byte offset into the conceptual header||data where * we start processing. */ k = 0; /* mac_end_offset is the index just past the end of the data to be * MACed. */ mac_end_offset = data_plus_mac_size + header_length - md_size; /* c is the index of the 0x80 byte in the final hash block that * contains application data. */ c = mac_end_offset % md_block_size; /* index_a is the hash block number that contains the 0x80 terminating * value. */ index_a = mac_end_offset / md_block_size; /* index_b is the hash block number that contains the 64-bit hash * length, in bits. */ index_b = (mac_end_offset + md_length_size) / md_block_size; /* bits is the hash-length in bits. It includes the additional hash * block for the masked HMAC key, or whole of |header| in the case of * SSLv3. */ /* For SSLv3, if we're going to have any starting blocks then we need * at least two because the header is larger than a single block. */ if (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0)) { num_starting_blocks = num_blocks - variance_blocks; k = md_block_size*num_starting_blocks; } bits = 8*mac_end_offset; if (!is_sslv3) { /* Compute the initial HMAC block. For SSLv3, the padding and * secret bytes are included in |header| because they take more * than a single block. */ bits += 8*md_block_size; memset(hmac_pad, 0, md_block_size); OPENSSL_assert(mac_secret_length <= sizeof(hmac_pad)); memcpy(hmac_pad, mac_secret, mac_secret_length); for (i = 0; i < md_block_size; i++) hmac_pad[i] ^= 0x36; md_transform(md_state, hmac_pad); } j = 0; if (md_length_size == 16) { memset(length_bytes, 0, 8); j = 8; } for (i = 0; i < 8; i++) length_bytes[i+j] = bits >> (8*(7-i)); if (k > 0) { if (is_sslv3) { /* The SSLv3 header is larger than a single block. * overhang is the number of bytes beyond a single * block that the header consumes: either 7 bytes * (SHA1) or 11 bytes (MD5). */ unsigned overhang = header_length-md_block_size; md_transform(md_state, header); memcpy(first_block, header + md_block_size, overhang); memcpy(first_block + overhang, data, md_block_size-overhang); md_transform(md_state, first_block); for (i = 1; i < k/md_block_size - 1; i++) md_transform(md_state, data + md_block_size*i - overhang); } else { /* k is a multiple of md_block_size. */ memcpy(first_block, header, 13); memcpy(first_block+13, data, md_block_size-13); md_transform(md_state, first_block); for (i = 1; i < k/md_block_size; i++) md_transform(md_state, data + md_block_size*i - 13); } } memset(mac_out, 0, sizeof(mac_out)); /* We now process the final hash blocks. For each block, we construct * it in constant time. If the |i==index_a| then we'll include the 0x80 * bytes and zero pad etc. For each block we selectively copy it, in * constant time, to |mac_out|. */ for (i = num_starting_blocks; i <= num_starting_blocks+variance_blocks; i++) { unsigned char block[MAX_HASH_BLOCK_SIZE]; unsigned char is_block_a = constant_time_eq_8(i, index_a); unsigned char is_block_b = constant_time_eq_8(i, index_b); for (j = 0; j < md_block_size; j++) { unsigned char b = 0, is_past_c, is_past_cp1; if (k < header_length) b = header[k]; else if (k < data_plus_mac_plus_padding_size + header_length) b = data[k-header_length]; k++; is_past_c = is_block_a & constant_time_ge(j, c); is_past_cp1 = is_block_a & constant_time_ge(j, c+1); /* If this is the block containing the end of the * application data, and we are at the offset for the * 0x80 value, then overwrite b with 0x80. */ b = (b&~is_past_c) | (0x80&is_past_c); /* If this the the block containing the end of the * application data and we're past the 0x80 value then * just write zero. */ b = b&~is_past_cp1; /* If this is index_b (the final block), but not * index_a (the end of the data), then the 64-bit * length didn't fit into index_a and we're having to * add an extra block of zeros. */ b &= ~is_block_b | is_block_a; /* The final bytes of one of the blocks contains the * length. */ if (j >= md_block_size - md_length_size) { /* If this is index_b, write a length byte. */ b = (b&~is_block_b) | (is_block_b&length_bytes[j-(md_block_size-md_length_size)]); } block[j] = b; } md_transform(md_state, block); md_final_raw(md_state, block); /* If this is index_b, copy the hash value to |mac_out|. */ for (j = 0; j < md_size; j++) mac_out[j] |= block[j]&is_block_b; } EVP_MD_CTX_init(&md_ctx); EVP_DigestInit_ex(&md_ctx, digest, NULL /* engine */); if (is_sslv3) { /* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */ memset(hmac_pad, 0x5c, sslv3_pad_length); EVP_DigestUpdate(&md_ctx, mac_secret, mac_secret_length); EVP_DigestUpdate(&md_ctx, hmac_pad, sslv3_pad_length); EVP_DigestUpdate(&md_ctx, mac_out, md_size); } else { /* Complete the HMAC in the standard manner. */ for (i = 0; i < md_block_size; i++) hmac_pad[i] ^= 0x6a; EVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size); EVP_DigestUpdate(&md_ctx, mac_out, md_size); } EVP_DigestFinal(&md_ctx, md_out, &md_out_size_u); if (md_out_size) *md_out_size = md_out_size_u; EVP_MD_CTX_cleanup(&md_ctx); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Don't access EVP_MD internals directly.'</s>
<s>[INST] Given the following code containing errors, provide 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 tls1_mac(SSL *ssl, unsigned char *md, int send) { SSL3_RECORD *rec; unsigned char *seq; EVP_MD_CTX *hash; size_t md_size; int i; EVP_MD_CTX hmac, *mac_ctx; unsigned char buf[5]; int stream_mac = (send?(ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM):(ssl->mac_flags&SSL_MAC_FLAG_READ_MAC_STREAM)); int t; if (send) { rec= &(ssl->s3->wrec); seq= &(ssl->s3->write_sequence[0]); hash=ssl->write_hash; } else { rec= &(ssl->s3->rrec); seq= &(ssl->s3->read_sequence[0]); hash=ssl->read_hash; } t=EVP_MD_CTX_size(hash); OPENSSL_assert(t >= 0); md_size=t; buf[0]=rec->type; buf[1]=(unsigned char)(ssl->version>>8); buf[2]=(unsigned char)(ssl->version); buf[3]=rec->length>>8; buf[4]=rec->length&0xff; /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */ if (stream_mac) { mac_ctx = hash; } else { EVP_MD_CTX_copy(&hmac,hash); mac_ctx = &hmac; } if (ssl->version == DTLS1_VERSION || ssl->version == DTLS1_BAD_VER) { unsigned char dtlsseq[8],*p=dtlsseq; s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p); memcpy (p,&seq[2],6); EVP_DigestSignUpdate(mac_ctx,dtlsseq,8); } else EVP_DigestSignUpdate(mac_ctx,seq,8); EVP_DigestSignUpdate(mac_ctx,buf,5); EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length); t=EVP_DigestSignFinal(mac_ctx,md,&md_size); OPENSSL_assert(t > 0); if (!stream_mac) EVP_MD_CTX_cleanup(&hmac); #ifdef TLS_DEBUG printf("sec="); {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",mac_sec[z]); printf("\n"); } printf("seq="); {int z; for (z=0; z<8; z++) printf("%02X ",seq[z]); printf("\n"); } printf("buf="); {int z; for (z=0; z<5; z++) printf("%02X ",buf[z]); printf("\n"); } printf("rec="); {unsigned int z; for (z=0; z<rec->length; z++) printf("%02X ",buf[z]); printf("\n"); } #endif if (ssl->version != DTLS1_VERSION && ssl->version != DTLS1_BAD_VER) { for (i=7; i>=0; i--) { ++seq[i]; if (seq[i] != 0) break; } } #ifdef TLS_DEBUG {unsigned int z; for (z=0; z<md_size; z++) printf("%02X ",md[z]); printf("\n"); } #endif return(md_size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Make CBC decoding constant time. This patch makes the decoding of SSLv3 and TLS CBC records constant time. Without this, a timing side-channel can be used to build a padding oracle and mount Vaudenay's attack. This patch also disables the stitched AESNI+SHA mode pending a similar fix to that code. In order to be easy to backport, this change is implemented in ssl/, rather than as a generic AEAD mode. In the future this should be changed around so that HMAC isn't in ssl/, but crypto/ as FIPS expects. (cherry picked from commit e130841bccfc0bb9da254dc84e23bc6a1c78a64e) Conflicts: crypto/evp/c_allc.c ssl/ssl_algs.c ssl/ssl_locl.h ssl/t1_enc.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dtls1_process_record(SSL *s) { int i,al; int clear=0; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; int decryption_failed_or_bad_record_mac = 0; unsigned char *mac = NULL; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; enc_err = s->method->ssl3_enc->enc(s,0); if (enc_err <= 0) { /* To minimize information leaked via timing, we will always * perform all computations before discarding the message. */ decryption_failed_or_bad_record_mac = 1; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ( (sess == NULL) || (s->enc_read_ctx == NULL) || (s->read_hash == NULL)) clear=1; if (!clear) { /* !clear => s->read_hash != NULL => mac_size != -1 */ int t; t=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(t >= 0); mac_size=t; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) { #if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */ al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG); goto f_err; #else decryption_failed_or_bad_record_mac = 1; #endif } /* check the MAC for rr->input (it's in mac_size bytes at the tail) */ if (rr->length >= mac_size) { rr->length -= mac_size; mac = &rr->data[rr->length]; } else rr->length = 0; i=s->method->ssl3_enc->mac(s,md,0); if (i < 0 || mac == NULL || CRYPTO_memcmp(md,mac,mac_size) != 0) { decryption_failed_or_bad_record_mac = 1; } } if (decryption_failed_or_bad_record_mac) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /* So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */ return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Don't crash when processing a zero-length, TLS >= 1.1 record. The previous CBC patch was bugged in that there was a path through enc() in s3_pkt.c/d1_pkt.c which didn't set orig_len. orig_len would be left at the previous value which could suggest that the packet was a sufficient length when it wasn't. (cherry picked from commit 6cb19b7681f600b2f165e4adc57547b097b475fd)'</s>
<s>[INST] Given the following code containing errors, provide 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 ssl3_cbc_digest_record( const EVP_MD_CTX *ctx, unsigned char* md_out, size_t* md_out_size, const unsigned char header[13], const unsigned char *data, size_t data_plus_mac_size, size_t data_plus_mac_plus_padding_size, const unsigned char *mac_secret, unsigned mac_secret_length, char is_sslv3) { union { double align; unsigned char c[sizeof(SHA512_CTX)]; } md_state; void (*md_final_raw)(void *ctx, unsigned char *md_out); void (*md_transform)(void *ctx, const unsigned char *block); unsigned md_size, md_block_size = 64; unsigned sslv3_pad_length = 40, header_length, variance_blocks, len, max_mac_bytes, num_blocks, num_starting_blocks, k, mac_end_offset, c, index_a, index_b; unsigned int bits; /* at most 18 bits */ unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES]; /* hmac_pad is the masked HMAC key. */ unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE]; unsigned char first_block[MAX_HASH_BLOCK_SIZE]; unsigned char mac_out[EVP_MAX_MD_SIZE]; unsigned i, j, md_out_size_u; EVP_MD_CTX md_ctx; /* mdLengthSize is the number of bytes in the length field that terminates * the hash. */ unsigned md_length_size = 8; /* This is a, hopefully redundant, check that allows us to forget about * many possible overflows later in this function. */ OPENSSL_assert(data_plus_mac_plus_padding_size < 1024*1024); switch (ctx->digest->type) { case NID_md5: MD5_Init((MD5_CTX*)md_state.c); md_final_raw = tls1_md5_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) MD5_Transform; md_size = 16; sslv3_pad_length = 48; break; case NID_sha1: SHA1_Init((SHA_CTX*)md_state.c); md_final_raw = tls1_sha1_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA1_Transform; md_size = 20; break; case NID_sha224: SHA224_Init((SHA256_CTX*)md_state.c); md_final_raw = tls1_sha256_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform; md_size = 224/8; break; case NID_sha256: SHA256_Init((SHA256_CTX*)md_state.c); md_final_raw = tls1_sha256_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA256_Transform; md_size = 32; break; case NID_sha384: SHA384_Init((SHA512_CTX*)md_state.c); md_final_raw = tls1_sha512_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform; md_size = 384/8; md_block_size = 128; md_length_size = 16; break; case NID_sha512: SHA512_Init((SHA512_CTX*)md_state.c); md_final_raw = tls1_sha512_final_raw; md_transform = (void(*)(void *ctx, const unsigned char *block)) SHA512_Transform; md_size = 64; md_block_size = 128; md_length_size = 16; break; default: /* ssl3_cbc_record_digest_supported should have been * called first to check that the hash function is * supported. */ OPENSSL_assert(0); if (md_out_size) *md_out_size = -1; return; } OPENSSL_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES); OPENSSL_assert(md_block_size <= MAX_HASH_BLOCK_SIZE); OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE); header_length = 13; if (is_sslv3) { header_length = mac_secret_length + sslv3_pad_length + 8 /* sequence number */ + 1 /* record type */ + 2 /* record length */; } /* variance_blocks is the number of blocks of the hash that we have to * calculate in constant time because they could be altered by the * padding value. * * In SSLv3, the padding must be minimal so the end of the plaintext * varies by, at most, 15+20 = 35 bytes. (We conservatively assume that * the MAC size varies from 0..20 bytes.) In case the 9 bytes of hash * termination (0x80 + 64-bit length) don't fit in the final block, we * say that the final two blocks can vary based on the padding. * * TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not * required to be minimal. Therefore we say that the final six blocks * can vary based on the padding. * * Later in the function, if the message is short and there obviously * cannot be this many blocks then variance_blocks can be reduced. */ variance_blocks = is_sslv3 ? 2 : 6; /* From now on we're dealing with the MAC, which conceptually has 13 * bytes of `header' before the start of the data (TLS) or 71/75 bytes * (SSLv3) */ len = data_plus_mac_plus_padding_size + header_length; /* max_mac_bytes contains the maximum bytes of bytes in the MAC, including * |header|, assuming that there's no padding. */ max_mac_bytes = len - md_size - 1; /* num_blocks is the maximum number of hash blocks. */ num_blocks = (max_mac_bytes + 1 + md_length_size + md_block_size - 1) / md_block_size; /* In order to calculate the MAC in constant time we have to handle * the final blocks specially because the padding value could cause the * end to appear somewhere in the final |variance_blocks| blocks and we * can't leak where. However, |num_starting_blocks| worth of data can * be hashed right away because no padding value can affect whether * they are plaintext. */ num_starting_blocks = 0; /* k is the starting byte offset into the conceptual header||data where * we start processing. */ k = 0; /* mac_end_offset is the index just past the end of the data to be * MACed. */ mac_end_offset = data_plus_mac_size + header_length - md_size; /* c is the index of the 0x80 byte in the final hash block that * contains application data. */ c = mac_end_offset % md_block_size; /* index_a is the hash block number that contains the 0x80 terminating * value. */ index_a = mac_end_offset / md_block_size; /* index_b is the hash block number that contains the 64-bit hash * length, in bits. */ index_b = (mac_end_offset + md_length_size) / md_block_size; /* bits is the hash-length in bits. It includes the additional hash * block for the masked HMAC key, or whole of |header| in the case of * SSLv3. */ /* For SSLv3, if we're going to have any starting blocks then we need * at least two because the header is larger than a single block. */ if (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0)) { num_starting_blocks = num_blocks - variance_blocks; k = md_block_size*num_starting_blocks; } bits = 8*mac_end_offset; if (!is_sslv3) { /* Compute the initial HMAC block. For SSLv3, the padding and * secret bytes are included in |header| because they take more * than a single block. */ bits += 8*md_block_size; memset(hmac_pad, 0, md_block_size); OPENSSL_assert(mac_secret_length <= sizeof(hmac_pad)); memcpy(hmac_pad, mac_secret, mac_secret_length); for (i = 0; i < md_block_size; i++) hmac_pad[i] ^= 0x36; md_transform(md_state.c, hmac_pad); } memset(length_bytes,0,md_length_size-4); length_bytes[md_length_size-4] = (unsigned char)(bits>>24); length_bytes[md_length_size-3] = (unsigned char)(bits>>16); length_bytes[md_length_size-2] = (unsigned char)(bits>>8); length_bytes[md_length_size-1] = (unsigned char)bits; if (k > 0) { if (is_sslv3) { /* The SSLv3 header is larger than a single block. * overhang is the number of bytes beyond a single * block that the header consumes: either 7 bytes * (SHA1) or 11 bytes (MD5). */ unsigned overhang = header_length-md_block_size; md_transform(md_state.c, header); memcpy(first_block, header + md_block_size, overhang); memcpy(first_block + overhang, data, md_block_size-overhang); md_transform(md_state.c, first_block); for (i = 1; i < k/md_block_size - 1; i++) md_transform(md_state.c, data + md_block_size*i - overhang); } else { /* k is a multiple of md_block_size. */ memcpy(first_block, header, 13); memcpy(first_block+13, data, md_block_size-13); md_transform(md_state.c, first_block); for (i = 1; i < k/md_block_size; i++) md_transform(md_state.c, data + md_block_size*i - 13); } } memset(mac_out, 0, sizeof(mac_out)); /* We now process the final hash blocks. For each block, we construct * it in constant time. If the |i==index_a| then we'll include the 0x80 * bytes and zero pad etc. For each block we selectively copy it, in * constant time, to |mac_out|. */ for (i = num_starting_blocks; i <= num_starting_blocks+variance_blocks; i++) { unsigned char block[MAX_HASH_BLOCK_SIZE]; unsigned char is_block_a = constant_time_eq_8(i, index_a); unsigned char is_block_b = constant_time_eq_8(i, index_b); for (j = 0; j < md_block_size; j++) { unsigned char b = 0, is_past_c, is_past_cp1; if (k < header_length) b = header[k]; else if (k < data_plus_mac_plus_padding_size + header_length) b = data[k-header_length]; k++; is_past_c = is_block_a & constant_time_ge(j, c); is_past_cp1 = is_block_a & constant_time_ge(j, c+1); /* If this is the block containing the end of the * application data, and we are at the offset for the * 0x80 value, then overwrite b with 0x80. */ b = (b&~is_past_c) | (0x80&is_past_c); /* If this the the block containing the end of the * application data and we're past the 0x80 value then * just write zero. */ b = b&~is_past_cp1; /* If this is index_b (the final block), but not * index_a (the end of the data), then the 64-bit * length didn't fit into index_a and we're having to * add an extra block of zeros. */ b &= ~is_block_b | is_block_a; /* The final bytes of one of the blocks contains the * length. */ if (j >= md_block_size - md_length_size) { /* If this is index_b, write a length byte. */ b = (b&~is_block_b) | (is_block_b&length_bytes[j-(md_block_size-md_length_size)]); } block[j] = b; } md_transform(md_state.c, block); md_final_raw(md_state.c, block); /* If this is index_b, copy the hash value to |mac_out|. */ for (j = 0; j < md_size; j++) mac_out[j] |= block[j]&is_block_b; } EVP_MD_CTX_init(&md_ctx); EVP_DigestInit_ex(&md_ctx, ctx->digest, NULL /* engine */); if (is_sslv3) { /* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */ memset(hmac_pad, 0x5c, sslv3_pad_length); EVP_DigestUpdate(&md_ctx, mac_secret, mac_secret_length); EVP_DigestUpdate(&md_ctx, hmac_pad, sslv3_pad_length); EVP_DigestUpdate(&md_ctx, mac_out, md_size); } else { /* Complete the HMAC in the standard manner. */ for (i = 0; i < md_block_size; i++) hmac_pad[i] ^= 0x6a; EVP_DigestUpdate(&md_ctx, hmac_pad, md_block_size); EVP_DigestUpdate(&md_ctx, mac_out, md_size); } EVP_DigestFinal(&md_ctx, md_out, &md_out_size_u); if (md_out_size) *md_out_size = md_out_size_u; EVP_MD_CTX_cleanup(&md_ctx); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 's3/s3_cbc.c: allow for compilations with NO_SHA256|512. (cherry picked from commit d5371324d978e4096bf99b9d0fe71b2cb65d9dc8)'</s>
<s>[INST] Given the following code containing errors, provide 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 tls1_cbc_remove_padding(const SSL* s, SSL3_RECORD *rec, unsigned block_size, unsigned mac_size) { unsigned padding_length, good, to_check, i; const char has_explicit_iv = s->version >= TLS1_1_VERSION || s->version == DTLS1_VERSION; const unsigned overhead = 1 /* padding length byte */ + mac_size + (has_explicit_iv ? block_size : 0); /* These lengths are all public so we can test them in non-constant * time. */ if (overhead > rec->length) return 0; padding_length = rec->data[rec->length-1]; /* NB: if compression is in operation the first packet may not be of * even length so the padding bug check cannot be performed. This bug * workaround has been around since SSLeay so hopefully it is either * fixed now or no buggy implementation supports compression [steve] */ if ( (s->options&SSL_OP_TLS_BLOCK_PADDING_BUG) && !s->expand) { /* First packet is even in size, so check */ if ((memcmp(s->s3->read_sequence, "\0\0\0\0\0\0\0\0",8) == 0) && !(padding_length & 1)) { s->s3->flags|=TLS1_FLAGS_TLS_PADDING_BUG; } if ((s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG) && padding_length > 0) { padding_length--; } } good = constant_time_ge(rec->length, overhead+padding_length); /* The padding consists of a length byte at the end of the record and * then that many bytes of padding, all with the same value as the * length byte. Thus, with the length byte included, there are i+1 * bytes of padding. * * We can't check just |padding_length+1| bytes because that leaks * decrypted information. Therefore we always have to check the maximum * amount of padding possible. (Again, the length of the record is * public information so we can use it.) */ to_check = 255; /* maximum amount of padding. */ if (to_check > rec->length-1) to_check = rec->length-1; for (i = 0; i < to_check; i++) { unsigned char mask = constant_time_ge(padding_length, i); unsigned char b = rec->data[rec->length-1-i]; /* The final |padding_length+1| bytes should all have the value * |padding_length|. Therefore the XOR should be zero. */ good &= ~(mask&(padding_length ^ b)); } /* If any of the final |padding_length+1| bytes had the wrong value, * one or more of the lower eight bits of |good| will be cleared. We * AND the bottom 8 bits together and duplicate the result to all the * bits. */ good &= good >> 4; good &= good >> 2; good &= good >> 1; good <<= sizeof(good)*8-1; good = DUPLICATE_MSB_TO_ALL(good); padding_length = good & (padding_length+1); rec->length -= padding_length; rec->type |= padding_length<<8; /* kludge: pass padding length */ /* We can always safely skip the explicit IV. We check at the beginning * of this function that the record has at least enough space for the * IV, MAC and padding length byte. (These can be checked in * non-constant time because it's all public information.) So, if the * padding was invalid, then we didn't change |rec->length| and this is * safe. If the padding was valid then we know that we have at least * overhead+padding_length bytes of space and so this is still safe * because overhead accounts for the explicit IV. */ if (has_explicit_iv) { rec->data += block_size; rec->input += block_size; rec->length -= block_size; } return (int)((good & 1) | (~good & -1)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'e_aes_cbc_hmac_sha1.c: address the CBC decrypt timing issues. Address CBC decrypt timing issues and reenable the AESNI+SHA1 stitch.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dtls1_hm_fragment_free(hm_fragment *frag) { if (frag->fragment) OPENSSL_free(frag->fragment); if (frag->reassembly) OPENSSL_free(frag->reassembly); OPENSSL_free(frag); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix DTLS retransmission from previous session. For DTLS we might need to retransmit messages from the previous session so keep a copy of write context in DTLS retransmission buffers instead of replacing it after sending CCS. CVE-2013-6450.'</s>
<s>[INST] Given the following code containing errors, provide 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 ssl3_accept(SSL *s) { BUF_MEM *buf; unsigned long l,Time=(unsigned long)time(NULL); void (*cb)(const SSL *ssl,int type,int val)=NULL; int ret= -1; int new_state,state,skip=0; RAND_add(&Time,sizeof(Time),0); ERR_clear_error(); clear_sys_error(); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; /* init things to blank */ s->in_handshake++; if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); if (s->cert == NULL) { SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET); return(-1); } for (;;) { state=s->state; switch (s->state) { case SSL_ST_RENEGOTIATE: s->new_session=1; /* s->state=SSL_ST_ACCEPT; */ case SSL_ST_BEFORE: case SSL_ST_ACCEPT: case SSL_ST_BEFORE|SSL_ST_ACCEPT: case SSL_ST_OK|SSL_ST_ACCEPT: s->server=1; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); if ((s->version>>8) != 3) { SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); return -1; } s->type=SSL_ST_ACCEPT; if (s->init_buf == NULL) { if ((buf=BUF_MEM_new()) == NULL) { ret= -1; goto end; } if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) { ret= -1; goto end; } s->init_buf=buf; } if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } s->init_num=0; s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE; if (s->state != SSL_ST_RENEGOTIATE) { /* Ok, we now need to push on a buffering BIO so that * the output is sent in a way that TCP likes :-) */ if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; } ssl3_init_finished_mac(s); s->state=SSL3_ST_SR_CLNT_HELLO_A; s->ctx->stats.sess_accept++; } else if (!s->s3->send_connection_binding && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { /* Server attempting to renegotiate with * client that doesn't support secure * renegotiation. */ SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); ret = -1; goto end; } else { /* s->state == SSL_ST_RENEGOTIATE, * we will just send a HelloRequest */ s->ctx->stats.sess_accept_renegotiate++; s->state=SSL3_ST_SW_HELLO_REQ_A; } break; case SSL3_ST_SW_HELLO_REQ_A: case SSL3_ST_SW_HELLO_REQ_B: s->shutdown=0; ret=ssl3_send_hello_request(s); if (ret <= 0) goto end; s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C; s->state=SSL3_ST_SW_FLUSH; s->init_num=0; ssl3_init_finished_mac(s); break; case SSL3_ST_SW_HELLO_REQ_C: s->state=SSL_ST_OK; break; case SSL3_ST_SR_CLNT_HELLO_A: case SSL3_ST_SR_CLNT_HELLO_B: case SSL3_ST_SR_CLNT_HELLO_C: s->shutdown=0; ret=ssl3_get_client_hello(s); if (ret <= 0) goto end; s->new_session = 2; s->state=SSL3_ST_SW_SRVR_HELLO_A; s->init_num=0; break; case SSL3_ST_SW_SRVR_HELLO_A: case SSL3_ST_SW_SRVR_HELLO_B: ret=ssl3_send_server_hello(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->hit) { if (s->tlsext_ticket_expected) s->state=SSL3_ST_SW_SESSION_TICKET_A; else s->state=SSL3_ST_SW_CHANGE_A; } #else if (s->hit) s->state=SSL3_ST_SW_CHANGE_A; #endif else s->state=SSL3_ST_SW_CERT_A; s->init_num=0; break; case SSL3_ST_SW_CERT_A: case SSL3_ST_SW_CERT_B: /* Check if it is anon DH or anon ECDH or KRB5 */ if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL) && !(s->s3->tmp.new_cipher->algorithms & SSL_aKRB5)) { ret=ssl3_send_server_certificate(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_status_expected) s->state=SSL3_ST_SW_CERT_STATUS_A; else s->state=SSL3_ST_SW_KEY_EXCH_A; } else { skip = 1; s->state=SSL3_ST_SW_KEY_EXCH_A; } #else } else skip=1; s->state=SSL3_ST_SW_KEY_EXCH_A; #endif s->init_num=0; break; case SSL3_ST_SW_KEY_EXCH_A: case SSL3_ST_SW_KEY_EXCH_B: l=s->s3->tmp.new_cipher->algorithms; /* clear this, it may get reset by * send_server_key_exchange */ if ((s->options & SSL_OP_EPHEMERAL_RSA) #ifndef OPENSSL_NO_KRB5 && !(l & SSL_KRB5) #endif /* OPENSSL_NO_KRB5 */ ) /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key * even when forbidden by protocol specs * (handshake may fail as clients are not required to * be able to handle this) */ s->s3->tmp.use_rsa_tmp=1; else s->s3->tmp.use_rsa_tmp=0; /* only send if a DH key exchange, fortezza or * RSA but we have a sign only certificate * * For ECC ciphersuites, we send a serverKeyExchange * message only if the cipher suite is either * ECDH-anon or ECDHE. In other cases, the * server certificate contains the server's * public key for key exchange. */ if (s->s3->tmp.use_rsa_tmp || (l & SSL_kECDHE) || (l & (SSL_DH|SSL_kFZA)) || ((l & SSL_kRSA) && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) ) ) ) ) { ret=ssl3_send_server_key_exchange(s); if (ret <= 0) goto end; } else skip=1; s->state=SSL3_ST_SW_CERT_REQ_A; s->init_num=0; break; case SSL3_ST_SW_CERT_REQ_A: case SSL3_ST_SW_CERT_REQ_B: if (/* don't request cert unless asked for it: */ !(s->verify_mode & SSL_VERIFY_PEER) || /* if SSL_VERIFY_CLIENT_ONCE is set, * don't request cert during re-negotiation: */ ((s->session->peer != NULL) && (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || /* never request cert in anonymous ciphersuites * (see section "Certificate request" in SSL 3 drafts * and in RFC 2246): */ ((s->s3->tmp.new_cipher->algorithms & SSL_aNULL) && /* ... except when the application insists on verification * (against the specs, but s3_clnt.c accepts this for SSL 3) */ !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || /* never request cert in Kerberos ciphersuites */ (s->s3->tmp.new_cipher->algorithms & SSL_aKRB5)) { /* no cert request */ skip=1; s->s3->tmp.cert_request=0; s->state=SSL3_ST_SW_SRVR_DONE_A; } else { s->s3->tmp.cert_request=1; ret=ssl3_send_certificate_request(s); if (ret <= 0) goto end; #ifndef NETSCAPE_HANG_BUG s->state=SSL3_ST_SW_SRVR_DONE_A; #else s->state=SSL3_ST_SW_FLUSH; s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; #endif s->init_num=0; } break; case SSL3_ST_SW_SRVR_DONE_A: case SSL3_ST_SW_SRVR_DONE_B: ret=ssl3_send_server_done(s); if (ret <= 0) goto end; s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; s->state=SSL3_ST_SW_FLUSH; s->init_num=0; break; case SSL3_ST_SW_FLUSH: /* This code originally checked to see if * any data was pending using BIO_CTRL_INFO * and then flushed. This caused problems * as documented in PR#1939. The proposed * fix doesn't completely resolve this issue * as buggy implementations of BIO_CTRL_PENDING * still exist. So instead we just flush * unconditionally. */ s->rwstate=SSL_WRITING; if (BIO_flush(s->wbio) <= 0) { ret= -1; goto end; } s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; break; case SSL3_ST_SR_CERT_A: case SSL3_ST_SR_CERT_B: /* Check for second client hello (MS SGC) */ ret = ssl3_check_client_hello(s); if (ret <= 0) goto end; if (ret == 2) s->state = SSL3_ST_SR_CLNT_HELLO_C; else { if (s->s3->tmp.cert_request) { ret=ssl3_get_client_certificate(s); if (ret <= 0) goto end; } s->init_num=0; s->state=SSL3_ST_SR_KEY_EXCH_A; } break; case SSL3_ST_SR_KEY_EXCH_A: case SSL3_ST_SR_KEY_EXCH_B: ret=ssl3_get_client_key_exchange(s); if (ret <= 0) goto end; if (ret == 2) { /* For the ECDH ciphersuites when * the client sends its ECDH pub key in * a certificate, the CertificateVerify * message is not sent. */ s->state=SSL3_ST_SR_FINISHED_A; s->init_num = 0; } else { s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; /* We need to get hashes here so if there is * a client cert, it can be verified */ s->method->ssl3_enc->cert_verify_mac(s, &(s->s3->finish_dgst1), &(s->s3->tmp.cert_verify_md[0])); s->method->ssl3_enc->cert_verify_mac(s, &(s->s3->finish_dgst2), &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH])); } break; case SSL3_ST_SR_CERT_VRFY_A: case SSL3_ST_SR_CERT_VRFY_B: /* we should decide if we expected this one */ ret=ssl3_get_cert_verify(s); if (ret <= 0) goto end; s->state=SSL3_ST_SR_FINISHED_A; s->init_num=0; break; case SSL3_ST_SR_FINISHED_A: case SSL3_ST_SR_FINISHED_B: ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A, SSL3_ST_SR_FINISHED_B); if (ret <= 0) goto end; if (s->hit) s->state=SSL_ST_OK; #ifndef OPENSSL_NO_TLSEXT else if (s->tlsext_ticket_expected) s->state=SSL3_ST_SW_SESSION_TICKET_A; #endif else s->state=SSL3_ST_SW_CHANGE_A; s->init_num=0; break; #ifndef OPENSSL_NO_TLSEXT case SSL3_ST_SW_SESSION_TICKET_A: case SSL3_ST_SW_SESSION_TICKET_B: ret=ssl3_send_newsession_ticket(s); if (ret <= 0) goto end; s->state=SSL3_ST_SW_CHANGE_A; s->init_num=0; break; case SSL3_ST_SW_CERT_STATUS_A: case SSL3_ST_SW_CERT_STATUS_B: ret=ssl3_send_cert_status(s); if (ret <= 0) goto end; s->state=SSL3_ST_SW_KEY_EXCH_A; s->init_num=0; break; #endif case SSL3_ST_SW_CHANGE_A: case SSL3_ST_SW_CHANGE_B: s->session->cipher=s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) { ret= -1; goto end; } ret=ssl3_send_change_cipher_spec(s, SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B); if (ret <= 0) goto end; s->state=SSL3_ST_SW_FINISHED_A; s->init_num=0; if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) { ret= -1; goto end; } break; case SSL3_ST_SW_FINISHED_A: case SSL3_ST_SW_FINISHED_B: ret=ssl3_send_finished(s, SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B, s->method->ssl3_enc->server_finished_label, s->method->ssl3_enc->server_finished_label_len); if (ret <= 0) goto end; s->state=SSL3_ST_SW_FLUSH; if (s->hit) s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; else s->s3->tmp.next_state=SSL_ST_OK; s->init_num=0; break; case SSL_ST_OK: /* clean a few things up */ ssl3_cleanup_key_block(s); BUF_MEM_free(s->init_buf); s->init_buf=NULL; /* remove buffering on output */ ssl_free_wbio_buffer(s); s->init_num=0; if (s->new_session == 2) /* skipped if we just sent a HelloRequest */ { /* actually not necessarily a 'new' session unless * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */ s->new_session=0; ssl_update_cache(s,SSL_SESS_CACHE_SERVER); s->ctx->stats.sess_accept_good++; /* s->server=1; */ s->handshake_func=ssl3_accept; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); } ret = 1; goto end; /* break; */ default: SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE); ret= -1; goto end; /* break; */ } if (!s->s3->tmp.reuse_message && !skip) { if (s->debug) { if ((ret=BIO_flush(s->wbio)) <= 0) goto end; } if ((cb != NULL) && (s->state != state)) { new_state=s->state; s->state=state; cb(s,SSL_CB_ACCEPT_LOOP,1); s->state=new_state; } } skip=0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-326'], 'message': 'Fix for CVE-2014-0224 Only accept change cipher spec when it is expected instead of at any time. This prevents premature setting of session keys before the master secret is determined which an attacker could use as a MITM attack. Thanks to KIKUCHI Masashi (Lepidum Co. Ltd.) for reporting this issue and providing the initial fix this patch is based on.'</s>
<s>[INST] Given the following code containing errors, provide 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 OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name) { int i,n=0,len,nid, first, use_bn; BIGNUM *bl; unsigned long l; const unsigned char *p; char tbuf[DECIMAL_SIZE(i)+DECIMAL_SIZE(l)+2]; if ((a == NULL) || (a->data == NULL)) { buf[0]='\0'; return(0); } if (!no_name && (nid=OBJ_obj2nid(a)) != NID_undef) { const char *s; s=OBJ_nid2ln(nid); if (s == NULL) s=OBJ_nid2sn(nid); if (s) { if (buf) BUF_strlcpy(buf,s,buf_len); n=strlen(s); return n; } } len=a->length; p=a->data; first = 1; bl = NULL; while (len > 0) { l=0; use_bn = 0; for (;;) { unsigned char c = *p++; len--; if ((len == 0) && (c & 0x80)) goto err; if (use_bn) { if (!BN_add_word(bl, c & 0x7f)) goto err; } else l |= c & 0x7f; if (!(c & 0x80)) break; if (!use_bn && (l > (ULONG_MAX >> 7L))) { if (!bl && !(bl = BN_new())) goto err; if (!BN_set_word(bl, l)) goto err; use_bn = 1; } if (use_bn) { if (!BN_lshift(bl, bl, 7)) goto err; } else l<<=7L; } if (first) { first = 0; if (l >= 80) { i = 2; if (use_bn) { if (!BN_sub_word(bl, 80)) goto err; } else l -= 80; } else { i=(int)(l/40); l-=(long)(i*40); } if (buf && (buf_len > 0)) { *buf++ = i + '0'; buf_len--; } n++; } if (use_bn) { char *bndec; bndec = BN_bn2dec(bl); if (!bndec) goto err; i = strlen(bndec); if (buf) { if (buf_len > 0) { *buf++ = '.'; buf_len--; } BUF_strlcpy(buf,bndec,buf_len); if (i > buf_len) { buf += buf_len; buf_len = 0; } else { buf+=i; buf_len-=i; } } n++; n += i; OPENSSL_free(bndec); } else { BIO_snprintf(tbuf,sizeof tbuf,".%lu",l); i=strlen(tbuf); if (buf && (buf_len > 0)) { BUF_strlcpy(buf,tbuf,buf_len); if (i > buf_len) { buf += buf_len; buf_len = 0; } else { buf+=i; buf_len-=i; } } n+=i; l=0; } } if (bl) BN_free(bl); return n; err: if (bl) BN_free(bl); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Fix OID handling: - Upon parsing, reject OIDs with invalid base-128 encoding. - Always NUL-terminate the destination buffer in OBJ_obj2txt printing function. CVE-2014-3508 Reviewed-by: Dr. Stephen Henson <steve@openssl.org> Reviewed-by: Kurt Roeckx <kurt@openssl.org> Reviewed-by: Tim Hudson <tjh@openssl.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: BIGNUM *SRP_Calc_u(BIGNUM *A, BIGNUM *B, BIGNUM *N) { /* k = SHA1(PAD(A) || PAD(B) ) -- tls-srp draft 8 */ BIGNUM *u; unsigned char cu[SHA_DIGEST_LENGTH]; unsigned char *cAB; EVP_MD_CTX ctxt; int longN; if ((A == NULL) ||(B == NULL) || (N == NULL)) return NULL; longN= BN_num_bytes(N); if ((cAB = OPENSSL_malloc(2*longN)) == NULL) return NULL; memset(cAB, 0, longN); EVP_MD_CTX_init(&ctxt); EVP_DigestInit_ex(&ctxt, EVP_sha1(), NULL); EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(A,cAB+longN), longN); EVP_DigestUpdate(&ctxt, cAB + BN_bn2bin(B,cAB+longN), longN); OPENSSL_free(cAB); EVP_DigestFinal_ex(&ctxt, cu, NULL); EVP_MD_CTX_cleanup(&ctxt); if (!(u = BN_bin2bn(cu, sizeof(cu), NULL))) return NULL; if (!BN_is_zero(u)) return u; BN_free(u); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix SRP buffer overrun vulnerability. Invalid parameters passed to the SRP code can be overrun an internal buffer. Add sanity check that g, A, B < N to SRP code. Thanks to Sean Devlin and Watson Ladd of Cryptography Services, NCC Group for reporting this issue.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int MAIN(int argc, char **argv) { int build_chain = 0; SSL *con=NULL; #ifndef OPENSSL_NO_KRB5 KSSL_CTX *kctx; #endif int s,k,width,state=0; char *cbuf=NULL,*sbuf=NULL,*mbuf=NULL; int cbuf_len,cbuf_off; int sbuf_len,sbuf_off; fd_set readfds,writefds; short port=PORT; int full_log=1; char *host=SSL_HOST_NAME; const char *unix_path = NULL; char *xmpphost = NULL; char *cert_file=NULL,*key_file=NULL,*chain_file=NULL; int cert_format = FORMAT_PEM, key_format = FORMAT_PEM; char *passarg = NULL, *pass = NULL; X509 *cert = NULL; EVP_PKEY *key = NULL; STACK_OF(X509) *chain = NULL; char *CApath=NULL,*CAfile=NULL; char *chCApath=NULL,*chCAfile=NULL; char *vfyCApath=NULL,*vfyCAfile=NULL; int reconnect=0,badop=0,verify=SSL_VERIFY_NONE; int crlf=0; int write_tty,read_tty,write_ssl,read_ssl,tty_on,ssl_pending; SSL_CTX *ctx=NULL; int ret=1,in_init=1,i,nbio_test=0; int starttls_proto = PROTO_OFF; int prexit = 0; X509_VERIFY_PARAM *vpm = NULL; int badarg = 0; const SSL_METHOD *meth=NULL; int socket_type=SOCK_STREAM; BIO *sbio; char *inrand=NULL; int mbuf_len=0; struct timeval timeout, *timeoutp; #ifndef OPENSSL_NO_ENGINE char *engine_id=NULL; char *ssl_client_engine_id=NULL; ENGINE *ssl_client_engine=NULL; #endif ENGINE *e=NULL; #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5) struct timeval tv; #if defined(OPENSSL_SYS_BEOS_R5) int stdin_set = 0; #endif #endif #ifndef OPENSSL_NO_TLSEXT char *servername = NULL; tlsextctx tlsextcbp = {NULL,0}; # ifndef OPENSSL_NO_NEXTPROTONEG const char *next_proto_neg_in = NULL; # endif const char *alpn_in = NULL; # define MAX_SI_TYPES 100 unsigned short serverinfo_types[MAX_SI_TYPES]; int serverinfo_types_count = 0; #endif char *sess_in = NULL; char *sess_out = NULL; struct sockaddr peer; int peerlen = sizeof(peer); int enable_timeouts = 0 ; long socket_mtu = 0; #ifndef OPENSSL_NO_JPAKE static char *jpake_secret = NULL; #define no_jpake !jpake_secret #else #define no_jpake 1 #endif #ifndef OPENSSL_NO_SRP char * srppass = NULL; int srp_lateuser = 0; SRP_ARG srp_arg = {NULL,NULL,0,0,0,1024}; #endif SSL_EXCERT *exc = NULL; SSL_CONF_CTX *cctx = NULL; STACK_OF(OPENSSL_STRING) *ssl_args = NULL; char *crl_file = NULL; int crl_format = FORMAT_PEM; int crl_download = 0; STACK_OF(X509_CRL) *crls = NULL; int sdebug = 0; meth=SSLv23_client_method(); apps_startup(); c_Pause=0; c_quiet=0; c_ign_eof=0; c_debug=0; c_msg=0; c_showcerts=0; if (bio_err == NULL) bio_err=BIO_new_fp(stderr,BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; cctx = SSL_CONF_CTX_new(); if (!cctx) goto end; SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT); SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CMDLINE); if ( ((cbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) || ((sbuf=OPENSSL_malloc(BUFSIZZ)) == NULL) || ((mbuf=OPENSSL_malloc(BUFSIZZ)) == NULL)) { BIO_printf(bio_err,"out of memory\n"); goto end; } verify_depth=0; verify_error=X509_V_OK; #ifdef FIONBIO c_nbio=0; #endif argc--; argv++; while (argc >= 1) { if (strcmp(*argv,"-host") == 0) { if (--argc < 1) goto bad; host= *(++argv); } else if (strcmp(*argv,"-port") == 0) { if (--argc < 1) goto bad; port=atoi(*(++argv)); if (port == 0) goto bad; } else if (strcmp(*argv,"-connect") == 0) { if (--argc < 1) goto bad; if (!extract_host_port(*(++argv),&host,NULL,&port)) goto bad; } else if (strcmp(*argv,"-unix") == 0) { if (--argc < 1) goto bad; unix_path = *(++argv); } else if (strcmp(*argv,"-xmpphost") == 0) { if (--argc < 1) goto bad; xmpphost= *(++argv); } else if (strcmp(*argv,"-verify") == 0) { verify=SSL_VERIFY_PEER; if (--argc < 1) goto bad; verify_depth=atoi(*(++argv)); if (!c_quiet) BIO_printf(bio_err,"verify depth is %d\n",verify_depth); } else if (strcmp(*argv,"-cert") == 0) { if (--argc < 1) goto bad; cert_file= *(++argv); } else if (strcmp(*argv,"-CRL") == 0) { if (--argc < 1) goto bad; crl_file= *(++argv); } else if (strcmp(*argv,"-crl_download") == 0) crl_download = 1; else if (strcmp(*argv,"-sess_out") == 0) { if (--argc < 1) goto bad; sess_out = *(++argv); } else if (strcmp(*argv,"-sess_in") == 0) { if (--argc < 1) goto bad; sess_in = *(++argv); } else if (strcmp(*argv,"-certform") == 0) { if (--argc < 1) goto bad; cert_format = str2fmt(*(++argv)); } else if (strcmp(*argv,"-CRLform") == 0) { if (--argc < 1) goto bad; crl_format = str2fmt(*(++argv)); } else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) { if (badarg) goto bad; continue; } else if (strcmp(*argv,"-verify_return_error") == 0) verify_return_error = 1; else if (strcmp(*argv,"-verify_quiet") == 0) verify_quiet = 1; else if (strcmp(*argv,"-brief") == 0) { c_brief = 1; verify_quiet = 1; c_quiet = 1; } else if (args_excert(&argv, &argc, &badarg, bio_err, &exc)) { if (badarg) goto bad; continue; } else if (args_ssl(&argv, &argc, cctx, &badarg, bio_err, &ssl_args)) { if (badarg) goto bad; continue; } else if (strcmp(*argv,"-prexit") == 0) prexit=1; else if (strcmp(*argv,"-crlf") == 0) crlf=1; else if (strcmp(*argv,"-quiet") == 0) { c_quiet=1; c_ign_eof=1; } else if (strcmp(*argv,"-ign_eof") == 0) c_ign_eof=1; else if (strcmp(*argv,"-no_ign_eof") == 0) c_ign_eof=0; else if (strcmp(*argv,"-pause") == 0) c_Pause=1; else if (strcmp(*argv,"-debug") == 0) c_debug=1; #ifndef OPENSSL_NO_TLSEXT else if (strcmp(*argv,"-tlsextdebug") == 0) c_tlsextdebug=1; else if (strcmp(*argv,"-status") == 0) c_status_req=1; #endif #ifdef WATT32 else if (strcmp(*argv,"-wdebug") == 0) dbug_init(); #endif else if (strcmp(*argv,"-msg") == 0) c_msg=1; else if (strcmp(*argv,"-msgfile") == 0) { if (--argc < 1) goto bad; bio_c_msg = BIO_new_file(*(++argv), "w"); } #ifndef OPENSSL_NO_SSL_TRACE else if (strcmp(*argv,"-trace") == 0) c_msg=2; #endif else if (strcmp(*argv,"-security_debug") == 0) { sdebug=1; } else if (strcmp(*argv,"-security_debug_verbose") == 0) { sdebug=2; } else if (strcmp(*argv,"-showcerts") == 0) c_showcerts=1; else if (strcmp(*argv,"-nbio_test") == 0) nbio_test=1; else if (strcmp(*argv,"-state") == 0) state=1; #ifndef OPENSSL_NO_PSK else if (strcmp(*argv,"-psk_identity") == 0) { if (--argc < 1) goto bad; psk_identity=*(++argv); } else if (strcmp(*argv,"-psk") == 0) { size_t j; if (--argc < 1) goto bad; psk_key=*(++argv); for (j = 0; j < strlen(psk_key); j++) { if (isxdigit((unsigned char)psk_key[j])) continue; BIO_printf(bio_err,"Not a hex number '%s'\n",*argv); goto bad; } } #endif #ifndef OPENSSL_NO_SRP else if (strcmp(*argv,"-srpuser") == 0) { if (--argc < 1) goto bad; srp_arg.srplogin= *(++argv); meth=TLSv1_client_method(); } else if (strcmp(*argv,"-srppass") == 0) { if (--argc < 1) goto bad; srppass= *(++argv); meth=TLSv1_client_method(); } else if (strcmp(*argv,"-srp_strength") == 0) { if (--argc < 1) goto bad; srp_arg.strength=atoi(*(++argv)); BIO_printf(bio_err,"SRP minimal length for N is %d\n",srp_arg.strength); meth=TLSv1_client_method(); } else if (strcmp(*argv,"-srp_lateuser") == 0) { srp_lateuser= 1; meth=TLSv1_client_method(); } else if (strcmp(*argv,"-srp_moregroups") == 0) { srp_arg.amp=1; meth=TLSv1_client_method(); } #endif #ifndef OPENSSL_NO_SSL2 else if (strcmp(*argv,"-ssl2") == 0) meth=SSLv2_client_method(); #endif #ifndef OPENSSL_NO_SSL3 else if (strcmp(*argv,"-ssl3") == 0) meth=SSLv3_client_method(); #endif #ifndef OPENSSL_NO_TLS1 else if (strcmp(*argv,"-tls1_2") == 0) meth=TLSv1_2_client_method(); else if (strcmp(*argv,"-tls1_1") == 0) meth=TLSv1_1_client_method(); else if (strcmp(*argv,"-tls1") == 0) meth=TLSv1_client_method(); #endif #ifndef OPENSSL_NO_DTLS1 else if (strcmp(*argv,"-dtls") == 0) { meth=DTLS_client_method(); socket_type=SOCK_DGRAM; } else if (strcmp(*argv,"-dtls1") == 0) { meth=DTLSv1_client_method(); socket_type=SOCK_DGRAM; } else if (strcmp(*argv,"-dtls1_2") == 0) { meth=DTLSv1_2_client_method(); socket_type=SOCK_DGRAM; } else if (strcmp(*argv,"-timeout") == 0) enable_timeouts=1; else if (strcmp(*argv,"-mtu") == 0) { if (--argc < 1) goto bad; socket_mtu = atol(*(++argv)); } #endif else if (strcmp(*argv,"-keyform") == 0) { if (--argc < 1) goto bad; key_format = str2fmt(*(++argv)); } else if (strcmp(*argv,"-pass") == 0) { if (--argc < 1) goto bad; passarg = *(++argv); } else if (strcmp(*argv,"-cert_chain") == 0) { if (--argc < 1) goto bad; chain_file= *(++argv); } else if (strcmp(*argv,"-key") == 0) { if (--argc < 1) goto bad; key_file= *(++argv); } else if (strcmp(*argv,"-reconnect") == 0) { reconnect=5; } else if (strcmp(*argv,"-CApath") == 0) { if (--argc < 1) goto bad; CApath= *(++argv); } else if (strcmp(*argv,"-chainCApath") == 0) { if (--argc < 1) goto bad; chCApath= *(++argv); } else if (strcmp(*argv,"-verifyCApath") == 0) { if (--argc < 1) goto bad; vfyCApath= *(++argv); } else if (strcmp(*argv,"-build_chain") == 0) build_chain = 1; else if (strcmp(*argv,"-CAfile") == 0) { if (--argc < 1) goto bad; CAfile= *(++argv); } else if (strcmp(*argv,"-chainCAfile") == 0) { if (--argc < 1) goto bad; chCAfile= *(++argv); } else if (strcmp(*argv,"-verifyCAfile") == 0) { if (--argc < 1) goto bad; vfyCAfile= *(++argv); } #ifndef OPENSSL_NO_TLSEXT # ifndef OPENSSL_NO_NEXTPROTONEG else if (strcmp(*argv,"-nextprotoneg") == 0) { if (--argc < 1) goto bad; next_proto_neg_in = *(++argv); } # endif else if (strcmp(*argv,"-alpn") == 0) { if (--argc < 1) goto bad; alpn_in = *(++argv); } else if (strcmp(*argv,"-serverinfo") == 0) { char *c; int start = 0; int len; if (--argc < 1) goto bad; c = *(++argv); serverinfo_types_count = 0; len = strlen(c); for (i = 0; i <= len; ++i) { if (i == len || c[i] == ',') { serverinfo_types[serverinfo_types_count] = atoi(c+start); serverinfo_types_count++; start = i+1; } if (serverinfo_types_count == MAX_SI_TYPES) break; } } #endif #ifdef FIONBIO else if (strcmp(*argv,"-nbio") == 0) { c_nbio=1; } #endif else if (strcmp(*argv,"-starttls") == 0) { if (--argc < 1) goto bad; ++argv; if (strcmp(*argv,"smtp") == 0) starttls_proto = PROTO_SMTP; else if (strcmp(*argv,"pop3") == 0) starttls_proto = PROTO_POP3; else if (strcmp(*argv,"imap") == 0) starttls_proto = PROTO_IMAP; else if (strcmp(*argv,"ftp") == 0) starttls_proto = PROTO_FTP; else if (strcmp(*argv, "xmpp") == 0) starttls_proto = PROTO_XMPP; else goto bad; } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv,"-engine") == 0) { if (--argc < 1) goto bad; engine_id = *(++argv); } else if (strcmp(*argv,"-ssl_client_engine") == 0) { if (--argc < 1) goto bad; ssl_client_engine_id = *(++argv); } #endif else if (strcmp(*argv,"-rand") == 0) { if (--argc < 1) goto bad; inrand= *(++argv); } #ifndef OPENSSL_NO_TLSEXT else if (strcmp(*argv,"-servername") == 0) { if (--argc < 1) goto bad; servername= *(++argv); /* meth=TLSv1_client_method(); */ } #endif #ifndef OPENSSL_NO_JPAKE else if (strcmp(*argv,"-jpake") == 0) { if (--argc < 1) goto bad; jpake_secret = *++argv; } #endif else if (strcmp(*argv,"-use_srtp") == 0) { if (--argc < 1) goto bad; srtp_profiles = *(++argv); } else if (strcmp(*argv,"-keymatexport") == 0) { if (--argc < 1) goto bad; keymatexportlabel= *(++argv); } else if (strcmp(*argv,"-keymatexportlen") == 0) { if (--argc < 1) goto bad; keymatexportlen=atoi(*(++argv)); if (keymatexportlen == 0) goto bad; } else { BIO_printf(bio_err,"unknown option %s\n",*argv); badop=1; break; } argc--; argv++; } if (badop) { bad: sc_usage(); goto end; } if (unix_path && (socket_type != SOCK_STREAM)) { BIO_printf(bio_err, "Can't use unix sockets and datagrams together\n"); goto end; } #if !defined(OPENSSL_NO_JPAKE) && !defined(OPENSSL_NO_PSK) if (jpake_secret) { if (psk_key) { BIO_printf(bio_err, "Can't use JPAKE and PSK together\n"); goto end; } psk_identity = "JPAKE"; } #endif OpenSSL_add_ssl_algorithms(); SSL_load_error_strings(); #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) next_proto.status = -1; if (next_proto_neg_in) { next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in); if (next_proto.data == NULL) { BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n"); goto end; } } else next_proto.data = NULL; #endif #ifndef OPENSSL_NO_ENGINE e = setup_engine(bio_err, engine_id, 1); if (ssl_client_engine_id) { ssl_client_engine = ENGINE_by_id(ssl_client_engine_id); if (!ssl_client_engine) { BIO_printf(bio_err, "Error getting client auth engine\n"); goto end; } } #endif if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (key_file == NULL) key_file = cert_file; if (key_file) { key = load_key(bio_err, key_file, key_format, 0, pass, e, "client certificate private key file"); if (!key) { ERR_print_errors(bio_err); goto end; } } if (cert_file) { cert = load_cert(bio_err,cert_file,cert_format, NULL, e, "client certificate file"); if (!cert) { ERR_print_errors(bio_err); goto end; } } if (chain_file) { chain = load_certs(bio_err, chain_file,FORMAT_PEM, NULL, e, "client certificate chain"); if (!chain) goto end; } if (crl_file) { X509_CRL *crl; crl = load_crl(crl_file, crl_format); if (!crl) { BIO_puts(bio_err, "Error loading CRL\n"); ERR_print_errors(bio_err); goto end; } crls = sk_X509_CRL_new_null(); if (!crls || !sk_X509_CRL_push(crls, crl)) { BIO_puts(bio_err, "Error adding CRL\n"); ERR_print_errors(bio_err); X509_CRL_free(crl); goto end; } } if (!load_excert(&exc, bio_err)) goto end; if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL && !RAND_status()) { BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n"); } if (inrand != NULL) BIO_printf(bio_err,"%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); if (bio_c_out == NULL) { if (c_quiet && !c_debug) { bio_c_out=BIO_new(BIO_s_null()); if (c_msg && !bio_c_msg) bio_c_msg=BIO_new_fp(stdout,BIO_NOCLOSE); } else { if (bio_c_out == NULL) bio_c_out=BIO_new_fp(stdout,BIO_NOCLOSE); } } #ifndef OPENSSL_NO_SRP if(!app_passwd(bio_err, srppass, NULL, &srp_arg.srppassin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } #endif ctx=SSL_CTX_new(meth); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } if (sdebug) ssl_ctx_security_debug(ctx, bio_err, sdebug); if (vpm) SSL_CTX_set1_param(ctx, vpm); if (!args_ssl_call(ctx, bio_err, cctx, ssl_args, 1, no_jpake)) { ERR_print_errors(bio_err); goto end; } if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, chCApath, chCAfile, crls, crl_download)) { BIO_printf(bio_err, "Error loading store locations\n"); ERR_print_errors(bio_err); goto end; } #ifndef OPENSSL_NO_ENGINE if (ssl_client_engine) { if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) { BIO_puts(bio_err, "Error setting client auth engine\n"); ERR_print_errors(bio_err); ENGINE_free(ssl_client_engine); goto end; } ENGINE_free(ssl_client_engine); } #endif #ifndef OPENSSL_NO_PSK #ifdef OPENSSL_NO_JPAKE if (psk_key != NULL) #else if (psk_key != NULL || jpake_secret) #endif { if (c_debug) BIO_printf(bio_c_out, "PSK key given or JPAKE in use, setting client callback\n"); SSL_CTX_set_psk_client_callback(ctx, psk_client_cb); } if (srtp_profiles != NULL) SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles); #endif if (exc) ssl_ctx_set_excert(ctx, exc); /* DTLS: partial reads end up discarding unread UDP bytes :-( * Setting read ahead solves this problem. */ if (socket_type == SOCK_DGRAM) SSL_CTX_set_read_ahead(ctx, 1); #if !defined(OPENSSL_NO_TLSEXT) # if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto.data) SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto); # endif if (alpn_in) { unsigned short alpn_len; unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in); if (alpn == NULL) { BIO_printf(bio_err, "Error parsing -alpn argument\n"); goto end; } SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len); OPENSSL_free(alpn); } #endif #ifndef OPENSSL_NO_TLSEXT for (i = 0; i < serverinfo_types_count; i++) { SSL_CTX_add_client_custom_ext(ctx, serverinfo_types[i], NULL, NULL, NULL, serverinfo_cli_parse_cb, NULL); } #endif if (state) SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback); #if 0 else SSL_CTX_set_cipher_list(ctx,getenv("SSL_CIPHER")); #endif SSL_CTX_set_verify(ctx,verify,verify_callback); if ((!SSL_CTX_load_verify_locations(ctx,CAfile,CApath)) || (!SSL_CTX_set_default_verify_paths(ctx))) { /* BIO_printf(bio_err,"error setting default verify locations\n"); */ ERR_print_errors(bio_err); /* goto end; */ } ssl_ctx_add_crls(ctx, crls, crl_download); if (!set_cert_key_stuff(ctx,cert,key,chain,build_chain)) goto end; #ifndef OPENSSL_NO_TLSEXT if (servername != NULL) { tlsextcbp.biodebug = bio_err; SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp); } #ifndef OPENSSL_NO_SRP if (srp_arg.srplogin) { if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg.srplogin)) { BIO_printf(bio_err,"Unable to set SRP username\n"); goto end; } srp_arg.msg = c_msg; srp_arg.debug = c_debug ; SSL_CTX_set_srp_cb_arg(ctx,&srp_arg); SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb); SSL_CTX_set_srp_strength(ctx, srp_arg.strength); if (c_msg || c_debug || srp_arg.amp == 0) SSL_CTX_set_srp_verify_param_callback(ctx, ssl_srp_verify_param_cb); } #endif #endif con=SSL_new(ctx); if (sess_in) { SSL_SESSION *sess; BIO *stmp = BIO_new_file(sess_in, "r"); if (!stmp) { BIO_printf(bio_err, "Can't open session file %s\n", sess_in); ERR_print_errors(bio_err); goto end; } sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); BIO_free(stmp); if (!sess) { BIO_printf(bio_err, "Can't open session file %s\n", sess_in); ERR_print_errors(bio_err); goto end; } SSL_set_session(con, sess); SSL_SESSION_free(sess); } #ifndef OPENSSL_NO_TLSEXT if (servername != NULL) { if (!SSL_set_tlsext_host_name(con,servername)) { BIO_printf(bio_err,"Unable to set TLS servername extension.\n"); ERR_print_errors(bio_err); goto end; } } #endif #ifndef OPENSSL_NO_KRB5 if (con && (kctx = kssl_ctx_new()) != NULL) { SSL_set0_kssl_ctx(con, kctx); kssl_ctx_setstring(kctx, KSSL_SERVER, host); } #endif /* OPENSSL_NO_KRB5 */ /* SSL_set_cipher_list(con,"RC4-MD5"); */ #if 0 #ifdef TLSEXT_TYPE_opaque_prf_input SSL_set_tlsext_opaque_prf_input(con, "Test client", 11); #endif #endif re_start: #ifdef NO_SYS_UN_H if (init_client(&s,host,port,socket_type) == 0) #else if ((!unix_path && (init_client(&s,host,port,socket_type) == 0)) || (unix_path && (init_client_unix(&s,unix_path) == 0))) #endif { BIO_printf(bio_err,"connect:errno=%d\n",get_last_socket_error()); SHUTDOWN(s); goto end; } BIO_printf(bio_c_out,"CONNECTED(%08X)\n",s); #ifdef FIONBIO if (c_nbio) { unsigned long l=1; BIO_printf(bio_c_out,"turning on non blocking io\n"); if (BIO_socket_ioctl(s,FIONBIO,&l) < 0) { ERR_print_errors(bio_err); goto end; } } #endif if (c_Pause & 0x01) SSL_set_debug(con, 1); if (socket_type == SOCK_DGRAM) { sbio=BIO_new_dgram(s,BIO_NOCLOSE); if (getsockname(s, &peer, (void *)&peerlen) < 0) { BIO_printf(bio_err, "getsockname:errno=%d\n", get_last_socket_error()); SHUTDOWN(s); goto end; } (void)BIO_ctrl_set_connected(sbio, 1, &peer); if (enable_timeouts) { timeout.tv_sec = 0; timeout.tv_usec = DGRAM_RCV_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); timeout.tv_sec = 0; timeout.tv_usec = DGRAM_SND_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout); } if (socket_mtu > 28) { SSL_set_options(con, SSL_OP_NO_QUERY_MTU); SSL_set_mtu(con, socket_mtu - 28); } else /* want to do MTU discovery */ BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL); } else sbio=BIO_new_socket(s,BIO_NOCLOSE); if (nbio_test) { BIO *test; test=BIO_new(BIO_f_nbio_test()); sbio=BIO_push(test,sbio); } if (c_debug) { SSL_set_debug(con, 1); BIO_set_callback(sbio,bio_dump_callback); BIO_set_callback_arg(sbio,(char *)bio_c_out); } if (c_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (c_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out); } #ifndef OPENSSL_NO_TLSEXT if (c_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_c_out); } if (c_status_req) { SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp); SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb); SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out); #if 0 { STACK_OF(OCSP_RESPID) *ids = sk_OCSP_RESPID_new_null(); OCSP_RESPID *id = OCSP_RESPID_new(); id->value.byKey = ASN1_OCTET_STRING_new(); id->type = V_OCSP_RESPID_KEY; ASN1_STRING_set(id->value.byKey, "Hello World", -1); sk_OCSP_RESPID_push(ids, id); SSL_set_tlsext_status_ids(con, ids); } #endif } #endif #ifndef OPENSSL_NO_JPAKE if (jpake_secret) jpake_client_auth(bio_c_out, sbio, jpake_secret); #endif SSL_set_bio(con,sbio,sbio); SSL_set_connect_state(con); /* ok, lets connect */ width=SSL_get_fd(con)+1; read_tty=1; write_tty=0; tty_on=0; read_ssl=1; write_ssl=1; cbuf_len=0; cbuf_off=0; sbuf_len=0; sbuf_off=0; /* This is an ugly hack that does a lot of assumptions */ /* We do have to handle multi-line responses which may come in a single packet or not. We therefore have to use BIO_gets() which does need a buffering BIO. So during the initial chitchat we do push a buffering BIO into the chain that is removed again later on to not disturb the rest of the s_client operation. */ if (starttls_proto == PROTO_SMTP) { int foundit=0; BIO *fbio = BIO_new(BIO_f_buffer()); BIO_push(fbio, sbio); /* wait for multi-line response to end from SMTP */ do { mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ); } while (mbuf_len>3 && mbuf[3]=='-'); /* STARTTLS command requires EHLO... */ BIO_printf(fbio,"EHLO openssl.client.net\r\n"); (void)BIO_flush(fbio); /* wait for multi-line response to end EHLO SMTP response */ do { mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ); if (strstr(mbuf,"STARTTLS")) foundit=1; } while (mbuf_len>3 && mbuf[3]=='-'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "didn't found starttls in server response," " try anyway...\n"); BIO_printf(sbio,"STARTTLS\r\n"); BIO_read(sbio,sbuf,BUFSIZZ); } else if (starttls_proto == PROTO_POP3) { BIO_read(sbio,mbuf,BUFSIZZ); BIO_printf(sbio,"STLS\r\n"); BIO_read(sbio,sbuf,BUFSIZZ); } else if (starttls_proto == PROTO_IMAP) { int foundit=0; BIO *fbio = BIO_new(BIO_f_buffer()); BIO_push(fbio, sbio); BIO_gets(fbio,mbuf,BUFSIZZ); /* STARTTLS command requires CAPABILITY... */ BIO_printf(fbio,". CAPABILITY\r\n"); (void)BIO_flush(fbio); /* wait for multi-line CAPABILITY response */ do { mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ); if (strstr(mbuf,"STARTTLS")) foundit=1; } while (mbuf_len>3 && mbuf[0]!='.'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "didn't found STARTTLS in server response," " try anyway...\n"); BIO_printf(sbio,". STARTTLS\r\n"); BIO_read(sbio,sbuf,BUFSIZZ); } else if (starttls_proto == PROTO_FTP) { BIO *fbio = BIO_new(BIO_f_buffer()); BIO_push(fbio, sbio); /* wait for multi-line response to end from FTP */ do { mbuf_len = BIO_gets(fbio,mbuf,BUFSIZZ); } while (mbuf_len>3 && mbuf[3]=='-'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); BIO_printf(sbio,"AUTH TLS\r\n"); BIO_read(sbio,sbuf,BUFSIZZ); } if (starttls_proto == PROTO_XMPP) { int seen = 0; BIO_printf(sbio,"<stream:stream " "xmlns:stream='http://etherx.jabber.org/streams' " "xmlns='jabber:client' to='%s' version='1.0'>", xmpphost ? xmpphost : host); seen = BIO_read(sbio,mbuf,BUFSIZZ); mbuf[seen] = 0; while (!strstr(mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'") && !strstr(mbuf, "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"")) { seen = BIO_read(sbio,mbuf,BUFSIZZ); if (seen <= 0) goto shut; mbuf[seen] = 0; } BIO_printf(sbio, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"); seen = BIO_read(sbio,sbuf,BUFSIZZ); sbuf[seen] = 0; if (!strstr(sbuf, "<proceed")) goto shut; mbuf[0] = 0; } for (;;) { FD_ZERO(&readfds); FD_ZERO(&writefds); if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_get_timeout(con, &timeout)) timeoutp = &timeout; else timeoutp = NULL; if (SSL_in_init(con) && !SSL_total_renegotiations(con)) { in_init=1; tty_on=0; } else { tty_on=1; if (in_init) { in_init=0; #if 0 /* This test doesn't really work as intended (needs to be fixed) */ #ifndef OPENSSL_NO_TLSEXT if (servername != NULL && !SSL_session_reused(con)) { BIO_printf(bio_c_out,"Server did %sacknowledge servername extension.\n",tlsextcbp.ack?"":"not "); } #endif #endif if (sess_out) { BIO *stmp = BIO_new_file(sess_out, "w"); if (stmp) { PEM_write_bio_SSL_SESSION(stmp, SSL_get_session(con)); BIO_free(stmp); } else BIO_printf(bio_err, "Error writing session file %s\n", sess_out); } if (c_brief) { BIO_puts(bio_err, "CONNECTION ESTABLISHED\n"); print_ssl_summary(bio_err, con); } print_stuff(bio_c_out,con,full_log); if (full_log > 0) full_log--; if (starttls_proto) { BIO_printf(bio_err,"%s",mbuf); /* We don't need to know any more */ starttls_proto = PROTO_OFF; } if (reconnect) { reconnect--; BIO_printf(bio_c_out,"drop connection and then reconnect\n"); SSL_shutdown(con); SSL_set_connect_state(con); SHUTDOWN(SSL_get_fd(con)); goto re_start; } } } ssl_pending = read_ssl && SSL_pending(con); if (!ssl_pending) { #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_NETWARE) && !defined (OPENSSL_SYS_BEOS_R5) if (tty_on) { if (read_tty) openssl_fdset(fileno(stdin),&readfds); if (write_tty) openssl_fdset(fileno(stdout),&writefds); } if (read_ssl) openssl_fdset(SSL_get_fd(con),&readfds); if (write_ssl) openssl_fdset(SSL_get_fd(con),&writefds); #else if(!tty_on || !write_tty) { if (read_ssl) openssl_fdset(SSL_get_fd(con),&readfds); if (write_ssl) openssl_fdset(SSL_get_fd(con),&writefds); } #endif /* printf("mode tty(%d %d%d) ssl(%d%d)\n", tty_on,read_tty,write_tty,read_ssl,write_ssl);*/ /* Note: under VMS with SOCKETSHR the second parameter * is currently of type (int *) whereas under other * systems it is (void *) if you don't have a cast it * will choke the compiler: if you do have a cast then * you can either go for (int *) or (void *). */ #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) /* Under Windows/DOS we make the assumption that we can * always write to the tty: therefore if we need to * write to the tty we just fall through. Otherwise * we timeout the select every second and see if there * are any keypresses. Note: this is a hack, in a proper * Windows application we wouldn't do this. */ i=0; if(!write_tty) { if(read_tty) { tv.tv_sec = 1; tv.tv_usec = 0; i=select(width,(void *)&readfds,(void *)&writefds, NULL,&tv); #if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS) if(!i && (!_kbhit() || !read_tty) ) continue; #else if(!i && (!((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0))) || !read_tty) ) continue; #endif } else i=select(width,(void *)&readfds,(void *)&writefds, NULL,timeoutp); } #elif defined(OPENSSL_SYS_NETWARE) if(!write_tty) { if(read_tty) { tv.tv_sec = 1; tv.tv_usec = 0; i=select(width,(void *)&readfds,(void *)&writefds, NULL,&tv); } else i=select(width,(void *)&readfds,(void *)&writefds, NULL,timeoutp); } #elif defined(OPENSSL_SYS_BEOS_R5) /* Under BeOS-R5 the situation is similar to DOS */ i=0; stdin_set = 0; (void)fcntl(fileno(stdin), F_SETFL, O_NONBLOCK); if(!write_tty) { if(read_tty) { tv.tv_sec = 1; tv.tv_usec = 0; i=select(width,(void *)&readfds,(void *)&writefds, NULL,&tv); if (read(fileno(stdin), sbuf, 0) >= 0) stdin_set = 1; if (!i && (stdin_set != 1 || !read_tty)) continue; } else i=select(width,(void *)&readfds,(void *)&writefds, NULL,timeoutp); } (void)fcntl(fileno(stdin), F_SETFL, 0); #else i=select(width,(void *)&readfds,(void *)&writefds, NULL,timeoutp); #endif if ( i < 0) { BIO_printf(bio_err,"bad select %d\n", get_last_socket_error()); goto shut; /* goto end; */ } } if ((SSL_version(con) == DTLS1_VERSION) && DTLSv1_handle_timeout(con) > 0) { BIO_printf(bio_err,"TIMEOUT occurred\n"); } if (!ssl_pending && FD_ISSET(SSL_get_fd(con),&writefds)) { k=SSL_write(con,&(cbuf[cbuf_off]), (unsigned int)cbuf_len); switch (SSL_get_error(con,k)) { case SSL_ERROR_NONE: cbuf_off+=k; cbuf_len-=k; if (k <= 0) goto end; /* we have done a write(con,NULL,0); */ if (cbuf_len <= 0) { read_tty=1; write_ssl=0; } else /* if (cbuf_len > 0) */ { read_tty=0; write_ssl=1; } break; case SSL_ERROR_WANT_WRITE: BIO_printf(bio_c_out,"write W BLOCK\n"); write_ssl=1; read_tty=0; break; case SSL_ERROR_WANT_READ: BIO_printf(bio_c_out,"write R BLOCK\n"); write_tty=0; read_ssl=1; write_ssl=0; break; case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_c_out,"write X BLOCK\n"); break; case SSL_ERROR_ZERO_RETURN: if (cbuf_len != 0) { BIO_printf(bio_c_out,"shutdown\n"); ret = 0; goto shut; } else { read_tty=1; write_ssl=0; break; } case SSL_ERROR_SYSCALL: if ((k != 0) || (cbuf_len != 0)) { BIO_printf(bio_err,"write:errno=%d\n", get_last_socket_error()); goto shut; } else { read_tty=1; write_ssl=0; } break; case SSL_ERROR_SSL: ERR_print_errors(bio_err); goto shut; } } #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_NETWARE) || defined(OPENSSL_SYS_BEOS_R5) /* Assume Windows/DOS/BeOS can always write */ else if (!ssl_pending && write_tty) #else else if (!ssl_pending && FD_ISSET(fileno(stdout),&writefds)) #endif { #ifdef CHARSET_EBCDIC ascii2ebcdic(&(sbuf[sbuf_off]),&(sbuf[sbuf_off]),sbuf_len); #endif i=raw_write_stdout(&(sbuf[sbuf_off]),sbuf_len); if (i <= 0) { BIO_printf(bio_c_out,"DONE\n"); ret = 0; goto shut; /* goto end; */ } sbuf_len-=i;; sbuf_off+=i; if (sbuf_len <= 0) { read_ssl=1; write_tty=0; } } else if (ssl_pending || FD_ISSET(SSL_get_fd(con),&readfds)) { #ifdef RENEG { static int iiii; if (++iiii == 52) { SSL_renegotiate(con); iiii=0; } } #endif #if 1 k=SSL_read(con,sbuf,1024 /* BUFSIZZ */ ); #else /* Demo for pending and peek :-) */ k=SSL_read(con,sbuf,16); { char zbuf[10240]; printf("read=%d pending=%d peek=%d\n",k,SSL_pending(con),SSL_peek(con,zbuf,10240)); } #endif switch (SSL_get_error(con,k)) { case SSL_ERROR_NONE: if (k <= 0) goto end; sbuf_off=0; sbuf_len=k; read_ssl=0; write_tty=1; break; case SSL_ERROR_WANT_WRITE: BIO_printf(bio_c_out,"read W BLOCK\n"); write_ssl=1; read_tty=0; break; case SSL_ERROR_WANT_READ: BIO_printf(bio_c_out,"read R BLOCK\n"); write_tty=0; read_ssl=1; if ((read_tty == 0) && (write_ssl == 0)) write_ssl=1; break; case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_c_out,"read X BLOCK\n"); break; case SSL_ERROR_SYSCALL: ret=get_last_socket_error(); if (c_brief) BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n"); else BIO_printf(bio_err,"read:errno=%d\n",ret); goto shut; case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_c_out,"closed\n"); ret=0; goto shut; case SSL_ERROR_SSL: ERR_print_errors(bio_err); goto shut; /* break; */ } } #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) #if defined(OPENSSL_SYS_WINCE) || defined(OPENSSL_SYS_MSDOS) else if (_kbhit()) #else else if ((_kbhit()) || (WAIT_OBJECT_0 == WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 0))) #endif #elif defined (OPENSSL_SYS_NETWARE) else if (_kbhit()) #elif defined(OPENSSL_SYS_BEOS_R5) else if (stdin_set) #else else if (FD_ISSET(fileno(stdin),&readfds)) #endif { if (crlf) { int j, lf_num; i=raw_read_stdin(cbuf,BUFSIZZ/2); lf_num = 0; /* both loops are skipped when i <= 0 */ for (j = 0; j < i; j++) if (cbuf[j] == '\n') lf_num++; for (j = i-1; j >= 0; j--) { cbuf[j+lf_num] = cbuf[j]; if (cbuf[j] == '\n') { lf_num--; i++; cbuf[j+lf_num] = '\r'; } } assert(lf_num == 0); } else i=raw_read_stdin(cbuf,BUFSIZZ); if ((!c_ign_eof) && ((i <= 0) || (cbuf[0] == 'Q'))) { BIO_printf(bio_err,"DONE\n"); ret=0; goto shut; } if ((!c_ign_eof) && (cbuf[0] == 'R')) { BIO_printf(bio_err,"RENEGOTIATING\n"); SSL_renegotiate(con); cbuf_len=0; } #ifndef OPENSSL_NO_HEARTBEATS else if ((!c_ign_eof) && (cbuf[0] == 'B')) { BIO_printf(bio_err,"HEARTBEATING\n"); SSL_heartbeat(con); cbuf_len=0; } #endif else { cbuf_len=i; cbuf_off=0; #ifdef CHARSET_EBCDIC ebcdic2ascii(cbuf, cbuf, i); #endif } write_ssl=1; read_tty=0; } } ret=0; shut: if (in_init) print_stuff(bio_c_out,con,full_log); SSL_shutdown(con); SHUTDOWN(SSL_get_fd(con)); end: if (con != NULL) { if (prexit != 0) print_stuff(bio_c_out,con,1); SSL_free(con); } #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto.data) OPENSSL_free(next_proto.data); #endif if (ctx != NULL) SSL_CTX_free(ctx); if (cert) X509_free(cert); if (crls) sk_X509_CRL_pop_free(crls, X509_CRL_free); if (key) EVP_PKEY_free(key); if (chain) sk_X509_pop_free(chain, X509_free); if (pass) OPENSSL_free(pass); if (vpm) X509_VERIFY_PARAM_free(vpm); ssl_excert_free(exc); if (ssl_args) sk_OPENSSL_STRING_free(ssl_args); if (cctx) SSL_CONF_CTX_free(cctx); #ifndef OPENSSL_NO_JPAKE if (jpake_secret && psk_key) OPENSSL_free(psk_key); #endif if (cbuf != NULL) { OPENSSL_cleanse(cbuf,BUFSIZZ); OPENSSL_free(cbuf); } if (sbuf != NULL) { OPENSSL_cleanse(sbuf,BUFSIZZ); OPENSSL_free(sbuf); } if (mbuf != NULL) { OPENSSL_cleanse(mbuf,BUFSIZZ); OPENSSL_free(mbuf); } if (bio_c_out != NULL) { BIO_free(bio_c_out); bio_c_out=NULL; } if (bio_c_msg != NULL) { BIO_free(bio_c_msg); bio_c_msg=NULL; } apps_shutdown(); OPENSSL_EXIT(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV. Reviewed-by: Stephen Henson <steve@openssl.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 ssl_cipher_list_to_bytes(SSL *s,STACK_OF(SSL_CIPHER) *sk,unsigned char *p, int (*put_cb)(const SSL_CIPHER *, unsigned char *)) { int i,j=0; SSL_CIPHER *c; unsigned char *q; #ifndef OPENSSL_NO_KRB5 int nokrb5 = !kssl_tgt_is_available(s->kssl_ctx); #endif /* OPENSSL_NO_KRB5 */ if (sk == NULL) return(0); q=p; for (i=0; i<sk_SSL_CIPHER_num(sk); i++) { c=sk_SSL_CIPHER_value(sk,i); /* Skip TLS v1.2 only ciphersuites if lower than v1.2 */ if ((c->algorithm_ssl & SSL_TLSV1_2) && (TLS1_get_client_version(s) < TLS1_2_VERSION)) continue; #ifndef OPENSSL_NO_KRB5 if (((c->algorithm_mkey & SSL_kKRB5) || (c->algorithm_auth & SSL_aKRB5)) && nokrb5) continue; #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_PSK /* with PSK there must be client callback set */ if (((c->algorithm_mkey & SSL_kPSK) || (c->algorithm_auth & SSL_aPSK)) && s->psk_client_callback == NULL) continue; #endif /* OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (((c->algorithm_mkey & SSL_kSRP) || (c->algorithm_auth & SSL_aSRP)) && !(s->srp_ctx.srp_Mask & SSL_kSRP)) continue; #endif /* OPENSSL_NO_SRP */ j = put_cb ? put_cb(c,p) : ssl_put_cipher_by_char(s,c,p); p+=j; } /* If p == q, no ciphers and caller indicates an error. Otherwise * add SCSV if not renegotiating. */ if (p != q && !s->renegotiate) { static SSL_CIPHER scsv = { 0, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; j = put_cb ? put_cb(&scsv,p) : ssl_put_cipher_by_char(s,&scsv,p); p+=j; #ifdef OPENSSL_RI_DEBUG fprintf(stderr, "SCSV sent by client\n"); #endif } return(p-q); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV. Reviewed-by: Rich Salz <rsalz@openssl.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: STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s,unsigned char *p,int num, STACK_OF(SSL_CIPHER) **skp) { SSL_CIPHER *c; STACK_OF(SSL_CIPHER) *sk; int i,n; if (s->s3) s->s3->send_connection_binding = 0; n=ssl_put_cipher_by_char(s,NULL,NULL); if ((num%n) != 0) { SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST); return(NULL); } if ((skp == NULL) || (*skp == NULL)) sk=sk_SSL_CIPHER_new_null(); /* change perhaps later */ else { sk= *skp; sk_SSL_CIPHER_zero(sk); } for (i=0; i<num; i+=n) { /* Check for SCSV */ if (s->s3 && (n != 3 || !p[0]) && (p[n-2] == ((SSL3_CK_SCSV >> 8) & 0xff)) && (p[n-1] == (SSL3_CK_SCSV & 0xff))) { /* SCSV fatal if renegotiating */ if (s->new_session) { SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); goto err; } s->s3->send_connection_binding = 1; p += n; #ifdef OPENSSL_RI_DEBUG fprintf(stderr, "SCSV received by server\n"); #endif continue; } c=ssl_get_cipher_by_char(s,p); p+=n; if (c != NULL) { if (!sk_SSL_CIPHER_push(sk,c)) { SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,ERR_R_MALLOC_FAILURE); goto err; } } } if (skp != NULL) *skp=sk; return(sk); err: if ((skp == NULL) || (*skp == NULL)) sk_SSL_CIPHER_free(sk); return(NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Support TLS_FALLBACK_SCSV. Reviewed-by: Stephen Henson <steve@openssl.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 ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) { unsigned short type; unsigned short size; unsigned short len; unsigned char *data = *p; int renegotiate_seen = 0; int sigalg_seen = 0; s->servername_done = 0; s->tlsext_status_type = -1; #ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; #endif #ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); #endif #ifndef OPENSSL_NO_EC if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG) ssl_check_for_safari(s, data, d, n); #endif /* !OPENSSL_NO_EC */ if (data >= (d+n-2)) goto ri_check; n2s(data,len); if (data > (d+n-len)) goto ri_check; while (data <= (d+n-4)) { n2s(data,type); n2s(data,size); if (data+size > (d+n)) goto ri_check; #if 0 fprintf(stderr,"Received extension type %d size %d\n",type,size); #endif if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg); /* The servername extension is treated as follows: - Only the hostname type is supported with a maximum length of 255. - The servername is rejected if too long or if it contains zeros, in which case an fatal alert is generated. - The servername field is maintained together with the session cache. - When a session is resumed, the servername call back invoked in order to allow the application to position itself to the right context. - The servername is acknowledged if it is new for a session or when it is identical to a previously used for the same session. Applications can control the behaviour. They can at any time set a 'desirable' servername for a new SSL object. This can be the case for example with HTTPS when a Host: header field is received and a renegotiation is requested. In this case, a possible servername presented in the new client hello is only acknowledged if it matches the value of the Host: field. - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION if they provide for changing an explicit servername context for the session, i.e. when the session has been established with a servername extension. - On session reconnect, the servername extension may be absent. */ if (type == TLSEXT_TYPE_server_name) { unsigned char *sdata; int servname_type; int dsize; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(data,dsize); size -= 2; if (dsize > size ) { *al = SSL_AD_DECODE_ERROR; return 0; } sdata = data; while (dsize > 3) { servname_type = *(sdata++); n2s(sdata,len); dsize -= 3; if (len > dsize) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->servername_done == 0) switch (servname_type) { case TLSEXT_NAMETYPE_host_name: if (!s->hit) { if(s->session->tlsext_hostname) { *al = SSL_AD_DECODE_ERROR; return 0; } if (len > TLSEXT_MAXLEN_host_name) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->session->tlsext_hostname, sdata, len); s->session->tlsext_hostname[len]='\0'; if (strlen(s->session->tlsext_hostname) != len) { OPENSSL_free(s->session->tlsext_hostname); s->session->tlsext_hostname = NULL; *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } s->servername_done = 1; } else s->servername_done = s->session->tlsext_hostname && strlen(s->session->tlsext_hostname) == len && strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0; break; default: break; } dsize -= len; } if (dsize != 0) { *al = SSL_AD_DECODE_ERROR; return 0; } } #ifndef OPENSSL_NO_SRP else if (type == TLSEXT_TYPE_srp) { if (size <= 0 || ((len = data[0])) != (size -1)) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->srp_ctx.login != NULL) { *al = SSL_AD_DECODE_ERROR; return 0; } if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL) return -1; memcpy(s->srp_ctx.login, &data[1], len); s->srp_ctx.login[len]='\0'; if (strlen(s->srp_ctx.login) != len) { *al = SSL_AD_DECODE_ERROR; return 0; } } #endif #ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (!s->hit) { if(s->session->tlsext_ecpointformatlist) { OPENSSL_free(s->session->tlsext_ecpointformatlist); s->session->tlsext_ecpointformatlist = NULL; } s->session->tlsext_ecpointformatlist_length = 0; if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } #if 0 fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr,"%i ",*(sdata++)); fprintf(stderr,"\n"); #endif } else if (type == TLSEXT_TYPE_elliptic_curves) { unsigned char *sdata = data; int ellipticcurvelist_length = (*(sdata++) << 8); ellipticcurvelist_length += (*(sdata++)); if (ellipticcurvelist_length != size - 2 || ellipticcurvelist_length < 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (!s->hit) { if(s->session->tlsext_ellipticcurvelist) { *al = TLS1_AD_DECODE_ERROR; return 0; } s->session->tlsext_ellipticcurvelist_length = 0; if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length; memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length); } #if 0 fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length); sdata = s->session->tlsext_ellipticcurvelist; for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++) fprintf(stderr,"%i ",*(sdata++)); fprintf(stderr,"\n"); #endif } #endif /* OPENSSL_NO_EC */ #ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input && s->version != DTLS1_VERSION) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */ OPENSSL_free(s->s3->client_opaque_prf_input); if (s->s3->client_opaque_prf_input_len == 0) s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */ else s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len); if (s->s3->client_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } #endif else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } else if (type == TLSEXT_TYPE_renegotiate) { if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } else if (type == TLSEXT_TYPE_signature_algorithms) { int dsize; if (sigalg_seen || size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } sigalg_seen = 1; n2s(data,dsize); size -= 2; if (dsize != size || dsize & 1) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!tls1_process_sigalgs(s, data, dsize)) { *al = SSL_AD_DECODE_ERROR; return 0; } } else if (type == TLSEXT_TYPE_status_request && s->version != DTLS1_VERSION) { if (size < 5) { *al = SSL_AD_DECODE_ERROR; return 0; } s->tlsext_status_type = *data++; size--; if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { const unsigned char *sdata; int dsize; /* Read in responder_id_list */ n2s(data,dsize); size -= 2; if (dsize > size ) { *al = SSL_AD_DECODE_ERROR; return 0; } while (dsize > 0) { OCSP_RESPID *id; int idsize; if (dsize < 4) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(data, idsize); dsize -= 2 + idsize; size -= 2 + idsize; if (dsize < 0) { *al = SSL_AD_DECODE_ERROR; return 0; } sdata = data; data += idsize; id = d2i_OCSP_RESPID(NULL, &sdata, idsize); if (!id) { *al = SSL_AD_DECODE_ERROR; return 0; } if (data != sdata) { OCSP_RESPID_free(id); *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->tlsext_ocsp_ids && !(s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null())) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } if (!sk_OCSP_RESPID_push( s->tlsext_ocsp_ids, id)) { OCSP_RESPID_free(id); *al = SSL_AD_INTERNAL_ERROR; return 0; } } /* Read in request_extensions */ if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(data,dsize); size -= 2; if (dsize != size) { *al = SSL_AD_DECODE_ERROR; return 0; } sdata = data; if (dsize > 0) { if (s->tlsext_ocsp_exts) { sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free); } s->tlsext_ocsp_exts = d2i_X509_EXTENSIONS(NULL, &sdata, dsize); if (!s->tlsext_ocsp_exts || (data + dsize != sdata)) { *al = SSL_AD_DECODE_ERROR; return 0; } } } /* We don't know what to do with any other type * so ignore it. */ else s->tlsext_status_type = -1; } #ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch(data[0]) { case 0x01: /* Client allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Client doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } #endif #ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { /* We shouldn't accept this extension on a * renegotiation. * * s->new_session will be set on renegotiation, but we * probably shouldn't rely that it couldn't be set on * the initial renegotation too in certain cases (when * there's some other reason to disallow resuming an * earlier session -- the current code won't be doing * anything like that, but this might change). * A valid sign that there's been a previous handshake * in this connection is if s->s3->tmp.finish_md_len > * 0. (We are talking about a check that will happen * in the Hello protocol round, well before a new * Finished message could have been computed.) */ s->s3->next_proto_neg_seen = 1; } #endif /* session ticket processed earlier */ #ifndef OPENSSL_NO_SRTP else if (type == TLSEXT_TYPE_use_srtp) { if(ssl_parse_clienthello_use_srtp_ext(s, data, size, al)) return 0; } #endif data+=size; } *p = data; ri_check: /* Need RI if renegotiating */ if (!renegotiate_seen && s->renegotiate && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Fix for SRTP Memory Leak CVE-2014-3513 This issue was reported to OpenSSL on 26th September 2014, based on an origi issue and patch developed by the LibreSSL project. Further analysis of the i was performed by the OpenSSL team. The fix was developed by the OpenSSL team. Reviewed-by: Tim Hudson <tjh@openssl.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 ssl23_get_client_hello(SSL *s) { char buf_space[11]; /* Request this many bytes in initial read. * We can detect SSL 3.0/TLS 1.0 Client Hellos * ('type == 3') correctly only when the following * is in a single record, which is not guaranteed by * the protocol specification: * Byte Content * 0 type \ * 1/2 version > record header * 3/4 length / * 5 msg_type \ * 6-8 length > Client Hello message * 9/10 client_version / */ char *buf= &(buf_space[0]); unsigned char *p,*d,*d_len,*dd; unsigned int i; unsigned int csl,sil,cl; int n=0,j; int type=0; int v[2]; if (s->state == SSL23_ST_SR_CLNT_HELLO_A) { /* read the initial header */ v[0]=v[1]=0; if (!ssl3_setup_buffers(s)) goto err; n=ssl23_read_bytes(s, sizeof buf_space); if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */ p=s->packet; memcpy(buf,p,n); if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) { /* * SSLv2 header */ if ((p[3] == 0x00) && (p[4] == 0x02)) { v[0]=p[3]; v[1]=p[4]; /* SSLv2 */ if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } else if (p[3] == SSL3_VERSION_MAJOR) { v[0]=p[3]; v[1]=p[4]; /* SSLv3/TLSv1 */ if (p[4] >= TLS1_VERSION_MINOR) { if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) { type=1; } } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } } else if ((p[0] == SSL3_RT_HANDSHAKE) && (p[1] == SSL3_VERSION_MAJOR) && (p[5] == SSL3_MT_CLIENT_HELLO) && ((p[3] == 0 && p[4] < 5 /* silly record length? */) || (p[9] >= p[1]))) { /* * SSLv3 or tls1 header */ v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */ /* We must look at client_version inside the Client Hello message * to get the correct minor version. * However if we have only a pathologically small fragment of the * Client Hello message, this would be difficult, and we'd have * to read more records to find out. * No known SSL 3.0 client fragments ClientHello like this, * so we simply reject such connections to avoid * protocol version downgrade attacks. */ if (p[3] == 0 && p[4] < 6) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL); goto err; } /* if major version number > 3 set minor to a value * which will use the highest version 3 we support. * If TLS 2.0 ever appears we will need to revise * this.... */ if (p[9] > SSL3_VERSION_MAJOR) v[1]=0xff; else v[1]=p[10]; /* minor version according to client_version */ if (v[1] >= TLS1_VERSION_MINOR) { if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } } else { /* client requests SSL 3.0 */ if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { /* we won't be able to use TLS of course, * but this will send an appropriate alert */ s->version=TLS1_VERSION; type=3; } } } else if ((strncmp("GET ", (char *)p,4) == 0) || (strncmp("POST ",(char *)p,5) == 0) || (strncmp("HEAD ",(char *)p,5) == 0) || (strncmp("PUT ", (char *)p,4) == 0)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST); goto err; } else if (strncmp("CONNECT",(char *)p,7) == 0) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST); goto err; } } #ifdef OPENSSL_FIPS if (FIPS_mode() && (s->version < TLS1_VERSION)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE); goto err; } #endif /* ensure that TLS_MAX_VERSION is up-to-date */ OPENSSL_assert(s->version <= TLS_MAX_VERSION); if (s->state == SSL23_ST_SR_CLNT_HELLO_B) { /* we have SSLv3/TLSv1 in an SSLv2 header * (other cases skip this state) */ type=2; p=s->packet; v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ v[1] = p[4]; /* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2 * header is sent directly on the wire, not wrapped as a TLS * record. It's format is: * Byte Content * 0-1 msg_length * 2 msg_type * 3-4 version * 5-6 cipher_spec_length * 7-8 session_id_length * 9-10 challenge_length * ... ... */ n=((p[0]&0x7f)<<8)|p[1]; if (n > (1024*4)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); goto err; } if (n < 9) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } j=ssl23_read_bytes(s,n+2); /* We previously read 11 bytes, so if j > 0, we must have * j == n+2 == s->packet_length. We have at least 11 valid * packet bytes. */ if (j <= 0) return(j); ssl3_finish_mac(s, s->packet+2, s->packet_length-2); if (s->msg_callback) s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */ p=s->packet; p+=5; n2s(p,csl); n2s(p,sil); n2s(p,cl); d=(unsigned char *)s->init_buf->data; if ((csl+sil+cl+11) != s->packet_length) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } /* record header: msg_type ... */ *(d++) = SSL3_MT_CLIENT_HELLO; /* ... and length (actual value will be written later) */ d_len = d; d += 3; /* client_version */ *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */ *(d++) = v[1]; /* lets populate the random area */ /* get the challenge_length */ i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl; memset(d,0,SSL3_RANDOM_SIZE); memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i); d+=SSL3_RANDOM_SIZE; /* no session-id reuse */ *(d++)=0; /* ciphers */ j=0; dd=d; d+=2; for (i=0; i<csl; i+=3) { if (p[i] != 0) continue; *(d++)=p[i+1]; *(d++)=p[i+2]; j+=2; } s2n(j,dd); /* COMPRESSION */ *(d++)=1; *(d++)=0; i = (d-(unsigned char *)s->init_buf->data) - 4; l2n3((long)i, d_len); /* get the data reused from the init_buf */ s->s3->tmp.reuse_message=1; s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO; s->s3->tmp.message_size=i; } /* imaginary new state (for program structure): */ /* s->state = SSL23_SR_CLNT_HELLO_C */ if (type == 1) { #ifdef OPENSSL_NO_SSL2 SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; #else /* we are talking sslv2 */ /* we need to clean up the SSLv3/TLSv1 setup and put in the * sslv2 stuff. */ if (s->s2 == NULL) { if (!ssl2_new(s)) goto err; } else ssl2_clear(s); if (s->s3 != NULL) ssl3_free(s); if (!BUF_MEM_grow_clean(s->init_buf, SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) { goto err; } s->state=SSL2_ST_GET_CLIENT_HELLO_A; if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3) s->s2->ssl2_rollback=0; else /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0 * (SSL 3.0 draft/RFC 2246, App. E.2) */ s->s2->ssl2_rollback=1; /* setup the n bytes we have read so we get them from * the sslv2 buffer */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; s->packet= &(s->s2->rbuf[0]); memcpy(s->packet,buf,n); s->s2->rbuf_left=n; s->s2->rbuf_offs=0; s->method=SSLv2_server_method(); s->handshake_func=s->method->ssl_accept; #endif } if ((type == 2) || (type == 3)) { /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ if (!ssl_init_wbio_buffer(s,1)) goto err; /* we are in this state */ s->state=SSL3_ST_SR_CLNT_HELLO_A; if (type == 3) { /* put the 'n' bytes we have read into the input buffer * for SSLv3 */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; s->packet= &(s->s3->rbuf.buf[0]); memcpy(s->packet,buf,n); s->s3->rbuf.left=n; s->s3->rbuf.offset=0; } else { s->packet_length=0; s->s3->rbuf.left=0; s->s3->rbuf.offset=0; } if (s->version == TLS1_VERSION) s->method = TLSv1_server_method(); else s->method = SSLv3_server_method(); #if 0 /* ssl3_get_client_hello does this */ s->client_version=(v[0]<<8)|v[1]; #endif s->handshake_func=s->method->ssl_accept; } if ((type < 1) || (type > 3)) { /* bad, very bad */ SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL); goto err; } s->init_num=0; if (buf != buf_space) OPENSSL_free(buf); return(SSL_accept(s)); err: if (buf != buf_space) OPENSSL_free(buf); return(-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix no-ssl3 configuration option CVE-2014-3568 Reviewed-by: Emilia Kasper <emilia@openssl.org> Reviewed-by: Rich Salz <rsalz@openssl.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 ssl3_get_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2]; #endif EVP_MD_CTX md_ctx; unsigned char *param,*p; int al,j,ok; long i,param_len,n,alg; EVP_PKEY *pkey=NULL; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL; BN_CTX *bn_ctx = NULL; EC_POINT *srvr_ecpoint = NULL; int curve_nid = 0; int encoded_pt_len = 0; #endif /* use same message size as in ssl3_get_certificate_request() * as ServerKeyExchange message may be skipped */ n=s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A, SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); alg=s->s3->tmp.new_cipher->algorithms; EVP_MD_CTX_init(&md_ctx); if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) { /* * Can't skip server key exchange if this is an ephemeral * ciphersuite. */ if (alg & (SSL_kEDH|SSL_kECDHE)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE); al = SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } s->s3->tmp.reuse_message=1; return(1); } param=p=(unsigned char *)s->init_msg; if (s->session->sess_cert != NULL) { #ifndef OPENSSL_NO_RSA if (s->session->sess_cert->peer_rsa_tmp != NULL) { RSA_free(s->session->sess_cert->peer_rsa_tmp); s->session->sess_cert->peer_rsa_tmp=NULL; } #endif #ifndef OPENSSL_NO_DH if (s->session->sess_cert->peer_dh_tmp) { DH_free(s->session->sess_cert->peer_dh_tmp); s->session->sess_cert->peer_dh_tmp=NULL; } #endif #ifndef OPENSSL_NO_ECDH if (s->session->sess_cert->peer_ecdh_tmp) { EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp); s->session->sess_cert->peer_ecdh_tmp=NULL; } #endif } else { s->session->sess_cert=ssl_sess_cert_new(); } /* Total length of the parameters including the length prefix */ param_len=0; al=SSL_AD_DECODE_ERROR; #ifndef OPENSSL_NO_RSA if (alg & SSL_kRSA) { if ((rsa=RSA_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH); goto f_err; } param_len += i; if (!(rsa->n=BN_bin2bn(p,i,rsa->n))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH); goto f_err; } param_len += i; if (!(rsa->e=BN_bin2bn(p,i,rsa->e))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; /* this should be because we are using an export cipher */ if (alg & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); else { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } s->session->sess_cert->peer_rsa_tmp=rsa; rsa=NULL; } #else /* OPENSSL_NO_RSA */ if (0) ; #endif #ifndef OPENSSL_NO_DH else if (alg & SSL_kEDH) { if ((dh=DH_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH); goto f_err; } param_len += i; if (!(dh->p=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH); goto f_err; } param_len += i; if (!(dh->g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH); goto f_err; } param_len += i; if (!(dh->pub_key=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; #ifndef OPENSSL_NO_RSA if (alg & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif /* else anonymous DH, so no certificate or pkey. */ s->session->sess_cert->peer_dh_tmp=dh; dh=NULL; } else if ((alg & SSL_kDHr) || (alg & SSL_kDHd)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); goto f_err; } #endif /* !OPENSSL_NO_DH */ #ifndef OPENSSL_NO_ECDH else if (alg & SSL_kECDHE) { EC_GROUP *ngroup; const EC_GROUP *group; if ((ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Extract elliptic curve parameters and the * server's ephemeral ECDH public key. * Keep accumulating lengths of various components in * param_len and make sure it never exceeds n. */ /* XXX: For now we only support named (not generic) curves * and the ECParameters in this case is just three bytes. We * also need one byte for the length of the encoded point */ param_len=4; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } if ((*p != NAMED_CURVE_TYPE) || ((curve_nid = curve_id2nid(*(p + 2))) == 0)) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS); goto f_err; } ngroup = EC_GROUP_new_by_curve_name(curve_nid); if (ngroup == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (EC_KEY_set_group(ecdh, ngroup) == 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } EC_GROUP_free(ngroup); group = EC_KEY_get0_group(ecdh); if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { al=SSL_AD_EXPORT_RESTRICTION; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto f_err; } p+=3; /* Next, get the encoded ECPoint */ if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) || ((bn_ctx = BN_CTX_new()) == NULL)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encoded_pt_len = *p; /* length of encoded point */ p+=1; if ((encoded_pt_len > n - param_len) || (EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len, bn_ctx) == 0)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT); goto f_err; } param_len += encoded_pt_len; n-=param_len; p+=encoded_pt_len; /* The ECC/TLS specification does not mention * the use of DSA to sign ECParameters in the server * key exchange message. We do support RSA and ECDSA. */ if (0) ; #ifndef OPENSSL_NO_RSA else if (alg & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #endif #ifndef OPENSSL_NO_ECDSA else if (alg & SSL_aECDSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); #endif /* else anonymous ECDH, so no certificate or pkey. */ EC_KEY_set_public_key(ecdh, srvr_ecpoint); s->session->sess_cert->peer_ecdh_tmp=ecdh; ecdh=NULL; BN_CTX_free(bn_ctx); bn_ctx = NULL; EC_POINT_free(srvr_ecpoint); srvr_ecpoint = NULL; } else if (alg & SSL_kECDH) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } #endif /* !OPENSSL_NO_ECDH */ if (alg & SSL_aFZA) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); goto f_err; } /* p points to the next byte, there are 'n' bytes left */ /* if it was signed, check the signature */ if (pkey != NULL) { n2s(p,i); n-=2; j=EVP_PKEY_size(pkey); /* Check signature length. If n is 0 then signature is empty */ if ((i != n) || (n > j) || (n <= 0)) { /* wrong packet length */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH); goto f_err; } #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA) { int num; unsigned int size; j=0; q=md_buf; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,param,param_len); EVP_DigestFinal_ex(&md_ctx,q,&size); q+=size; j+=size; } i=RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { /* lets do DSS */ EVP_VerifyInit_ex(&md_ctx,EVP_dss1(), NULL); EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,param,param_len); if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_ECDSA if (pkey->type == EVP_PKEY_EC) { /* let's do ECDSA */ EVP_VerifyInit_ex(&md_ctx,EVP_ecdsa(), NULL); EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,param,param_len); if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } } else { /* still data left over */ if (!(alg & SSL_aNULL)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } if (n != 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE); goto f_err; } } EVP_PKEY_free(pkey); EVP_MD_CTX_cleanup(&md_ctx); return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_RSA if (rsa != NULL) RSA_free(rsa); #endif #ifndef OPENSSL_NO_DH if (dh != NULL) DH_free(dh); #endif #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); EC_POINT_free(srvr_ecpoint); if (ecdh != NULL) EC_KEY_free(ecdh); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Only allow ephemeral RSA keys in export ciphersuites. OpenSSL clients would tolerate temporary RSA keys in non-export ciphersuites. It also had an option SSL_OP_EPHEMERAL_RSA which enabled this server side. Remove both options as they are a protocol violation. Thanks to Karthikeyan Bhargavan for reporting this issue. (CVE-2015-0204) Reviewed-by: Matt Caswell <matt@openssl.org> Reviewed-by: Tim Hudson <tjh@openssl.org> (cherry picked from commit 4b4c1fcc88aec8c9e001b0a0077d3cd4de1ed0e6) Conflicts: CHANGES doc/ssl/SSL_CTX_set_options.pod ssl/d1_srvr.c ssl/s3_srvr.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int X509_verify(X509 *a, EVP_PKEY *r) { return(ASN1_item_verify(ASN1_ITEM_rptr(X509_CINF),a->sig_alg, a->signature,a->cert_info,r)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix various certificate fingerprint issues. By using non-DER or invalid encodings outside the signed portion of a certificate the fingerprint can be changed without breaking the signature. Although no details of the signed portion of the certificate can be changed this can cause problems with some applications: e.g. those using the certificate fingerprint for blacklists. 1. Reject signatures with non zero unused bits. If the BIT STRING containing the signature has non zero unused bits reject the signature. All current signature algorithms require zero unused bits. 2. Check certificate algorithm consistency. Check the AlgorithmIdentifier inside TBS matches the one in the certificate signature. NB: this will result in signature failure errors for some broken certificates. 3. Check DSA/ECDSA signatures use DER. Reencode DSA/ECDSA signatures and compare with the original received signature. Return an error if there is a mismatch. This will reject various cases including garbage after signature (thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS program for discovering this case) and use of BER or invalid ASN.1 INTEGERs (negative or with leading zeroes). CVE-2014-8275 Reviewed-by: Emilia Käsper <emilia@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { #ifdef BN_LLONG BN_ULLONG t; #else BN_ULONG bl,bh; #endif BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[4],b[0],c2,c3,c1); mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); mul_add_c(a[0],b[4],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[0],b[5],c3,c1,c2); mul_add_c(a[1],b[4],c3,c1,c2); mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); mul_add_c(a[4],b[1],c3,c1,c2); mul_add_c(a[5],b[0],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[6],b[0],c1,c2,c3); mul_add_c(a[5],b[1],c1,c2,c3); mul_add_c(a[4],b[2],c1,c2,c3); mul_add_c(a[3],b[3],c1,c2,c3); mul_add_c(a[2],b[4],c1,c2,c3); mul_add_c(a[1],b[5],c1,c2,c3); mul_add_c(a[0],b[6],c1,c2,c3); r[6]=c1; c1=0; mul_add_c(a[0],b[7],c2,c3,c1); mul_add_c(a[1],b[6],c2,c3,c1); mul_add_c(a[2],b[5],c2,c3,c1); mul_add_c(a[3],b[4],c2,c3,c1); mul_add_c(a[4],b[3],c2,c3,c1); mul_add_c(a[5],b[2],c2,c3,c1); mul_add_c(a[6],b[1],c2,c3,c1); mul_add_c(a[7],b[0],c2,c3,c1); r[7]=c2; c2=0; mul_add_c(a[7],b[1],c3,c1,c2); mul_add_c(a[6],b[2],c3,c1,c2); mul_add_c(a[5],b[3],c3,c1,c2); mul_add_c(a[4],b[4],c3,c1,c2); mul_add_c(a[3],b[5],c3,c1,c2); mul_add_c(a[2],b[6],c3,c1,c2); mul_add_c(a[1],b[7],c3,c1,c2); r[8]=c3; c3=0; mul_add_c(a[2],b[7],c1,c2,c3); mul_add_c(a[3],b[6],c1,c2,c3); mul_add_c(a[4],b[5],c1,c2,c3); mul_add_c(a[5],b[4],c1,c2,c3); mul_add_c(a[6],b[3],c1,c2,c3); mul_add_c(a[7],b[2],c1,c2,c3); r[9]=c1; c1=0; mul_add_c(a[7],b[3],c2,c3,c1); mul_add_c(a[6],b[4],c2,c3,c1); mul_add_c(a[5],b[5],c2,c3,c1); mul_add_c(a[4],b[6],c2,c3,c1); mul_add_c(a[3],b[7],c2,c3,c1); r[10]=c2; c2=0; mul_add_c(a[4],b[7],c3,c1,c2); mul_add_c(a[5],b[6],c3,c1,c2); mul_add_c(a[6],b[5],c3,c1,c2); mul_add_c(a[7],b[4],c3,c1,c2); r[11]=c3; c3=0; mul_add_c(a[7],b[5],c1,c2,c3); mul_add_c(a[6],b[6],c1,c2,c3); mul_add_c(a[5],b[7],c1,c2,c3); r[12]=c1; c1=0; mul_add_c(a[6],b[7],c2,c3,c1); mul_add_c(a[7],b[6],c2,c3,c1); r[13]=c2; c2=0; mul_add_c(a[7],b[7],c3,c1,c2); r[14]=c3; r[15]=c1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <emilia@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG t[8]; bn_sqr_normal(r,a,4,t); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <emilia@openssl.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 ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) { int result = -1; if (!a || !b || a->type != b->type) return -1; switch (a->type) { case V_ASN1_OBJECT: result = OBJ_cmp(a->value.object, b->value.object); break; case V_ASN1_NULL: result = 0; /* They do not have content. */ break; case V_ASN1_INTEGER: case V_ASN1_NEG_INTEGER: case V_ASN1_ENUMERATED: case V_ASN1_NEG_ENUMERATED: case V_ASN1_BIT_STRING: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_OTHER: default: result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr, (ASN1_STRING *)b->value.ptr); break; } return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-17'], 'message': 'Fix ASN1_TYPE_cmp Fix segmentation violation when ASN1_TYPE_cmp is passed a boolean type. This can be triggered during certificate verification so could be a DoS attack against a client or a server enabling client authentication. CVE-2015-0286 Reviewed-by: Richard Levitte <levitte@openssl.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 ssl3_send_client_key_exchange(SSL *s) { unsigned char *p; int n; unsigned long alg_k; #ifndef OPENSSL_NO_RSA unsigned char *q; EVP_PKEY *pkey = NULL; #endif #ifndef OPENSSL_NO_KRB5 KSSL_ERR kssl_err; #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH EC_KEY *clnt_ecdh = NULL; const EC_POINT *srvr_ecpoint = NULL; EVP_PKEY *srvr_pub_pkey = NULL; unsigned char *encodedPoint = NULL; int encoded_pt_len = 0; BN_CTX *bn_ctx = NULL; #endif if (s->state == SSL3_ST_CW_KEY_EXCH_A) { p = ssl_handshake_start(s); alg_k = s->s3->tmp.new_cipher->algorithm_mkey; /* Fool emacs indentation */ if (0) { } #ifndef OPENSSL_NO_RSA else if (alg_k & SSL_kRSA) { RSA *rsa; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; if (s->session->sess_cert == NULL) { /* * We should always have a server certificate with SSL_kRSA. */ SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if (s->session->sess_cert->peer_rsa_tmp != NULL) rsa = s->session->sess_cert->peer_rsa_tmp; else { pkey = X509_get_pubkey(s->session-> sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC]. x509); if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } rsa = pkey->pkey.rsa; EVP_PKEY_free(pkey); } tmp_buf[0] = s->client_version >> 8; tmp_buf[1] = s->client_version & 0xff; if (RAND_bytes(&(tmp_buf[2]), sizeof tmp_buf - 2) <= 0) goto err; s->session->master_key_length = sizeof tmp_buf; q = p; /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) p += 2; n = RSA_public_encrypt(sizeof tmp_buf, tmp_buf, p, rsa, RSA_PKCS1_PADDING); # ifdef PKCS1_CHECK if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++; if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0] = 0x70; # endif if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_BAD_RSA_ENCRYPT); goto err; } /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) { s2n(n, q); n += 2; } s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(tmp_buf, sizeof tmp_buf); } #endif #ifndef OPENSSL_NO_KRB5 else if (alg_k & SSL_kKRB5) { krb5_error_code krb5rc; KSSL_CTX *kssl_ctx = s->kssl_ctx; /* krb5_data krb5_ap_req; */ krb5_data *enc_ticket; krb5_data authenticator, *authp = NULL; EVP_CIPHER_CTX ciph_ctx; const EVP_CIPHER *enc = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_IV_LENGTH]; int padl, outl = sizeof(epms); EVP_CIPHER_CTX_init(&ciph_ctx); # ifdef KSSL_DEBUG fprintf(stderr, "ssl3_send_client_key_exchange(%lx & %lx)\n", alg_k, SSL_kKRB5); # endif /* KSSL_DEBUG */ authp = NULL; # ifdef KRB5SENDAUTH if (KRB5SENDAUTH) authp = &authenticator; # endif /* KRB5SENDAUTH */ krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, &kssl_err); enc = kssl_map_enc(kssl_ctx->enctype); if (enc == NULL) goto err; # ifdef KSSL_DEBUG { fprintf(stderr, "kssl_cget_tkt rtn %d\n", krb5rc); if (krb5rc && kssl_err.text) fprintf(stderr, "kssl_cget_tkt kssl_err=%s\n", kssl_err.text); } # endif /* KSSL_DEBUG */ if (krb5rc) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } /*- * 20010406 VRS - Earlier versions used KRB5 AP_REQ * in place of RFC 2712 KerberosWrapper, as in: * * Send ticket (copy to *p, set n = length) * n = krb5_ap_req.length; * memcpy(p, krb5_ap_req.data, krb5_ap_req.length); * if (krb5_ap_req.data) * kssl_krb5_free_data_contents(NULL,&krb5_ap_req); * * Now using real RFC 2712 KerberosWrapper * (Thanks to Simon Wilkinson <sxw@sxw.org.uk>) * Note: 2712 "opaque" types are here replaced * with a 2-byte length followed by the value. * Example: * KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms * Where "xx xx" = length bytes. Shown here with * optional authenticator omitted. */ /* KerberosWrapper.Ticket */ s2n(enc_ticket->length, p); memcpy(p, enc_ticket->data, enc_ticket->length); p += enc_ticket->length; n = enc_ticket->length + 2; /* KerberosWrapper.Authenticator */ if (authp && authp->length) { s2n(authp->length, p); memcpy(p, authp->data, authp->length); p += authp->length; n += authp->length + 2; free(authp->data); authp->data = NULL; authp->length = 0; } else { s2n(0, p); /* null authenticator length */ n += 2; } tmp_buf[0] = s->client_version >> 8; tmp_buf[1] = s->client_version & 0xff; if (RAND_bytes(&(tmp_buf[2]), sizeof tmp_buf - 2) <= 0) goto err; /*- * 20010420 VRS. Tried it this way; failed. * EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL); * EVP_CIPHER_CTX_set_key_length(&ciph_ctx, * kssl_ctx->length); * EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv); */ memset(iv, 0, sizeof iv); /* per RFC 1510 */ EVP_EncryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv); EVP_EncryptUpdate(&ciph_ctx, epms, &outl, tmp_buf, sizeof tmp_buf); EVP_EncryptFinal_ex(&ciph_ctx, &(epms[outl]), &padl); outl += padl; if (outl > (int)sizeof epms) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } EVP_CIPHER_CTX_cleanup(&ciph_ctx); /* KerberosWrapper.EncryptedPreMasterSecret */ s2n(outl, p); memcpy(p, epms, outl); p += outl; n += outl + 2; s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(epms, outl); } #endif #ifndef OPENSSL_NO_DH else if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) { DH *dh_srvr, *dh_clnt; SESS_CERT *scert = s->session->sess_cert; if (scert == NULL) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE); goto err; } if (scert->peer_dh_tmp != NULL) dh_srvr = scert->peer_dh_tmp; else { /* we get them from the cert */ int idx = scert->peer_cert_type; EVP_PKEY *spkey = NULL; dh_srvr = NULL; if (idx >= 0) spkey = X509_get_pubkey(scert->peer_pkeys[idx].x509); if (spkey) { dh_srvr = EVP_PKEY_get1_DH(spkey); EVP_PKEY_free(spkey); } if (dh_srvr == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) { /* Use client certificate key */ EVP_PKEY *clkey = s->cert->key->privatekey; dh_clnt = NULL; if (clkey) dh_clnt = EVP_PKEY_get1_DH(clkey); if (dh_clnt == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } else { /* generate a new random key */ if ((dh_clnt = DHparams_dup(dh_srvr)) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } if (!DH_generate_key(dh_clnt)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB); DH_free(dh_clnt); goto err; } } /* * use the 'p' output buffer for the DH key, but make sure to * clear it out afterwards */ n = DH_compute_key(p, dh_srvr->pub_key, dh_clnt); if (scert->peer_dh_tmp == NULL) DH_free(dh_srvr); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB); DH_free(dh_clnt); goto err; } /* generate master key from the result */ s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, p, n); /* clean up */ memset(p, 0, n); if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) n = 0; else { /* send off the data */ n = BN_num_bytes(dh_clnt->pub_key); s2n(n, p); BN_bn2bin(dh_clnt->pub_key, p); n += 2; } DH_free(dh_clnt); /* perhaps clean things up a bit EAY EAY EAY EAY */ } #endif #ifndef OPENSSL_NO_ECDH else if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) { const EC_GROUP *srvr_group = NULL; EC_KEY *tkey; int ecdh_clnt_cert = 0; int field_size = 0; if (s->session->sess_cert == NULL) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE); goto err; } /* * Did we send out the client's ECDH share for use in premaster * computation as part of client certificate? If so, set * ecdh_clnt_cert to 1. */ if ((alg_k & (SSL_kECDHr | SSL_kECDHe)) && (s->cert != NULL)) { /*- * XXX: For now, we do not support client * authentication using ECDH certificates. * To add such support, one needs to add * code that checks for appropriate * conditions and sets ecdh_clnt_cert to 1. * For example, the cert have an ECC * key on the same curve as the server's * and the key should be authorized for * key agreement. * * One also needs to add code in ssl3_connect * to skip sending the certificate verify * message. * * if ((s->cert->key->privatekey != NULL) && * (s->cert->key->privatekey->type == * EVP_PKEY_EC) && ...) * ecdh_clnt_cert = 1; */ } if (s->session->sess_cert->peer_ecdh_tmp != NULL) { tkey = s->session->sess_cert->peer_ecdh_tmp; } else { /* Get the Server Public Key from Cert */ srvr_pub_pkey = X509_get_pubkey(s->session-> sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); if ((srvr_pub_pkey == NULL) || (srvr_pub_pkey->type != EVP_PKEY_EC) || (srvr_pub_pkey->pkey.ec == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } tkey = srvr_pub_pkey->pkey.ec; } srvr_group = EC_KEY_get0_group(tkey); srvr_ecpoint = EC_KEY_get0_public_key(tkey); if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((clnt_ecdh = EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } if (ecdh_clnt_cert) { /* * Reuse key info from our certificate We only need our * private key to perform the ECDH computation. */ const BIGNUM *priv_key; tkey = s->cert->key->privatekey->pkey.ec; priv_key = EC_KEY_get0_private_key(tkey); if (priv_key == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } } else { /* Generate a new ECDH key pair */ if (!(EC_KEY_generate_key(clnt_ecdh))) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } } /* * use the 'p' output buffer for the ECDH key, but make sure to * clear it out afterwards */ field_size = EC_GROUP_get_degree(srvr_group); if (field_size <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } n = ECDH_compute_key(p, (field_size + 7) / 8, srvr_ecpoint, clnt_ecdh, NULL); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } /* generate master key from the result */ s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, p, n); memset(p, 0, n); /* clean up */ if (ecdh_clnt_cert) { /* Send empty client key exch message */ n = 0; } else { /* * First check the size of encoding and allocate memory * accordingly. */ encoded_pt_len = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); encodedPoint = (unsigned char *) OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char)); bn_ctx = BN_CTX_new(); if ((encodedPoint == NULL) || (bn_ctx == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } /* Encode the public key */ n = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encoded_pt_len, bn_ctx); *p = n; /* length of encoded point */ /* Encoded point will be copied here */ p += 1; /* copy the point */ memcpy((unsigned char *)p, encodedPoint, n); /* increment n to account for length field */ n += 1; } /* Free allocated memory */ BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); } #endif /* !OPENSSL_NO_ECDH */ else if (alg_k & SSL_kGOST) { /* GOST key exchange message creation */ EVP_PKEY_CTX *pkey_ctx; X509 *peer_cert; size_t msglen; unsigned int md_len; int keytype; unsigned char premaster_secret[32], shared_ukm[32], tmp[256]; EVP_MD_CTX *ukm_hash; EVP_PKEY *pub_key; /* * Get server sertificate PKEY and create ctx from it */ peer_cert = s->session-> sess_cert->peer_pkeys[(keytype = SSL_PKEY_GOST01)].x509; if (!peer_cert) peer_cert = s->session-> sess_cert->peer_pkeys[(keytype = SSL_PKEY_GOST94)].x509; if (!peer_cert) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER); goto err; } pkey_ctx = EVP_PKEY_CTX_new(pub_key = X509_get_pubkey(peer_cert), NULL); /* * If we have send a certificate, and certificate key * * * parameters match those of server certificate, use * certificate key for key exchange */ /* Otherwise, generate ephemeral key pair */ EVP_PKEY_encrypt_init(pkey_ctx); /* Generate session key */ if (RAND_bytes(premaster_secret, 32) <= 0) { EVP_PKEY_CTX_free(pkey_ctx); goto err; } /* * If we have client certificate, use its secret as peer key */ if (s->s3->tmp.cert_req && s->cert->key->privatekey) { if (EVP_PKEY_derive_set_peer (pkey_ctx, s->cert->key->privatekey) <= 0) { /* * If there was an error - just ignore it. Ephemeral key * * would be used */ ERR_clear_error(); } } /* * Compute shared IV and store it in algorithm-specific context * data */ ukm_hash = EVP_MD_CTX_create(); EVP_DigestInit(ukm_hash, EVP_get_digestbynid(NID_id_GostR3411_94)); EVP_DigestUpdate(ukm_hash, s->s3->client_random, SSL3_RANDOM_SIZE); EVP_DigestUpdate(ukm_hash, s->s3->server_random, SSL3_RANDOM_SIZE); EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len); EVP_MD_CTX_destroy(ukm_hash); if (EVP_PKEY_CTX_ctrl (pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT, EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_LIBRARY_BUG); goto err; } /* Make GOST keytransport blob message */ /* * Encapsulate it into sequence */ *(p++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED; msglen = 255; if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, premaster_secret, 32) < 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_LIBRARY_BUG); goto err; } if (msglen >= 0x80) { *(p++) = 0x81; *(p++) = msglen & 0xff; n = msglen + 3; } else { *(p++) = msglen & 0xff; n = msglen + 2; } memcpy(p, tmp, msglen); /* Check if pubkey from client certificate was used */ if (EVP_PKEY_CTX_ctrl (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) { /* Set flag "skip certificate verify" */ s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY; } EVP_PKEY_CTX_free(pkey_ctx); s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, premaster_secret, 32); EVP_PKEY_free(pub_key); } #ifndef OPENSSL_NO_SRP else if (alg_k & SSL_kSRP) { if (s->srp_ctx.A != NULL) { /* send off the data */ n = BN_num_bytes(s->srp_ctx.A); s2n(n, p); BN_bn2bin(s->srp_ctx.A, p); n += 2; } else { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if (s->session->srp_username != NULL) OPENSSL_free(s->session->srp_username); s->session->srp_username = BUF_strdup(s->srp_ctx.login); if (s->session->srp_username == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if ((s->session->master_key_length = SRP_generate_client_master_secret(s, s->session->master_key)) < 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } #endif #ifndef OPENSSL_NO_PSK else if (alg_k & SSL_kPSK) { /* * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a * \0-terminated identity. The last byte is for us for simulating * strnlen. */ char identity[PSK_MAX_IDENTITY_LEN + 2]; size_t identity_len; unsigned char *t = NULL; unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4]; unsigned int pre_ms_len = 0, psk_len = 0; int psk_err = 1; n = 0; if (s->psk_client_callback == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_PSK_NO_CLIENT_CB); goto err; } memset(identity, 0, sizeof(identity)); psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint, identity, sizeof(identity) - 1, psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_len > PSK_MAX_PSK_LEN) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } else if (psk_len == 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_PSK_IDENTITY_NOT_FOUND); goto psk_err; } identity[PSK_MAX_IDENTITY_LEN + 1] = '\0'; identity_len = strlen(identity); if (identity_len > PSK_MAX_IDENTITY_LEN) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } /* create PSK pre_master_secret */ pre_ms_len = 2 + psk_len + 2 + psk_len; t = psk_or_pre_ms; memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len); s2n(psk_len, t); memset(t, 0, psk_len); t += psk_len; s2n(psk_len, t); if (s->session->psk_identity_hint != NULL) OPENSSL_free(s->session->psk_identity_hint); s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); if (s->ctx->psk_identity_hint != NULL && s->session->psk_identity_hint == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } if (s->session->psk_identity != NULL) OPENSSL_free(s->session->psk_identity); s->session->psk_identity = BUF_strdup(identity); if (s->session->psk_identity == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, psk_or_pre_ms, pre_ms_len); s2n(identity_len, p); memcpy(p, identity, identity_len); n = 2 + identity_len; psk_err = 0; psk_err: OPENSSL_cleanse(identity, sizeof(identity)); OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_err != 0) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); goto err; } } #endif else { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n); s->state = SSL3_ST_CW_KEY_EXCH_B; } /* SSL3_ST_CW_KEY_EXCH_B */ return ssl_do_write(s); err: #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); #endif s->state = SSL_ST_ERR; return (-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'client: reject handshakes with DH parameters < 768 bits. Since the client has no way of communicating her supported parameter range to the server, connections to servers that choose weak DH will simply fail. Reviewed-by: Kurt Roeckx <kurt@openssl.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 X509_STORE *init_revocation_store(EAP_TLS_CONF *conf) { X509_STORE *store = NULL; store = X509_STORE_new(); /* Load the CAs we trust */ if (conf->ca_file || conf->ca_path) if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) { radlog(L_ERR, "rlm_eap: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL)); radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file ); return NULL; } #ifdef X509_V_FLAG_CRL_CHECK if (conf->check_crl) X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK); #endif return store; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'Set X509_V_FLAG_CRL_CHECK_ALL'</s>
<s>[INST] Given the following code containing errors, provide 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 ssl3_get_client_key_exchange(SSL *s) { int i, al, ok; long n; unsigned long alg_k; unsigned char *p; #ifndef OPENSSL_NO_RSA RSA *rsa = NULL; EVP_PKEY *pkey = NULL; #endif #ifndef OPENSSL_NO_DH BIGNUM *pub = NULL; DH *dh_srvr, *dh_clnt = NULL; #endif #ifndef OPENSSL_NO_KRB5 KSSL_ERR kssl_err; #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH EC_KEY *srvr_ecdh = NULL; EVP_PKEY *clnt_pub_pkey = NULL; EC_POINT *clnt_ecpoint = NULL; BN_CTX *bn_ctx = NULL; #endif n = s->method->ssl_get_message(s, SSL3_ST_SR_KEY_EXCH_A, SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok); if (!ok) return ((int)n); p = (unsigned char *)s->init_msg; alg_k = s->s3->tmp.new_cipher->algorithm_mkey; #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH]; int decrypt_len; unsigned char decrypt_good, version_good; size_t j; /* FIX THIS UP EAY EAY EAY EAY */ if (s->s3->tmp.use_rsa_tmp) { if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL)) rsa = s->cert->rsa_tmp; /* * Don't do a callback because rsa_tmp should be sent already */ if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_MISSING_TMP_RSA_PKEY); goto f_err; } } else { pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey; if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_MISSING_RSA_CERTIFICATE); goto f_err; } rsa = pkey->pkey.rsa; } /* TLS and [incidentally] DTLS{0xFEFF} */ if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) { n2s(p, i); if (n != i + 2) { if (!(s->options & SSL_OP_TLS_D5_BUG)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG); goto f_err; } else p -= 2; } else n = i; } /* * Reject overly short RSA ciphertext because we want to be sure * that the buffer size makes it safe to iterate over the entire * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The * actual expected size is larger due to RSA padding, but the * bound is sufficient to be safe. */ if (n < SSL_MAX_MASTER_KEY_LENGTH) { al = SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG); goto f_err; } /* * We must not leak whether a decryption failure occurs because of * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246, * section 7.4.7.1). The code follows that advice of the TLS RFC and * generates a random premaster secret for the case that the decrypt * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */ /* * should be RAND_bytes, but we cannot work around a failure. */ if (RAND_pseudo_bytes(rand_premaster_secret, sizeof(rand_premaster_secret)) <= 0) goto err; decrypt_len = RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING); ERR_clear_error(); /* * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will * be 0xff if so and zero otherwise. */ decrypt_good = constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH); /* * If the version in the decrypted pre-master secret is correct then * version_good will be 0xff, otherwise it'll be zero. The * Klima-Pokorny-Rosa extension of Bleichenbacher's attack * (http://eprint.iacr.org/2003/052/) exploits the version number * check as a "bad version oracle". Thus version checks are done in * constant time and are treated like any other decryption error. */ version_good = constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8)); version_good &= constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff)); /* * The premaster secret must contain the same version number as the * ClientHello to detect version rollback attacks (strangely, the * protocol does not offer such protection for DH ciphersuites). * However, buggy clients exist that send the negotiated protocol * version instead if the server does not support the requested * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such * clients. */ if (s->options & SSL_OP_TLS_ROLLBACK_BUG) { unsigned char workaround_good; workaround_good = constant_time_eq_8(p[0], (unsigned)(s->version >> 8)); workaround_good &= constant_time_eq_8(p[1], (unsigned)(s->version & 0xff)); version_good |= workaround_good; } /* * Both decryption and version must be good for decrypt_good to * remain non-zero (0xff). */ decrypt_good &= version_good; /* * Now copy rand_premaster_secret over from p using * decrypt_good_mask. If decryption failed, then p does not * contain valid plaintext, however, a check above guarantees * it is still sufficiently large to read from. */ for (j = 0; j < sizeof(rand_premaster_secret); j++) { p[j] = constant_time_select_8(decrypt_good, p[j], rand_premaster_secret[j]); } s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, p, sizeof (rand_premaster_secret)); OPENSSL_cleanse(p, sizeof(rand_premaster_secret)); } else #endif #ifndef OPENSSL_NO_DH if (alg_k & (SSL_kEDH | SSL_kDHr | SSL_kDHd)) { int idx = -1; EVP_PKEY *skey = NULL; if (n > 1) { n2s(p, i); } else { if (alg_k & SSL_kDHE) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG); goto f_err; } i = 0; } if (n && n != i + 2) { if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG); goto err; } else { p -= 2; i = (int)n; } } if (alg_k & SSL_kDHr) idx = SSL_PKEY_DH_RSA; else if (alg_k & SSL_kDHd) idx = SSL_PKEY_DH_DSA; if (idx >= 0) { skey = s->cert->pkeys[idx].privatekey; if ((skey == NULL) || (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_MISSING_RSA_CERTIFICATE); goto f_err; } dh_srvr = skey->pkey.dh; } else if (s->s3->tmp.dh == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_MISSING_TMP_DH_KEY); goto f_err; } else dh_srvr = s->s3->tmp.dh; if (n == 0L) { /* Get pubkey from cert */ EVP_PKEY *clkey = X509_get_pubkey(s->session->peer); if (clkey) { if (EVP_PKEY_cmp_parameters(clkey, skey) == 1) dh_clnt = EVP_PKEY_get1_DH(clkey); } if (dh_clnt == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_MISSING_TMP_DH_KEY); goto f_err; } EVP_PKEY_free(clkey); pub = dh_clnt->pub_key; } else pub = BN_bin2bn(p, i, NULL); if (pub == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB); goto err; } i = DH_compute_key(p, pub, dh_srvr); if (i <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB); BN_clear_free(pub); goto err; } DH_free(s->s3->tmp.dh); s->s3->tmp.dh = NULL; if (dh_clnt) DH_free(dh_clnt); else BN_clear_free(pub); pub = NULL; s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, p, i); OPENSSL_cleanse(p, i); if (dh_clnt) return 2; } else #endif #ifndef OPENSSL_NO_KRB5 if (alg_k & SSL_kKRB5) { krb5_error_code krb5rc; krb5_data enc_ticket; krb5_data authenticator; krb5_data enc_pms; KSSL_CTX *kssl_ctx = s->kssl_ctx; EVP_CIPHER_CTX ciph_ctx; const EVP_CIPHER *enc = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH]; int padl, outl; krb5_timestamp authtime = 0; krb5_ticket_times ttimes; int kerr = 0; EVP_CIPHER_CTX_init(&ciph_ctx); if (!kssl_ctx) kssl_ctx = kssl_ctx_new(); n2s(p, i); enc_ticket.length = i; if (n < (long)(enc_ticket.length + 6)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } enc_ticket.data = (char *)p; p += enc_ticket.length; n2s(p, i); authenticator.length = i; if (n < (long)(enc_ticket.length + authenticator.length + 6)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } authenticator.data = (char *)p; p += authenticator.length; n2s(p, i); enc_pms.length = i; enc_pms.data = (char *)p; p += enc_pms.length; /* * Note that the length is checked again below, ** after decryption */ if (enc_pms.length > sizeof pms) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if (n != (long)(enc_ticket.length + authenticator.length + enc_pms.length + 6)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes, &kssl_err)) != 0) { # ifdef KSSL_DEBUG fprintf(stderr, "kssl_sget_tkt rtn %d [%d]\n", krb5rc, kssl_err.reason); if (kssl_err.text) fprintf(stderr, "kssl_err text= %s\n", kssl_err.text); # endif /* KSSL_DEBUG */ SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } /* * Note: no authenticator is not considered an error, ** but will * return authtime == 0. */ if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator, &authtime, &kssl_err)) != 0) { # ifdef KSSL_DEBUG fprintf(stderr, "kssl_check_authent rtn %d [%d]\n", krb5rc, kssl_err.reason); if (kssl_err.text) fprintf(stderr, "kssl_err text= %s\n", kssl_err.text); # endif /* KSSL_DEBUG */ SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc); goto err; } # ifdef KSSL_DEBUG kssl_ctx_show(kssl_ctx); # endif /* KSSL_DEBUG */ enc = kssl_map_enc(kssl_ctx->enctype); if (enc == NULL) goto err; memset(iv, 0, sizeof iv); /* per RFC 1510 */ if (!EVP_DecryptInit_ex(&ciph_ctx, enc, NULL, kssl_ctx->key, iv)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); goto err; } if (!EVP_DecryptUpdate(&ciph_ctx, pms, &outl, (unsigned char *)enc_pms.data, enc_pms.length)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); kerr = 1; goto kclean; } if (outl > SSL_MAX_MASTER_KEY_LENGTH) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); kerr = 1; goto kclean; } if (!EVP_DecryptFinal_ex(&ciph_ctx, &(pms[outl]), &padl)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); kerr = 1; goto kclean; } outl += padl; if (outl > SSL_MAX_MASTER_KEY_LENGTH) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); kerr = 1; goto kclean; } if (!((pms[0] == (s->client_version >> 8)) && (pms[1] == (s->client_version & 0xff)))) { /* * The premaster secret must contain the same version number as * the ClientHello to detect version rollback attacks (strangely, * the protocol does not offer such protection for DH * ciphersuites). However, buggy clients exist that send random * bytes instead of the protocol version. If * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. * (Perhaps we should have a separate BUG value for the Kerberos * cipher) */ if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_AD_DECODE_ERROR); kerr = 1; goto kclean; } } EVP_CIPHER_CTX_cleanup(&ciph_ctx); s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, pms, outl); if (kssl_ctx->client_princ) { size_t len = strlen(kssl_ctx->client_princ); if (len < SSL_MAX_KRB5_PRINCIPAL_LENGTH) { s->session->krb5_client_princ_len = len; memcpy(s->session->krb5_client_princ, kssl_ctx->client_princ, len); } } /*- Was doing kssl_ctx_free() here, * but it caused problems for apache. * kssl_ctx = kssl_ctx_free(kssl_ctx); * if (s->kssl_ctx) s->kssl_ctx = NULL; */ kclean: OPENSSL_cleanse(pms, sizeof(pms)); if (kerr) goto err; } else #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH if (alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe)) { int ret = 1; int field_size = 0; const EC_KEY *tkey; const EC_GROUP *group; const BIGNUM *priv_key; /* initialize structures for server's ECDH key pair */ if ((srvr_ecdh = EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } /* Let's get server private key and group information */ if (alg_k & (SSL_kECDHr | SSL_kECDHe)) { /* use the certificate */ tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec; } else { /* * use the ephermeral values we saved when generating the * ServerKeyExchange msg. */ tkey = s->s3->tmp.ecdh; } group = EC_KEY_get0_group(tkey); priv_key = EC_KEY_get0_private_key(tkey); if (!EC_KEY_set_group(srvr_ecdh, group) || !EC_KEY_set_private_key(srvr_ecdh, priv_key)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } /* Let's get client's public key */ if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if (n == 0L) { /* Client Publickey was in Client Certificate */ if (alg_k & SSL_kEECDH) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_MISSING_TMP_ECDH_KEY); goto f_err; } if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer)) == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) { /* * XXX: For now, we do not support client authentication * using ECDH certificates so this branch (n == 0L) of the * code is never executed. When that support is added, we * ought to ensure the key received in the certificate is * authorized for key agreement. ECDH_compute_key implicitly * checks that the two ECDH shares are for the same group. */ al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNABLE_TO_DECODE_ECDH_CERTS); goto f_err; } if (EC_POINT_copy(clnt_ecpoint, EC_KEY_get0_public_key(clnt_pub_pkey-> pkey.ec)) == 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } ret = 2; /* Skip certificate verify processing */ } else { /* * Get client's public key from encoded point in the * ClientKeyExchange message. */ if ((bn_ctx = BN_CTX_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } /* Get encoded point length */ i = *p; p += 1; if (n != 1 + i) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } /* * p is pointing to somewhere in the buffer currently, so set it * to the start */ p = (unsigned char *)s->init_buf->data; } /* Compute the shared pre-master secret */ field_size = EC_GROUP_get_degree(group); if (field_size <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh, NULL); if (i <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } EVP_PKEY_free(clnt_pub_pkey); EC_POINT_free(clnt_ecpoint); EC_KEY_free(srvr_ecdh); BN_CTX_free(bn_ctx); EC_KEY_free(s->s3->tmp.ecdh); s->s3->tmp.ecdh = NULL; /* Compute the master secret */ s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, p, i); OPENSSL_cleanse(p, i); return (ret); } else #endif #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { unsigned char *t = NULL; unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4]; unsigned int pre_ms_len = 0, psk_len = 0; int psk_err = 1; char tmp_id[PSK_MAX_IDENTITY_LEN + 1]; al = SSL_AD_HANDSHAKE_FAILURE; n2s(p, i); if (n != i + 2) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH); goto psk_err; } if (i > PSK_MAX_IDENTITY_LEN) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto psk_err; } if (s->psk_server_callback == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_PSK_NO_SERVER_CB); goto psk_err; } /* * Create guaranteed NULL-terminated identity string for the callback */ memcpy(tmp_id, p, i); memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i); psk_len = s->psk_server_callback(s, tmp_id, psk_or_pre_ms, sizeof(psk_or_pre_ms)); OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1); if (psk_len > PSK_MAX_PSK_LEN) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } else if (psk_len == 0) { /* * PSK related to the given identity not found */ SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_PSK_IDENTITY_NOT_FOUND); al = SSL_AD_UNKNOWN_PSK_IDENTITY; goto psk_err; } /* create PSK pre_master_secret */ pre_ms_len = 2 + psk_len + 2 + psk_len; t = psk_or_pre_ms; memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len); s2n(psk_len, t); memset(t, 0, psk_len); t += psk_len; s2n(psk_len, t); if (s->session->psk_identity != NULL) OPENSSL_free(s->session->psk_identity); s->session->psk_identity = BUF_strdup((char *)p); if (s->session->psk_identity == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } if (s->session->psk_identity_hint != NULL) OPENSSL_free(s->session->psk_identity_hint); s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); if (s->ctx->psk_identity_hint != NULL && s->session->psk_identity_hint == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, psk_or_pre_ms, pre_ms_len); psk_err = 0; psk_err: OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_err != 0) goto f_err; } else #endif #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { int param_len; n2s(p, i); param_len = i + 2; if (param_len > n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BAD_SRP_A_LENGTH); goto f_err; } if (!(s->srp_ctx.A = BN_bin2bn(p, i, NULL))) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB); goto err; } if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BAD_SRP_PARAMETERS); goto f_err; } if (s->session->srp_username != NULL) OPENSSL_free(s->session->srp_username); s->session->srp_username = BUF_strdup(s->srp_ctx.login); if (s->session->srp_username == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if ((s->session->master_key_length = SRP_generate_server_master_secret(s, s->session->master_key)) < 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } p += i; } else #endif /* OPENSSL_NO_SRP */ if (alg_k & SSL_kGOST) { int ret = 0; EVP_PKEY_CTX *pkey_ctx; EVP_PKEY *client_pub_pkey = NULL, *pk = NULL; unsigned char premaster_secret[32], *start; size_t outlen = 32, inlen; unsigned long alg_a; int Ttag, Tclass; long Tlen; /* Get our certificate private key */ alg_a = s->s3->tmp.new_cipher->algorithm_auth; if (alg_a & SSL_aGOST94) pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey; else if (alg_a & SSL_aGOST01) pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey; pkey_ctx = EVP_PKEY_CTX_new(pk, NULL); EVP_PKEY_decrypt_init(pkey_ctx); /* * If client certificate is present and is of the same type, maybe * use it for key exchange. Don't mind errors from * EVP_PKEY_derive_set_peer, because it is completely valid to use a * client certificate for authorization only. */ client_pub_pkey = X509_get_pubkey(s->session->peer); if (client_pub_pkey) { if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0) ERR_clear_error(); } /* Decrypt session key */ if (ASN1_get_object ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); goto gerr; } start = p; inlen = Tlen; if (EVP_PKEY_decrypt (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); goto gerr; } /* Generate master secret */ s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s-> session->master_key, premaster_secret, 32); OPENSSL_cleanse(premaster_secret, sizeof(premaster_secret)); /* Check if pubkey from client certificate was used */ if (EVP_PKEY_CTX_ctrl (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) ret = 2; else ret = 1; gerr: EVP_PKEY_free(client_pub_pkey); EVP_PKEY_CTX_free(pkey_ctx); if (ret) return ret; else goto err; } else { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE); goto f_err; } return (1); f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP) err: #endif #ifndef OPENSSL_NO_ECDH EVP_PKEY_free(clnt_pub_pkey); EC_POINT_free(clnt_ecpoint); if (srvr_ecdh != NULL) EC_KEY_free(srvr_ecdh); BN_CTX_free(bn_ctx); #endif s->state = SSL_ST_ERR; return (-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix PSK handling. The PSK identity hint should be stored in the SSL_SESSION structure and not in the parent context (which will overwrite values used by other SSL structures with the same SSL_CTX). Use BUF_strndup when copying identity as it may not be null terminated. Reviewed-by: Tim Hudson <tjh@openssl.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: TIFFRGBAImageOK(TIFF* tif, char emsg[1024]) { TIFFDirectory* td = &tif->tif_dir; uint16 photometric; int colorchannels; if (!tif->tif_decodestatus) { sprintf(emsg, "Sorry, requested compression method is not configured"); return (0); } switch (td->td_bitspersample) { case 1: case 2: case 4: case 8: case 16: break; default: sprintf(emsg, "Sorry, can not handle images with %d-bit samples", td->td_bitspersample); return (0); } colorchannels = td->td_samplesperpixel - td->td_extrasamples; if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) { switch (colorchannels) { case 1: photometric = PHOTOMETRIC_MINISBLACK; break; case 3: photometric = PHOTOMETRIC_RGB; break; default: sprintf(emsg, "Missing needed %s tag", photoTag); return (0); } } switch (photometric) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: if (td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_samplesperpixel != 1 && td->td_bitspersample < 8 ) { sprintf(emsg, "Sorry, can not handle contiguous data with %s=%d, " "and %s=%d and Bits/Sample=%d", photoTag, photometric, "Samples/pixel", td->td_samplesperpixel, td->td_bitspersample); return (0); } /* * We should likely validate that any extra samples are either * to be ignored, or are alpha, and if alpha we should try to use * them. But for now we won't bother with this. */ break; case PHOTOMETRIC_YCBCR: /* * TODO: if at all meaningful and useful, make more complete * support check here, or better still, refactor to let supporting * code decide whether there is support and what meaningfull * error to return */ break; case PHOTOMETRIC_RGB: if (colorchannels < 3) { sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", "Color channels", colorchannels); return (0); } break; case PHOTOMETRIC_SEPARATED: { uint16 inkset; TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset); if (inkset != INKSET_CMYK) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "InkSet", inkset); return 0; } if (td->td_samplesperpixel < 4) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "Samples/pixel", td->td_samplesperpixel); return 0; } break; } case PHOTOMETRIC_LOGL: if (td->td_compression != COMPRESSION_SGILOG) { sprintf(emsg, "Sorry, LogL data must have %s=%d", "Compression", COMPRESSION_SGILOG); return (0); } break; case PHOTOMETRIC_LOGLUV: if (td->td_compression != COMPRESSION_SGILOG && td->td_compression != COMPRESSION_SGILOG24) { sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); return (0); } if (td->td_planarconfig != PLANARCONFIG_CONTIG) { sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", "Planarconfiguration", td->td_planarconfig); return (0); } if( td->td_samplesperpixel != 3 ) { sprintf(emsg, "Sorry, can not handle image with %s=%d", "Samples/pixel", td->td_samplesperpixel); return 0; } break; case PHOTOMETRIC_CIELAB: if( td->td_samplesperpixel != 3 || td->td_bitspersample != 8 ) { sprintf(emsg, "Sorry, can not handle image with %s=%d and %s=%d", "Samples/pixel", td->td_samplesperpixel, "Bits/sample", td->td_bitspersample); return 0; } break; default: sprintf(emsg, "Sorry, can not handle image with %s=%d", photoTag, photometric); return (0); } return (1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': '* libtiff/tif_getimage.c: fix out-of-bound reads in TIFFRGBAImage interface in case of unsupported values of SamplesPerPixel/ExtraSamples for LogLUV / CIELab. Add explicit call to TIFFRGBAImageOK() in TIFFRGBAImageBegin(). Fix CVE-2015-8665 reported by limingxing and CVE-2015-8683 reported by zzf of Alibaba.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: LogLuvEncode24(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { LogLuvState* sp = EncoderState(tif); tmsize_t i; tmsize_t npixels; tmsize_t occ; uint8* op; uint32* tp; assert(s == 0); assert(sp != NULL); npixels = cc / sp->pixel_size; if (sp->user_datafmt == SGILOGDATAFMT_RAW) tp = (uint32*) bp; else { tp = (uint32*) sp->tbuf; assert(sp->tbuflen >= npixels); (*sp->tfunc)(sp, bp, npixels); } /* write out encoded pixels */ op = tif->tif_rawcp; occ = tif->tif_rawdatasize - tif->tif_rawcc; for (i = npixels; i--; ) { if (occ < 3) { tif->tif_rawcp = op; tif->tif_rawcc = tif->tif_rawdatasize - occ; if (!TIFFFlushData1(tif)) return (-1); op = tif->tif_rawcp; occ = tif->tif_rawdatasize - tif->tif_rawcc; } *op++ = (uint8)(*tp >> 16); *op++ = (uint8)(*tp >> 8 & 0xff); *op++ = (uint8)(*tp++ & 0xff); occ -= 3; } tif->tif_rawcp = op; tif->tif_rawcc = tif->tif_rawdatasize - occ; return (1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': '* libtiff/tif_luv.c: fix potential out-of-bound writes in decode functions in non debug builds by replacing assert()s by regular if checks (bugzilla #2522). Fix potential out-of-bound reads in case of short input data.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top, unsigned char *buf, int idx, int width) { size_t i, j; if (bn_wexpand(b, top) == NULL) return 0; for (i = 0, j = idx; i < top * sizeof b->d[0]; i++, j += width) { ((unsigned char *)b->d)[i] = buf[j]; } b->top = top; bn_correct_top(b); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'bn/bn_exp.c: constant-time MOD_EXP_CTIME_COPY_FROM_PREBUF. Performance penalty varies from platform to platform, and even key length. For rsa2048 sign it was observed to reach almost 10%. CVE-2016-0702 Reviewed-by: Richard Levitte <levitte@openssl.org> Reviewed-by: Rich Salz <rsalz@openssl.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: _dopr(char **sbuffer, char **buffer, size_t *maxlen, size_t *retlen, int *truncated, const char *format, va_list args) { char ch; LLONG value; LDOUBLE fvalue; char *strvalue; int min; int max; int state; int flags; int cflags; size_t currlen; state = DP_S_DEFAULT; flags = currlen = cflags = min = 0; max = -1; ch = *format++; while (state != DP_S_DONE) { if (ch == '\0' || (buffer == NULL && currlen >= *maxlen)) state = DP_S_DONE; switch (state) { case DP_S_DEFAULT: if (ch == '%') state = DP_S_FLAGS; else doapr_outch(sbuffer, buffer, &currlen, maxlen, ch); ch = *format++; break; case DP_S_FLAGS: switch (ch) { case '-': flags |= DP_F_MINUS; ch = *format++; break; case '+': flags |= DP_F_PLUS; ch = *format++; break; case ' ': flags |= DP_F_SPACE; ch = *format++; break; case '#': flags |= DP_F_NUM; ch = *format++; break; case '0': flags |= DP_F_ZERO; ch = *format++; break; default: state = DP_S_MIN; break; } break; case DP_S_MIN: if (isdigit((unsigned char)ch)) { min = 10 * min + char_to_int(ch); ch = *format++; } else if (ch == '*') { min = va_arg(args, int); ch = *format++; state = DP_S_DOT; } else state = DP_S_DOT; break; case DP_S_DOT: if (ch == '.') { state = DP_S_MAX; ch = *format++; } else state = DP_S_MOD; break; case DP_S_MAX: if (isdigit((unsigned char)ch)) { if (max < 0) max = 0; max = 10 * max + char_to_int(ch); ch = *format++; } else if (ch == '*') { max = va_arg(args, int); ch = *format++; state = DP_S_MOD; } else state = DP_S_MOD; break; case DP_S_MOD: switch (ch) { case 'h': cflags = DP_C_SHORT; ch = *format++; break; case 'l': if (*format == 'l') { cflags = DP_C_LLONG; format++; } else cflags = DP_C_LONG; ch = *format++; break; case 'q': cflags = DP_C_LLONG; ch = *format++; break; case 'L': cflags = DP_C_LDOUBLE; ch = *format++; break; default: break; } state = DP_S_CONV; break; case DP_S_CONV: switch (ch) { case 'd': case 'i': switch (cflags) { case DP_C_SHORT: value = (short int)va_arg(args, int); break; case DP_C_LONG: value = va_arg(args, long int); break; case DP_C_LLONG: value = va_arg(args, LLONG); break; default: value = va_arg(args, int); break; } fmtint(sbuffer, buffer, &currlen, maxlen, value, 10, min, max, flags); break; case 'X': flags |= DP_F_UP; /* FALLTHROUGH */ case 'x': case 'o': case 'u': flags |= DP_F_UNSIGNED; switch (cflags) { case DP_C_SHORT: value = (unsigned short int)va_arg(args, unsigned int); break; case DP_C_LONG: value = (LLONG) va_arg(args, unsigned long int); break; case DP_C_LLONG: value = va_arg(args, unsigned LLONG); break; default: value = (LLONG) va_arg(args, unsigned int); break; } fmtint(sbuffer, buffer, &currlen, maxlen, value, ch == 'o' ? 8 : (ch == 'u' ? 10 : 16), min, max, flags); break; case 'f': if (cflags == DP_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); fmtfp(sbuffer, buffer, &currlen, maxlen, fvalue, min, max, flags); break; case 'E': flags |= DP_F_UP; case 'e': if (cflags == DP_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); break; case 'G': flags |= DP_F_UP; case 'g': if (cflags == DP_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); break; case 'c': doapr_outch(sbuffer, buffer, &currlen, maxlen, va_arg(args, int)); break; case 's': strvalue = va_arg(args, char *); if (max < 0) { if (buffer) max = INT_MAX; else max = *maxlen; } fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue, flags, min, max); break; case 'p': value = (long)va_arg(args, void *); fmtint(sbuffer, buffer, &currlen, maxlen, value, 16, min, max, flags | DP_F_NUM); break; case 'n': /* XXX */ if (cflags == DP_C_SHORT) { short int *num; num = va_arg(args, short int *); *num = currlen; } else if (cflags == DP_C_LONG) { /* XXX */ long int *num; num = va_arg(args, long int *); *num = (long int)currlen; } else if (cflags == DP_C_LLONG) { /* XXX */ LLONG *num; num = va_arg(args, LLONG *); *num = (LLONG) currlen; } else { int *num; num = va_arg(args, int *); *num = currlen; } break; case '%': doapr_outch(sbuffer, buffer, &currlen, maxlen, ch); break; case 'w': /* not supported yet, treat as next char */ ch = *format++; break; default: /* unknown, skip */ break; } ch = *format++; state = DP_S_DEFAULT; flags = cflags = min = 0; max = -1; break; case DP_S_DONE: break; default: break; } } *truncated = (currlen > *maxlen - 1); if (*truncated) currlen = *maxlen - 1; doapr_outch(sbuffer, buffer, &currlen, maxlen, '\0'); *retlen = currlen - 1; return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix memory issues in BIO_*printf functions The internal |fmtstr| function used in processing a "%s" format string in the BIO_*printf functions could overflow while calculating the length of a string and cause an OOB read when printing very long strings. Additionally the internal |doapr_outch| function can attempt to write to an OOB memory location (at an offset from the NULL pointer) in the event of a memory allocation failure. In 1.0.2 and below this could be caused where the size of a buffer to be allocated is greater than INT_MAX. E.g. this could be in processing a very long "%s" format string. Memory leaks can also occur. These issues will only occur on certain platforms where sizeof(size_t) > sizeof(int). E.g. many 64 bit systems. The first issue may mask the second issue dependent on compiler behaviour. These problems could enable attacks where large amounts of untrusted data is passed to the BIO_*printf functions. If applications use these functions in this way then they could be vulnerable. OpenSSL itself uses these functions when printing out human-readable dumps of ASN.1 data. Therefore applications that print this data could be vulnerable if the data is from untrusted sources. OpenSSL command line applications could also be vulnerable where they print out ASN.1 data, or if untrusted data is passed as command line arguments. Libssl is not considered directly vulnerable. Additionally certificates etc received via remote connections via libssl are also unlikely to be able to trigger these issues because of message size limits enforced within libssl. CVE-2016-0799 Issue reported by Guido Vranken. Reviewed-by: Andy Polyakov <appro@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int i, j; unsigned int total = 0; *outl = 0; if (inl <= 0) return; OPENSSL_assert(ctx->length <= (int)sizeof(ctx->enc_data)); if ((ctx->num + inl) < ctx->length) { memcpy(&(ctx->enc_data[ctx->num]), in, inl); ctx->num += inl; return; } if (ctx->num != 0) { i = ctx->length - ctx->num; memcpy(&(ctx->enc_data[ctx->num]), in, i); in += i; inl -= i; j = EVP_EncodeBlock(out, ctx->enc_data, ctx->length); ctx->num = 0; out += j; *(out++) = '\n'; *out = '\0'; total = j + 1; } while (inl >= ctx->length) { j = EVP_EncodeBlock(out, in, ctx->length); in += ctx->length; inl -= ctx->length; out += j; *(out++) = '\n'; *out = '\0'; total += j + 1; } if (inl != 0) memcpy(&(ctx->enc_data[0]), in, inl); ctx->num = inl; *outl = total; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-189'], 'message': 'Avoid overflow in EVP_EncodeUpdate An overflow can occur in the EVP_EncodeUpdate function which is used for Base64 encoding of binary data. If an attacker is able to supply very large amounts of input data then a length check can overflow resulting in a heap corruption. Due to the very large amounts of data involved this will most likely result in a crash. Internally to OpenSSL the EVP_EncodeUpdate function is primarly used by the PEM_write_bio* family of functions. These are mainly used within the OpenSSL command line applications, so any application which processes data from an untrusted source and outputs it as a PEM file should be considered vulnerable to this issue. User applications that call these APIs directly with large amounts of untrusted data may also be vulnerable. Issue reported by Guido Vranken. CVE-2016-2105 Reviewed-by: Richard Levitte <levitte@openssl.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: rsvg_state_inherit_run (RsvgState * dst, const RsvgState * src, const InheritanceFunction function, const gboolean inherituninheritables) { gint i; if (function (dst->has_current_color, src->has_current_color)) dst->current_color = src->current_color; if (function (dst->has_flood_color, src->has_flood_color)) dst->flood_color = src->flood_color; if (function (dst->has_flood_opacity, src->has_flood_opacity)) dst->flood_opacity = src->flood_opacity; if (function (dst->has_fill_server, src->has_fill_server)) { rsvg_paint_server_ref (src->fill); if (dst->fill) rsvg_paint_server_unref (dst->fill); dst->fill = src->fill; } if (function (dst->has_fill_opacity, src->has_fill_opacity)) dst->fill_opacity = src->fill_opacity; if (function (dst->has_fill_rule, src->has_fill_rule)) dst->fill_rule = src->fill_rule; if (function (dst->has_clip_rule, src->has_clip_rule)) dst->clip_rule = src->clip_rule; if (function (dst->overflow, src->overflow)) dst->overflow = src->overflow; if (function (dst->has_stroke_server, src->has_stroke_server)) { rsvg_paint_server_ref (src->stroke); if (dst->stroke) rsvg_paint_server_unref (dst->stroke); dst->stroke = src->stroke; } if (function (dst->has_stroke_opacity, src->has_stroke_opacity)) dst->stroke_opacity = src->stroke_opacity; if (function (dst->has_stroke_width, src->has_stroke_width)) dst->stroke_width = src->stroke_width; if (function (dst->has_miter_limit, src->has_miter_limit)) dst->miter_limit = src->miter_limit; if (function (dst->has_cap, src->has_cap)) dst->cap = src->cap; if (function (dst->has_join, src->has_join)) dst->join = src->join; if (function (dst->has_stop_color, src->has_stop_color)) dst->stop_color = src->stop_color; if (function (dst->has_stop_opacity, src->has_stop_opacity)) dst->stop_opacity = src->stop_opacity; if (function (dst->has_cond, src->has_cond)) dst->cond_true = src->cond_true; if (function (dst->has_font_size, src->has_font_size)) dst->font_size = src->font_size; if (function (dst->has_font_style, src->has_font_style)) dst->font_style = src->font_style; if (function (dst->has_font_variant, src->has_font_variant)) dst->font_variant = src->font_variant; if (function (dst->has_font_weight, src->has_font_weight)) dst->font_weight = src->font_weight; if (function (dst->has_font_stretch, src->has_font_stretch)) dst->font_stretch = src->font_stretch; if (function (dst->has_font_decor, src->has_font_decor)) dst->font_decor = src->font_decor; if (function (dst->has_text_dir, src->has_text_dir)) dst->text_dir = src->text_dir; if (function (dst->has_text_gravity, src->has_text_gravity)) dst->text_gravity = src->text_gravity; if (function (dst->has_unicode_bidi, src->has_unicode_bidi)) dst->unicode_bidi = src->unicode_bidi; if (function (dst->has_text_anchor, src->has_text_anchor)) dst->text_anchor = src->text_anchor; if (function (dst->has_letter_spacing, src->has_letter_spacing)) dst->letter_spacing = src->letter_spacing; if (function (dst->has_startMarker, src->has_startMarker)) dst->startMarker = src->startMarker; if (function (dst->has_middleMarker, src->has_middleMarker)) dst->middleMarker = src->middleMarker; if (function (dst->has_endMarker, src->has_endMarker)) dst->endMarker = src->endMarker; if (function (dst->has_shape_rendering_type, src->has_shape_rendering_type)) dst->shape_rendering_type = src->shape_rendering_type; if (function (dst->has_text_rendering_type, src->has_text_rendering_type)) dst->text_rendering_type = src->text_rendering_type; if (function (dst->has_font_family, src->has_font_family)) { g_free (dst->font_family); /* font_family is always set to something */ dst->font_family = g_strdup (src->font_family); } if (function (dst->has_space_preserve, src->has_space_preserve)) dst->space_preserve = src->space_preserve; if (function (dst->has_visible, src->has_visible)) dst->visible = src->visible; if (function (dst->has_lang, src->has_lang)) { if (dst->has_lang) g_free (dst->lang); dst->lang = g_strdup (src->lang); } if (src->dash.n_dash > 0 && (function (dst->has_dash, src->has_dash))) { if (dst->has_dash) g_free (dst->dash.dash); dst->dash.dash = g_new (gdouble, src->dash.n_dash); dst->dash.n_dash = src->dash.n_dash; for (i = 0; i < src->dash.n_dash; i++) dst->dash.dash[i] = src->dash.dash[i]; } if (function (dst->has_dashoffset, src->has_dashoffset)) { dst->dash.offset = src->dash.offset; } if (inherituninheritables) { dst->clip_path_ref = src->clip_path_ref; dst->mask = src->mask; dst->enable_background = src->enable_background; dst->adobe_blend = src->adobe_blend; dst->opacity = src->opacity; dst->filter = src->filter; dst->comp_op = src->comp_op; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'state: Store mask as reference Instead of immediately looking up the mask, store the reference and look it up on use.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Address Zone::NewExpand(int size) { // Make sure the requested size is already properly aligned and that // there isn't enough room in the Zone to satisfy the request. ASSERT(size == RoundDown(size, kAlignment)); ASSERT(size > limit_ - position_); // Compute the new segment size. We use a 'high water mark' // strategy, where we increase the segment size every time we expand // except that we employ a maximum segment size when we delete. This // is to avoid excessive malloc() and free() overhead. Segment* head = segment_head_; int old_size = (head == NULL) ? 0 : head->size(); static const int kSegmentOverhead = sizeof(Segment) + kAlignment; int new_size_no_overhead = size + (old_size << 1); int new_size = kSegmentOverhead + new_size_no_overhead; // Guard against integer overflow. if (new_size_no_overhead < size || new_size < kSegmentOverhead) { V8::FatalProcessOutOfMemory("Zone"); return NULL; } if (new_size < kMinimumSegmentSize) { new_size = kMinimumSegmentSize; } else if (new_size > kMaximumSegmentSize) { // Limit the size of new segments to avoid growing the segment size // exponentially, thus putting pressure on contiguous virtual address space. // All the while making sure to allocate a segment large enough to hold the // requested size. new_size = Max(kSegmentOverhead + size, kMaximumSegmentSize); } Segment* segment = NewSegment(new_size); if (segment == NULL) { V8::FatalProcessOutOfMemory("Zone"); return NULL; } // Recompute 'top' and 'limit' based on the new segment. Address result = RoundUp(segment->start(), kAlignment); position_ = result + size; // Check for address overflow. if (position_ < result) { V8::FatalProcessOutOfMemory("Zone"); return NULL; } limit_ = segment->end(); ASSERT(position_ <= limit_); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'deps: backport 3a9bfec from v8 upstream Some of the logic from `zone.cc` is found in `zone-inl.h` in this release stream. Original commit message: Fix overflow issue in Zone::New When requesting a large allocation near the end of the address space, the computation could overflow and erroneously *not* grow the Zone as required. BUG=chromium:606115 LOG=y Review-Url: https://codereview.chromium.org/1930873002 Cr-Commit-Position: refs/heads/master@{#35903} PR-URL: https://github.com/nodejs/node-private/pull/43 Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Rod Vagg <rod@vagg.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 ssl_parse_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) { unsigned short length; unsigned short type; unsigned short size; unsigned char *data = *p; int tlsext_servername = 0; int renegotiate_seen = 0; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif s->tlsext_ticket_expected = 0; # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif if (data >= (d + n - 2)) goto ri_check; n2s(data, length); if (data + length != d + n) { *al = SSL_AD_DECODE_ERROR; return 0; } while (data <= (d + n - 4)) { n2s(data, type); n2s(data, size); if (data + size > (d + n)) goto ri_check; if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg); if (type == TLSEXT_TYPE_server_name) { if (s->tlsext_hostname == NULL || size > 0) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } tlsext_servername = 1; } # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1 || ecpointformatlist_length < 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (!s->hit) { s->session->tlsext_ecpointformatlist_length = 0; if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist); if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, "ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist "); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, "%i ", *(sdata++)); fprintf(stderr, "\n"); # endif } # endif /* OPENSSL_NO_EC */ else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if ((SSL_get_options(s) & SSL_OP_NO_TICKET) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } s->tlsext_ticket_expected = 1; } # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input && s->version != DTLS1_VERSION) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->server_opaque_prf_input_len); if (s->s3->server_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->server_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->server_opaque_prf_input); } if (s->s3->server_opaque_prf_input_len == 0) { /* dummy byte just to get non-NULL */ s->s3->server_opaque_prf_input = OPENSSL_malloc(1); } else { s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len); } if (s->s3->server_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_status_request && s->version != DTLS1_VERSION) { /* * MUST be empty and only sent if we've requested a status * request message. */ if ((s->tlsext_status_type == -1) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* Set flag to expect CertificateStatus message */ s->tlsext_status_expected = 1; } # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { unsigned char *selected; unsigned char selected_len; /* We must have requested it. */ if (s->ctx->next_proto_select_cb == NULL) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* The data must be valid */ if (!ssl_next_proto_validate(data, size)) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s-> ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->next_proto_negotiated = OPENSSL_malloc(selected_len); if (!s->next_proto_negotiated) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->next_proto_negotiated, selected, selected_len); s->next_proto_negotiated_len = selected_len; s->s3->next_proto_neg_seen = 1; } # endif else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Server allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Server doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al)) return 0; } # endif data += size; } if (data != d + n) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->hit && tlsext_servername == 1) { if (s->tlsext_hostname) { if (s->session->tlsext_hostname == NULL) { s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname); if (!s->session->tlsext_hostname) { *al = SSL_AD_UNRECOGNIZED_NAME; return 0; } } else { *al = SSL_AD_DECODE_ERROR; return 0; } } } *p = data; ri_check: /* * Determine if we need to see RI. Strictly speaking if we want to avoid * an attack we should *always* see RI even on initial server hello * because the client doesn't see any renegotiation during an attack. * However this would mean we could not connect to any server which * doesn't support RI so for the immediate future tolerate RI absence on * initial connect only. */ if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT) && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Avoid some undefined pointer arithmetic A common idiom in the codebase is: if (p + len > limit) { return; /* Too long */ } Where "p" points to some malloc'd data of SIZE bytes and limit == p + SIZE "len" here could be from some externally supplied data (e.g. from a TLS message). The rules of C pointer arithmetic are such that "p + len" is only well defined where len <= SIZE. Therefore the above idiom is actually undefined behaviour. For example this could cause problems if some malloc implementation provides an address for "p" such that "p + len" actually overflows for values of len that are too big and therefore p + len < limit! Issue reported by Guido Vranken. CVE-2016-2177 Reviewed-by: Rich Salz <rsalz@openssl.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: char *BN_bn2dec(const BIGNUM *a) { int i = 0, num, ok = 0; char *buf = NULL; char *p; BIGNUM *t = NULL; BN_ULONG *bn_data = NULL, *lp; /*- * get an upper bound for the length of the decimal integer * num <= (BN_num_bits(a) + 1) * log(2) * <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1 (rounding error) * <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1 */ i = BN_num_bits(a) * 3; num = (i / 10 + i / 1000 + 1) + 1; bn_data = OPENSSL_malloc((num / BN_DEC_NUM + 1) * sizeof(BN_ULONG)); buf = OPENSSL_malloc(num + 3); if ((buf == NULL) || (bn_data == NULL)) { BNerr(BN_F_BN_BN2DEC, ERR_R_MALLOC_FAILURE); goto err; } if ((t = BN_dup(a)) == NULL) goto err; #define BUF_REMAIN (num+3 - (size_t)(p - buf)) p = buf; lp = bn_data; if (BN_is_zero(t)) { *(p++) = '0'; *(p++) = '\0'; } else { if (BN_is_negative(t)) *p++ = '-'; i = 0; while (!BN_is_zero(t)) { *lp = BN_div_word(t, BN_DEC_CONV); lp++; } lp--; /* * We now have a series of blocks, BN_DEC_NUM chars in length, where * the last one needs truncation. The blocks need to be reversed in * order. */ BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp); while (*p) p++; while (lp != bn_data) { lp--; BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp); while (*p) p++; } } ok = 1; err: OPENSSL_free(bn_data); BN_free(t); if (ok) return buf; OPENSSL_free(buf); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Check for errors in BN_bn2dec() If an oversize BIGNUM is presented to BN_bn2dec() it can cause BN_div_word() to fail and not reduce the value of 't' resulting in OOB writes to the bn_data buffer and eventually crashing. Fix by checking return value of BN_div_word() and checking writes don't overflow buffer. Thanks to Shi Lei for reporting this bug. CVE-2016-2182 Reviewed-by: Tim Hudson <tjh@openssl.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 dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok) { /*- * (0) check whether the desired fragment is available * if so: * (1) copy over the fragment to s->init_buf->data[] * (2) update s->init_num */ pitem *item; hm_fragment *frag; int al; *ok = 0; item = pqueue_peek(s->d1->buffered_messages); if (item == NULL) return 0; frag = (hm_fragment *)item->data; /* Don't return if reassembly still in progress */ if (frag->reassembly != NULL) return 0; if (s->d1->handshake_read_seq == frag->msg_header.seq) { unsigned long frag_len = frag->msg_header.frag_len; pqueue_pop(s->d1->buffered_messages); al = dtls1_preprocess_fragment(s, &frag->msg_header, max); if (al == 0) { /* no alert */ unsigned char *p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH; memcpy(&p[frag->msg_header.frag_off], frag->fragment, frag->msg_header.frag_len); } dtls1_hm_fragment_free(frag); pitem_free(item); if (al == 0) { *ok = 1; return frag_len; } ssl3_send_alert(s, SSL3_AL_FATAL, al); s->init_num = 0; *ok = 0; return -1; } else return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Fix DTLS buffered message DoS attack DTLS can handle out of order record delivery. Additionally since handshake messages can be bigger than will fit into a single packet, the messages can be fragmented across multiple records (as with normal TLS). That means that the messages can arrive mixed up, and we have to reassemble them. We keep a queue of buffered messages that are "from the future", i.e. messages we're not ready to deal with yet but have arrived early. The messages held there may not be full yet - they could be one or more fragments that are still in the process of being reassembled. The code assumes that we will eventually complete the reassembly and when that occurs the complete message is removed from the queue at the point that we need to use it. However, DTLS is also tolerant of packet loss. To get around that DTLS messages can be retransmitted. If we receive a full (non-fragmented) message from the peer after previously having received a fragment of that message, then we ignore the message in the queue and just use the non-fragmented version. At that point the queued message will never get removed. Additionally the peer could send "future" messages that we never get to in order to complete the handshake. Each message has a sequence number (starting from 0). We will accept a message fragment for the current message sequence number, or for any sequence up to 10 into the future. However if the Finished message has a sequence number of 2, anything greater than that in the queue is just left there. So, in those two ways we can end up with "orphaned" data in the queue that will never get removed - except when the connection is closed. At that point all the queues are flushed. An attacker could seek to exploit this by filling up the queues with lots of large messages that are never going to be used in order to attempt a DoS by memory exhaustion. I will assume that we are only concerned with servers here. It does not seem reasonable to be concerned about a memory exhaustion attack on a client. They are unlikely to process enough connections for this to be an issue. A "long" handshake with many messages might be 5 messages long (in the incoming direction), e.g. ClientHello, Certificate, ClientKeyExchange, CertificateVerify, Finished. So this would be message sequence numbers 0 to 4. Additionally we can buffer up to 10 messages in the future. Therefore the maximum number of messages that an attacker could send that could get orphaned would typically be 15. The maximum size that a DTLS message is allowed to be is defined by max_cert_list, which by default is 100k. Therefore the maximum amount of "orphaned" memory per connection is 1500k. Message sequence numbers get reset after the Finished message, so renegotiation will not extend the maximum number of messages that can be orphaned per connection. As noted above, the queues do get cleared when the connection is closed. Therefore in order to mount an effective attack, an attacker would have to open many simultaneous connections. Issue reported by Quan Luo. CVE-2016-2179 Reviewed-by: Richard Levitte <levitte@openssl.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 ssl3_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok) { unsigned char *p; unsigned long l; long n; int i, al; if (s->s3->tmp.reuse_message) { s->s3->tmp.reuse_message = 0; if ((mt >= 0) && (s->s3->tmp.message_type != mt)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE); goto f_err; } *ok = 1; s->state = stn; s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH; s->init_num = (int)s->s3->tmp.message_size; return s->init_num; } p = (unsigned char *)s->init_buf->data; if (s->state == st1) { /* s->init_num < SSL3_HM_HEADER_LENGTH */ int skip_message; do { while (s->init_num < SSL3_HM_HEADER_LENGTH) { i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &p[s->init_num], SSL3_HM_HEADER_LENGTH - s->init_num, 0); if (i <= 0) { s->rwstate = SSL_READING; *ok = 0; return i; } s->init_num += i; } skip_message = 0; if (!s->server) if (p[0] == SSL3_MT_HELLO_REQUEST) /* * The server may always send 'Hello Request' messages -- * we are doing a handshake anyway now, so ignore them if * their format is correct. Does not count for 'Finished' * MAC. */ if (p[1] == 0 && p[2] == 0 && p[3] == 0) { s->init_num = 0; skip_message = 1; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, p, SSL3_HM_HEADER_LENGTH, s, s->msg_callback_arg); } } while (skip_message); /* s->init_num == SSL3_HM_HEADER_LENGTH */ if ((mt >= 0) && (*p != mt)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE); goto f_err; } if ((mt < 0) && (*p == SSL3_MT_CLIENT_HELLO) && (st1 == SSL3_ST_SR_CERT_A) && (stn == SSL3_ST_SR_CERT_B)) { /* * At this point we have got an MS SGC second client hello (maybe * we should always allow the client to start a new handshake?). * We need to restart the mac. Don't increment * {num,total}_renegotiations because we have not completed the * handshake. */ ssl3_init_finished_mac(s); } s->s3->tmp.message_type = *(p++); n2l3(p, l); if (l > (unsigned long)max) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_MESSAGE, SSL_R_EXCESSIVE_MESSAGE_SIZE); goto f_err; } if (l && !BUF_MEM_grow_clean(s->init_buf, (int)l + SSL3_HM_HEADER_LENGTH)) { SSLerr(SSL_F_SSL3_GET_MESSAGE, ERR_R_BUF_LIB); goto err; } s->s3->tmp.message_size = l; s->state = stn; s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH; s->init_num = 0; } /* next state (stn) */ p = s->init_msg; n = s->s3->tmp.message_size - s->init_num; while (n > 0) { i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, &p[s->init_num], n, 0); if (i <= 0) { s->rwstate = SSL_READING; *ok = 0; return i; } s->init_num += i; n -= i; } #ifndef OPENSSL_NO_NEXTPROTONEG /* * If receiving Finished, record MAC of prior handshake messages for * Finished verification. */ if (*s->init_buf->data == SSL3_MT_FINISHED) ssl3_take_mac(s); #endif /* Feed this message into MAC computation. */ ssl3_finish_mac(s, (unsigned char *)s->init_buf->data, s->init_num + SSL3_HM_HEADER_LENGTH); if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data, (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, s, s->msg_callback_arg); *ok = 1; return s->init_num; f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: *ok = 0; return (-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Make message buffer slightly larger than message. Grow TLS/DTLS 16 bytes more than strictly necessary as a precaution against OOB reads. In most cases this will have no effect because the message buffer will be large enough already. Reviewed-by: Matt Caswell <matt@openssl.org> (cherry picked from commit 006a788c84e541c8920dd2ad85fb62b52185c519)'</s>
<s>[INST] Given the following code containing errors, provide 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 SUB_STATE_RETURN read_state_machine(SSL *s) { OSSL_STATEM *st = &s->statem; int ret, mt; unsigned long len = 0; int (*transition) (SSL *s, int mt); PACKET pkt; MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt); WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst); unsigned long (*max_message_size) (SSL *s); void (*cb) (const SSL *ssl, int type, int val) = NULL; cb = get_callback(s); if (s->server) { transition = ossl_statem_server_read_transition; process_message = ossl_statem_server_process_message; max_message_size = ossl_statem_server_max_message_size; post_process_message = ossl_statem_server_post_process_message; } else { transition = ossl_statem_client_read_transition; process_message = ossl_statem_client_process_message; max_message_size = ossl_statem_client_max_message_size; post_process_message = ossl_statem_client_post_process_message; } if (st->read_state_first_init) { s->first_packet = 1; st->read_state_first_init = 0; } while (1) { switch (st->read_state) { case READ_STATE_HEADER: /* Get the state the peer wants to move to */ if (SSL_IS_DTLS(s)) { /* * In DTLS we get the whole message in one go - header and body */ ret = dtls_get_message(s, &mt, &len); } else { ret = tls_get_message_header(s, &mt); } if (ret == 0) { /* Could be non-blocking IO */ return SUB_STATE_ERROR; } if (cb != NULL) { /* Notify callback of an impending state change */ if (s->server) cb(s, SSL_CB_ACCEPT_LOOP, 1); else cb(s, SSL_CB_CONNECT_LOOP, 1); } /* * Validate that we are allowed to move to the new state and move * to that state if so */ if (!transition(s, mt)) { ossl_statem_set_error(s); return SUB_STATE_ERROR; } if (s->s3->tmp.message_size > max_message_size(s)) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER); SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE); return SUB_STATE_ERROR; } /* dtls_get_message already did this */ if (!SSL_IS_DTLS(s) && s->s3->tmp.message_size > 0 && !BUF_MEM_grow_clean(s->init_buf, (int)s->s3->tmp.message_size + SSL3_HM_HEADER_LENGTH)) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR); SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_BUF_LIB); return SUB_STATE_ERROR; } st->read_state = READ_STATE_BODY; /* Fall through */ case READ_STATE_BODY: if (!SSL_IS_DTLS(s)) { /* We already got this above for DTLS */ ret = tls_get_message_body(s, &len); if (ret == 0) { /* Could be non-blocking IO */ return SUB_STATE_ERROR; } } s->first_packet = 0; if (!PACKET_buf_init(&pkt, s->init_msg, len)) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR); SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR); return SUB_STATE_ERROR; } ret = process_message(s, &pkt); /* Discard the packet data */ s->init_num = 0; switch (ret) { case MSG_PROCESS_ERROR: return SUB_STATE_ERROR; case MSG_PROCESS_FINISHED_READING: if (SSL_IS_DTLS(s)) { dtls1_stop_timer(s); } return SUB_STATE_FINISHED; case MSG_PROCESS_CONTINUE_PROCESSING: st->read_state = READ_STATE_POST_PROCESS; st->read_state_work = WORK_MORE_A; break; default: st->read_state = READ_STATE_HEADER; break; } break; case READ_STATE_POST_PROCESS: st->read_state_work = post_process_message(s, st->read_state_work); switch (st->read_state_work) { default: return SUB_STATE_ERROR; case WORK_FINISHED_CONTINUE: st->read_state = READ_STATE_HEADER; break; case WORK_FINISHED_STOP: if (SSL_IS_DTLS(s)) { dtls1_stop_timer(s); } return SUB_STATE_FINISHED; } break; default: /* Shouldn't happen */ ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR); SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR); ossl_statem_set_error(s); return SUB_STATE_ERROR; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix Use After Free for large message sizes The buffer to receive messages is initialised to 16k. If a message is received that is larger than that then the buffer is "realloc'd". This can cause the location of the underlying buffer to change. Anything that is referring to the old location will be referring to free'd data. In the recent commit c1ef7c97 (master) and 4b390b6c (1.1.0) the point in the code where the message buffer is grown was changed. However s->init_msg was not updated to point at the new location. CVE-2016-6309 Reviewed-by: Emilia Käsper <emilia@openssl.org> (cherry picked from commit 0d698f6696e114a6e47f8b75ff88ec81f9e30175)'</s>
<s>[INST] Given the following code containing errors, provide 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 dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf, int len, int peek) { int al, i, j, ret; unsigned int n; SSL3_RECORD *rr; void (*cb) (const SSL *ssl, int type2, int val) = NULL; if (!SSL3_BUFFER_is_initialised(&s->rlayer.rbuf)) { /* Not initialized yet */ if (!ssl3_setup_buffers(s)) return (-1); } if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } /* * check whether there's a handshake message (client hello?) waiting */ if ((ret = have_handshake_fragment(s, type, buf, len))) return ret; /* * Now s->rlayer.d->handshake_fragment_len == 0 if * type == SSL3_RT_HANDSHAKE. */ #ifndef OPENSSL_NO_SCTP /* * Continue handshake if it had to be interrupted to read app data with * SCTP. */ if ((!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) || (BIO_dgram_is_sctp(SSL_get_rbio(s)) && ossl_statem_in_sctp_read_sock(s) && s->s3->in_read_app_data != 2)) #else if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) #endif { /* type == SSL3_RT_APPLICATION_DATA */ i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } } start: s->rwstate = SSL_NOTHING; /*- * s->s3->rrec.type - is the type of record * s->s3->rrec.data, - data * s->s3->rrec.off, - offset into 'data' for next read * s->s3->rrec.length, - number of bytes. */ rr = s->rlayer.rrec; /* * We are not handshaking and have no data yet, so process data buffered * during the last handshake in advance, if any. */ if (SSL_is_init_finished(s) && SSL3_RECORD_get_length(rr) == 0) { pitem *item; item = pqueue_pop(s->rlayer.d->buffered_app_data.q); if (item) { #ifndef OPENSSL_NO_SCTP /* Restore bio_dgram_sctp_rcvinfo struct */ if (BIO_dgram_is_sctp(SSL_get_rbio(s))) { DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data; BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo); } #endif dtls1_copy_record(s, item); OPENSSL_free(item->data); pitem_free(item); } } /* Check for timeout */ if (dtls1_handle_timeout(s) > 0) goto start; /* get new packet if necessary */ if ((SSL3_RECORD_get_length(rr) == 0) || (s->rlayer.rstate == SSL_ST_READ_BODY)) { ret = dtls1_get_record(s); if (ret <= 0) { ret = dtls1_read_failed(s, ret); /* anything other than a timeout is an error */ if (ret <= 0) return (ret); else goto start; } } /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) { /* * We now have application data between CCS and Finished. Most likely * the packets were reordered on their way, so buffer the application * data for later processing rather than dropping the connection. */ if (dtls1_buffer_record(s, &(s->rlayer.d->buffered_app_data), SSL3_RECORD_get_seq_num(rr)) < 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } SSL3_RECORD_set_length(rr, 0); goto start; } /* * If the other end has shut down, throw anything we read away (even in * 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { SSL3_RECORD_set_length(rr, 0); s->rwstate = SSL_NOTHING; return (0); } if (type == SSL3_RECORD_get_type(rr) || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) { /* * SSL3_RT_APPLICATION_DATA or * SSL3_RT_HANDSHAKE or * SSL3_RT_CHANGE_CIPHER_SPEC */ /* * make sure that we are not getting application data when we are * doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE); goto f_err; } if (recvd_type != NULL) *recvd_type = SSL3_RECORD_get_type(rr); if (len <= 0) return (len); if ((unsigned int)len > SSL3_RECORD_get_length(rr)) n = SSL3_RECORD_get_length(rr); else n = (unsigned int)len; memcpy(buf, &(SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)]), n); if (!peek) { SSL3_RECORD_sub_length(rr, n); SSL3_RECORD_add_off(rr, n); if (SSL3_RECORD_get_length(rr) == 0) { s->rlayer.rstate = SSL_ST_READ_HEADER; SSL3_RECORD_set_off(rr, 0); } } #ifndef OPENSSL_NO_SCTP /* * We were about to renegotiate but had to read belated application * data first, so retry. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && SSL3_RECORD_get_type(rr) == SSL3_RT_APPLICATION_DATA && ossl_statem_in_sctp_read_sock(s)) { s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); } /* * We might had to delay a close_notify alert because of reordered * app data. If there was an alert and there is no message to read * anymore, finally set shutdown. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && s->d1->shutdown_received && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); } #endif return (n); } /* * If we get here, then type != rr->type; if we have a handshake message, * then it was unexpected (Hello Request or Client Hello). */ /* * In case of record types for which we have 'fragment' storage, fill * that so that we can process the data at a fixed place. */ { unsigned int k, dest_maxlen = 0; unsigned char *dest = NULL; unsigned int *dest_len = NULL; if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) { dest_maxlen = sizeof s->rlayer.d->handshake_fragment; dest = s->rlayer.d->handshake_fragment; dest_len = &s->rlayer.d->handshake_fragment_len; } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) { dest_maxlen = sizeof(s->rlayer.d->alert_fragment); dest = s->rlayer.d->alert_fragment; dest_len = &s->rlayer.d->alert_fragment_len; } #ifndef OPENSSL_NO_HEARTBEATS else if (SSL3_RECORD_get_type(rr) == DTLS1_RT_HEARTBEAT) { /* We allow a 0 return */ if (dtls1_process_heartbeat(s, SSL3_RECORD_get_data(rr), SSL3_RECORD_get_length(rr)) < 0) { return -1; } /* Exit and notify application to read again */ SSL3_RECORD_set_length(rr, 0); s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return (-1); } #endif /* else it's a CCS message, or application data or wrong */ else if (SSL3_RECORD_get_type(rr) != SSL3_RT_CHANGE_CIPHER_SPEC) { /* * Application data while renegotiating is allowed. Try again * reading. */ if (SSL3_RECORD_get_type(rr) == SSL3_RT_APPLICATION_DATA) { BIO *bio; s->s3->in_read_app_data = 2; bio = SSL_get_rbio(s); s->rwstate = SSL_READING; BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } /* Not certain if this is the right error handling */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; } if (dest_maxlen > 0) { /* * XDTLS: In a pathological case, the Client Hello may be * fragmented--don't always expect dest_maxlen bytes */ if (SSL3_RECORD_get_length(rr) < dest_maxlen) { #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE /* * for normal alerts rr->length is 2, while * dest_maxlen is 7 if we were to handle this * non-existing alert... */ FIX ME; #endif s->rlayer.rstate = SSL_ST_READ_HEADER; SSL3_RECORD_set_length(rr, 0); goto start; } /* now move 'n' bytes: */ for (k = 0; k < dest_maxlen; k++) { dest[k] = SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)]; SSL3_RECORD_add_off(rr, 1); SSL3_RECORD_add_length(rr, -1); } *dest_len = dest_maxlen; } } /*- * s->rlayer.d->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE; * s->rlayer.d->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ /* If we are a client, check for an incoming 'Hello Request': */ if ((!s->server) && (s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && (s->rlayer.d->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && (s->session != NULL) && (s->session->cipher != NULL)) { s->rlayer.d->handshake_fragment_len = 0; if ((s->rlayer.d->handshake_fragment[1] != 0) || (s->rlayer.d->handshake_fragment[2] != 0) || (s->rlayer.d->handshake_fragment[3] != 0)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST); goto f_err; } /* * no need to check sequence number on HELLO REQUEST messages */ if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->rlayer.d->handshake_fragment, 4, s, s->msg_callback_arg); if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && !s->s3->renegotiate) { s->d1->handshake_read_seq++; s->new_session = 1; ssl3_renegotiate(s); if (ssl3_renegotiate_check(s)) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } } } /* * we either finished a handshake or ignored the request, now try * again to obtain the (application) data we were asked for */ goto start; } if (s->rlayer.d->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) { int alert_level = s->rlayer.d->alert_fragment[0]; int alert_descr = s->rlayer.d->alert_fragment[1]; s->rlayer.d->alert_fragment_len = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, s->rlayer.d->alert_fragment, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == SSL3_AL_WARNING) { s->s3->warn_alert = alert_descr; if (alert_descr == SSL_AD_CLOSE_NOTIFY) { #ifndef OPENSSL_NO_SCTP /* * With SCTP and streams the socket may deliver app data * after a close_notify alert. We have to check this first so * that nothing gets discarded. */ if (BIO_dgram_is_sctp(SSL_get_rbio(s)) && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->d1->shutdown_received = 1; s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return -1; } #endif s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); } #if 0 /* XXX: this is a possible improvement in the future */ /* now check if it's a missing record */ if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) { unsigned short seq; unsigned int frag_off; unsigned char *p = &(s->rlayer.d->alert_fragment[2]); n2s(p, seq); n2l3(p, frag_off); dtls1_retransmit_message(s, dtls1_get_queue_priority (frag->msg_header.seq, 0), frag_off, &found); if (!found && SSL_in_init(s)) { /* * fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */ /* * requested a message not yet sent, send an alert * ourselves */ ssl3_send_alert(s, SSL3_AL_WARNING, DTLS1_AD_MISSING_HANDSHAKE_MESSAGE); } } #endif } else if (alert_level == SSL3_AL_FATAL) { char tmp[16]; s->rwstate = SSL_NOTHING; s->s3->fatal_alert = alert_descr; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr); ERR_add_error_data(2, "SSL alert number ", tmp); s->shutdown |= SSL_RECEIVED_SHUTDOWN; SSL_CTX_remove_session(s->session_ctx, s->session); return (0); } else { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE); goto f_err; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a * shutdown */ s->rwstate = SSL_NOTHING; SSL3_RECORD_set_length(rr, 0); return (0); } if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) { /* * We can't process a CCS now, because previous handshake messages * are still missing, so just drop it. */ SSL3_RECORD_set_length(rr, 0); goto start; } /* * Unexpected handshake message (Client Hello, or protocol violation) */ if ((s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && !ossl_statem_get_in_handshake(s)) { struct hm_header_st msg_hdr; /* this may just be a stale retransmit */ dtls1_get_message_header(rr->data, &msg_hdr); if (SSL3_RECORD_get_epoch(rr) != s->rlayer.d->r_epoch) { SSL3_RECORD_set_length(rr, 0); goto start; } /* * If we are server, we may have a repeated FINISHED of the client * here, then retransmit our CCS and FINISHED. */ if (msg_hdr.type == SSL3_MT_FINISHED) { if (dtls1_check_timeout_num(s) < 0) return -1; dtls1_retransmit_buffered_messages(s); SSL3_RECORD_set_length(rr, 0); goto start; } if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { ossl_statem_set_in_init(s, 1); s->renegotiate = 1; s->new_session = 1; } i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, but we * trigger an SSL handshake, we return -1 with the retry * option set. Otherwise renegotiation may cause nasty * problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } goto start; } switch (SSL3_RECORD_get_type(rr)) { default: /* TLS just ignores unknown message types */ if (s->version == TLS1_VERSION) { SSL3_RECORD_set_length(rr, 0); goto start; } al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* * we already handled all of these, with the possible exception of * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but * that should not happen when type != rr->type */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR); goto f_err; case SSL3_RT_APPLICATION_DATA: /* * At this point, we were expecting handshake data, but have * application data. If the library was running inside ssl3_read() * (i.e. in_read_app_data is set) and it makes sense to read * application data at this point (session renegotiation not yet * started), we will indulge it. */ if (s->s3->in_read_app_data && (s->s3->total_renegotiations != 0) && ossl_statem_app_data_allowed(s)) { s->s3->in_read_app_data = 2; return (-1); } else { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; } } /* not reached */ f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); return (-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': 'Don't allow too many consecutive warning alerts Certain warning alerts are ignored if they are received. This can mean that no progress will be made if one peer continually sends those warning alerts. Implement a count so that we abort the connection if we receive too many. Issue reported by Shi Lei. Reviewed-by: Rich Salz <rsalz@openssl.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: horizontalDifference16(unsigned short *ip, int n, int stride, unsigned short *wp, uint16 *From14) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; /* assumption is unsigned pixel values */ #undef CLAMP #define CLAMP(v) From14[(v) >> 2] mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { ip += n - 1; /* point to last one */ wp += n - 1; /* point to last one */ n -= stride; while (n > 0) { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp[stride] -= wp[0]; wp[stride] &= mask; wp--; ip--) n -= stride; } REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities in heap or stack allocated buffers. Reported as MSVR 35093, MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR 35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities in heap allocated buffers. Reported as MSVR 35094. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1() that didn't reset the tif_rawcc and tif_rawcp members. I'm not completely sure if that could happen in practice outside of the odd behaviour of t2p_seekproc() of tiff2pdf). The report points that a better fix could be to check the return value of TIFFFlushData1() in places where it isn't done currently, but it seems this patch is enough. Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan & Suha Can from the MSRC Vulnerabilities & Mitigations team.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PredictorDecodeTile(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->decodetile != NULL); if ((*sp->decodetile)(tif, op0, occ0, s)) { tmsize_t rowsize = sp->rowsize; assert(rowsize > 0); assert((occ0%rowsize)==0); assert(sp->decodepfunc != NULL); while (occ0 > 0) { (*sp->decodepfunc)(tif, op0, rowsize); occ0 -= rowsize; op0 += rowsize; } return 1; } else return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc) { uint32* wp = (uint32*) cp0; tmsize_t wc = cc / 4; horDiff32(tif, cp0, cc); TIFFSwabArrayOfLong(wp, wc); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DECLAREwriteFunc(writeBufferToContigTiles) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': '* tools/tiffcp.c: fix out-of-bounds write on tiled images with odd tile width vs image width. Reported as MSVR 35103 by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: EC_GROUP *EC_GROUP_new(const EC_METHOD *meth) { EC_GROUP *ret; if (meth == NULL) { ECerr(EC_F_EC_GROUP_NEW, EC_R_SLOT_FULL); return NULL; } if (meth->group_init == 0) { ECerr(EC_F_EC_GROUP_NEW, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return NULL; } ret = OPENSSL_malloc(sizeof *ret); if (ret == NULL) { ECerr(EC_F_EC_GROUP_NEW, ERR_R_MALLOC_FAILURE); return NULL; } ret->meth = meth; ret->extra_data = NULL; ret->generator = NULL; BN_init(&ret->order); BN_init(&ret->cofactor); ret->curve_name = 0; ret->asn1_flag = 0; ret->asn1_form = POINT_CONVERSION_UNCOMPRESSED; ret->seed = NULL; ret->seed_len = 0; if (!meth->group_init(ret)) { OPENSSL_free(ret); return NULL; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-320'], 'message': 'Reserve option to use BN_mod_exp_mont_consttime in ECDSA. Submitted by Shay Gueron, Intel Corp. RT: 3149 Reviewed-by: Rich Salz <rsalz@openssl.org> (cherry picked from commit f54be179aa4cbbd944728771d7d59ed588158a12)'</s>
<s>[INST] Given the following code containing errors, provide 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 rc4_hmac_md5_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr) { EVP_RC4_HMAC_MD5 *key = data(ctx); switch (type) { case EVP_CTRL_AEAD_SET_MAC_KEY: { unsigned int i; unsigned char hmac_key[64]; memset(hmac_key, 0, sizeof(hmac_key)); if (arg > (int)sizeof(hmac_key)) { MD5_Init(&key->head); MD5_Update(&key->head, ptr, arg); MD5_Final(hmac_key, &key->head); } else { memcpy(hmac_key, ptr, arg); } for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36; /* ipad */ MD5_Init(&key->head); MD5_Update(&key->head, hmac_key, sizeof(hmac_key)); for (i = 0; i < sizeof(hmac_key); i++) hmac_key[i] ^= 0x36 ^ 0x5c; /* opad */ MD5_Init(&key->tail); MD5_Update(&key->tail, hmac_key, sizeof(hmac_key)); OPENSSL_cleanse(hmac_key, sizeof(hmac_key)); return 1; } case EVP_CTRL_AEAD_TLS1_AAD: { unsigned char *p = ptr; unsigned int len; if (arg != EVP_AEAD_TLS1_AAD_LEN) return -1; len = p[arg - 2] << 8 | p[arg - 1]; if (!EVP_CIPHER_CTX_encrypting(ctx)) { len -= MD5_DIGEST_LENGTH; p[arg - 2] = len >> 8; p[arg - 1] = len; } key->payload_length = len; key->md = key->head; MD5_Update(&key->md, p, arg); return MD5_DIGEST_LENGTH; } default: return -1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'crypto/evp: harden RC4_MD5 cipher. Originally a crash in 32-bit build was reported CHACHA20-POLY1305 cipher. The crash is triggered by truncated packet and is result of excessive hashing to the edge of accessible memory (or bogus MAC value is produced if x86 MD5 assembly module is involved). Since hash operation is read-only it is not considered to be exploitable beyond a DoS condition. Thanks to Robert Święcki for report. CVE-2017-3731 Reviewed-by: Rich Salz <rsalz@openssl.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: TIFFNumberOfStrips(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; uint32 nstrips; /* If the value was already computed and store in td_nstrips, then return it, since ChopUpSingleUncompressedStrip might have altered and resized the since the td_stripbytecount and td_stripoffset arrays to the new value after the initial affectation of td_nstrips = TIFFNumberOfStrips() in tif_dirread.c ~line 3612. See http://bugzilla.maptools.org/show_bug.cgi?id=2587 */ if( td->td_nstrips ) return td->td_nstrips; nstrips = (td->td_rowsperstrip == (uint32) -1 ? 1 : TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip)); if (td->td_planarconfig == PLANARCONFIG_SEPARATE) nstrips = _TIFFMultiply32(tif, nstrips, (uint32)td->td_samplesperpixel, "TIFFNumberOfStrips"); return (nstrips); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': '* libtiff/tif_dirread.c: modify ChopUpSingleUncompressedStrip() to instanciate compute ntrips as TIFFhowmany_32(td->td_imagelength, rowsperstrip), instead of a logic based on the total size of data. Which is faulty is the total size of data is not sufficient to fill the whole image, and thus results in reading outside of the StripByCounts/StripOffsets arrays when using TIFFReadScanline(). Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2608. * libtiff/tif_strip.c: revert the change in TIFFNumberOfStrips() done for http://bugzilla.maptools.org/show_bug.cgi?id=2587 / CVE-2016-9273 since the above change is a better fix that makes it unnecessary.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DECLAREContigPutFunc(putagreytile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; while (h-- > 0) { for (x = w; x-- > 0;) { *cp++ = BWmap[*pp][0] & (*(pp+1) << 24 | ~A1); pp += samplesperpixel; } cp += toskew; pp += fromskew; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': '* libtiff/tif_getimage.c: add explicit uint32 cast in putagreytile to avoid UndefinedBehaviorSanitizer warning. Patch by Nicolás Peña. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2658'</s>
<s>[INST] Given the following code containing errors, provide 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 enum TIFFReadDirEntryErr TIFFReadDirEntryFloatArray(TIFF* tif, TIFFDirEntry* direntry, float** value) { enum TIFFReadDirEntryErr err; uint32 count; void* origdata; float* data; switch (direntry->tdir_type) { case TIFF_BYTE: case TIFF_SBYTE: case TIFF_SHORT: case TIFF_SSHORT: case TIFF_LONG: case TIFF_SLONG: case TIFF_LONG8: case TIFF_SLONG8: case TIFF_RATIONAL: case TIFF_SRATIONAL: case TIFF_FLOAT: case TIFF_DOUBLE: break; default: return(TIFFReadDirEntryErrType); } err=TIFFReadDirEntryArray(tif,direntry,&count,4,&origdata); if ((err!=TIFFReadDirEntryErrOk)||(origdata==0)) { *value=0; return(err); } switch (direntry->tdir_type) { case TIFF_FLOAT: if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong((uint32*)origdata,count); TIFFCvtIEEEDoubleToNative(tif,count,(float*)origdata); *value=(float*)origdata; return(TIFFReadDirEntryErrOk); } data=(float*)_TIFFmalloc(count*sizeof(float)); if (data==0) { _TIFFfree(origdata); return(TIFFReadDirEntryErrAlloc); } switch (direntry->tdir_type) { case TIFF_BYTE: { uint8* ma; float* mb; uint32 n; ma=(uint8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(float)(*ma++); } break; case TIFF_SBYTE: { int8* ma; float* mb; uint32 n; ma=(int8*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(float)(*ma++); } break; case TIFF_SHORT: { uint16* ma; float* mb; uint32 n; ma=(uint16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort(ma); *mb++=(float)(*ma++); } } break; case TIFF_SSHORT: { int16* ma; float* mb; uint32 n; ma=(int16*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabShort((uint16*)ma); *mb++=(float)(*ma++); } } break; case TIFF_LONG: { uint32* ma; float* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); *mb++=(float)(*ma++); } } break; case TIFF_SLONG: { int32* ma; float* mb; uint32 n; ma=(int32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong((uint32*)ma); *mb++=(float)(*ma++); } } break; case TIFF_LONG8: { uint64* ma; float* mb; uint32 n; ma=(uint64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8(ma); #if defined(__WIN32__) && (_MSC_VER < 1500) /* * XXX: MSVC 6.0 does not support * conversion of 64-bit integers into * floating point values. */ *mb++ = _TIFFUInt64ToFloat(*ma++); #else *mb++ = (float)(*ma++); #endif } } break; case TIFF_SLONG8: { int64* ma; float* mb; uint32 n; ma=(int64*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong8((uint64*)ma); *mb++=(float)(*ma++); } } break; case TIFF_RATIONAL: { uint32* ma; uint32 maa; uint32 mab; float* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); maa=*ma++; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); mab=*ma++; if (mab==0) *mb++=0.0; else *mb++=(float)maa/(float)mab; } } break; case TIFF_SRATIONAL: { uint32* ma; int32 maa; uint32 mab; float* mb; uint32 n; ma=(uint32*)origdata; mb=data; for (n=0; n<count; n++) { if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); maa=*(int32*)ma; ma++; if (tif->tif_flags&TIFF_SWAB) TIFFSwabLong(ma); mab=*ma++; if (mab==0) *mb++=0.0; else *mb++=(float)maa/(float)mab; } } break; case TIFF_DOUBLE: { double* ma; float* mb; uint32 n; if (tif->tif_flags&TIFF_SWAB) TIFFSwabArrayOfLong8((uint64*)origdata,count); TIFFCvtIEEEDoubleToNative(tif,count,(double*)origdata); ma=(double*)origdata; mb=data; for (n=0; n<count; n++) *mb++=(float)(*ma++); } break; } _TIFFfree(origdata); *value=data; return(TIFFReadDirEntryErrOk); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': '* libtiff/tif_dir.c, tif_dirread.c, tif_dirwrite.c: implement various clampings of double to other data types to avoid undefined behaviour if the output range isn't big enough to hold the input value. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2643 http://bugzilla.maptools.org/show_bug.cgi?id=2642 http://bugzilla.maptools.org/show_bug.cgi?id=2646 http://bugzilla.maptools.org/show_bug.cgi?id=2647'</s>
<s>[INST] Given the following code containing errors, provide 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 punycode_uint decode_digit(punycode_uint cp) { return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'lib/puny_decode: Fix integer overflow (found by fuzzing)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: sfe_copy_data_fp (SNDFILE *outfile, SNDFILE *infile, int channels, int normalize) { static double data [BUFFER_LEN], max ; sf_count_t frames, readcount, k ; frames = BUFFER_LEN / channels ; readcount = frames ; sf_command (infile, SFC_CALC_SIGNAL_MAX, &max, sizeof (max)) ; if (!normalize && max < 1.0) { while (readcount > 0) { readcount = sf_readf_double (infile, data, frames) ; sf_writef_double (outfile, data, readcount) ; } ; } else { sf_command (infile, SFC_SET_NORM_DOUBLE, NULL, SF_FALSE) ; while (readcount > 0) { readcount = sf_readf_double (infile, data, frames) ; for (k = 0 ; k < readcount * channels ; k++) data [k] /= max ; sf_writef_double (outfile, data, readcount) ; } ; } ; return ; } /* sfe_copy_data_fp */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'sfe_copy_data_fp: check value of "max" variable for being normal and check elements of the data[] array for being finite. Both checks use functions provided by the <math.h> header as declared by the C99 standard. Fixes #317 CVE-2017-14245 CVE-2017-14246'</s>
<s>[INST] Given the following code containing errors, provide 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 asn1_item_embed_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, int tag, int aclass, char opt, ASN1_TLC *ctx) { const ASN1_TEMPLATE *tt, *errtt = NULL; const ASN1_EXTERN_FUNCS *ef; const ASN1_AUX *aux = it->funcs; ASN1_aux_cb *asn1_cb; const unsigned char *p = NULL, *q; unsigned char oclass; char seq_eoc, seq_nolen, cst, isopt; long tmplen; int i; int otag; int ret = 0; ASN1_VALUE **pchptr; if (!pval) return 0; if (aux && aux->asn1_cb) asn1_cb = aux->asn1_cb; else asn1_cb = 0; switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { /* * tagging or OPTIONAL is currently illegal on an item template * because the flags can't get passed down. In practice this * isn't a problem: we include the relevant flags from the item * template in the template itself. */ if ((tag != -1) || opt) { ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE); goto err; } return asn1_template_ex_d2i(pval, in, len, it->templates, opt, ctx); } return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt, ctx); case ASN1_ITYPE_MSTRING: p = *in; /* Just read in tag and class */ ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL, &p, len, -1, 0, 1, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Must be UNIVERSAL class */ if (oclass != V_ASN1_UNIVERSAL) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL); goto err; } /* Check tag matches bit map */ if (!(ASN1_tag2bit(otag) & it->utype)) { /* If OPTIONAL, assume this is OK */ if (opt) return -1; ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_MSTRING_WRONG_TAG); goto err; } return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx); case ASN1_ITYPE_EXTERN: /* Use new style d2i */ ef = it->funcs; return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx); case ASN1_ITYPE_CHOICE: if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; if (*pval) { /* Free up and zero CHOICE value if initialised */ i = asn1_get_choice_selector(pval, it); if ((i >= 0) && (i < it->tcount)) { tt = it->templates + i; pchptr = asn1_get_field_ptr(pval, tt); asn1_template_free(pchptr, tt); asn1_set_choice_selector(pval, -1, it); } } else if (!ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* CHOICE type, try each possibility in turn */ p = *in; for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { pchptr = asn1_get_field_ptr(pval, tt); /* * We mark field as OPTIONAL so its absence can be recognised. */ ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx); /* If field not present, try the next one */ if (ret == -1) continue; /* If positive return, read OK, break loop */ if (ret > 0) break; /* * Must be an ASN1 parsing error. * Free up any partial choice value */ asn1_template_free(pchptr, tt); errtt = tt; ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } /* Did we fall off the end without reading anything? */ if (i == it->tcount) { /* If OPTIONAL, this is OK */ if (opt) { /* Free and zero it */ ASN1_item_ex_free(pval, it); return -1; } ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE); goto err; } asn1_set_choice_selector(pval, i, it); if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; *in = p; return 1; case ASN1_ITYPE_NDEF_SEQUENCE: case ASN1_ITYPE_SEQUENCE: p = *in; tmplen = len; /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */ if (tag == -1) { tag = V_ASN1_SEQUENCE; aclass = V_ASN1_UNIVERSAL; } /* Get SEQUENCE length and update len, p */ ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst, &p, len, tag, aclass, opt, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } else if (ret == -1) return -1; if (aux && (aux->flags & ASN1_AFLG_BROKEN)) { len = tmplen - (p - *in); seq_nolen = 1; } /* If indefinite we don't do a length check */ else seq_nolen = seq_eoc; if (!cst) { ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED); goto err; } if (!*pval && !ASN1_item_ex_new(pval, it)) { ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) goto auxerr; /* Free up and zero any ADB found */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { if (tt->flags & ASN1_TFLG_ADB_MASK) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; seqtt = asn1_do_adb(pval, tt, 0); if (seqtt == NULL) continue; pseqval = asn1_get_field_ptr(pval, seqtt); asn1_template_free(pseqval, seqtt); } } /* Get each field entry */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { const ASN1_TEMPLATE *seqtt; ASN1_VALUE **pseqval; seqtt = asn1_do_adb(pval, tt, 1); if (seqtt == NULL) goto err; pseqval = asn1_get_field_ptr(pval, seqtt); /* Have we ran out of data? */ if (!len) break; q = p; if (asn1_check_eoc(&p, len)) { if (!seq_eoc) { ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_UNEXPECTED_EOC); goto err; } len -= p - q; seq_eoc = 0; q = p; break; } /* * This determines the OPTIONAL flag value. The field cannot be * omitted if it is the last of a SEQUENCE and there is still * data to be read. This isn't strictly necessary but it * increases efficiency in some cases. */ if (i == (it->tcount - 1)) isopt = 0; else isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL); /* * attempt to read in field, allowing each to be OPTIONAL */ ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx); if (!ret) { errtt = seqtt; goto err; } else if (ret == -1) { /* * OPTIONAL component absent. Free and zero the field. */ asn1_template_free(pseqval, seqtt); continue; } /* Update length */ len -= p - q; } /* Check for EOC if expecting one */ if (seq_eoc && !asn1_check_eoc(&p, len)) { ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_MISSING_EOC); goto err; } /* Check all data read */ if (!seq_nolen && len) { ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH); goto err; } /* * If we get here we've got no more data in the SEQUENCE, however we * may not have read all fields so check all remaining are OPTIONAL * and clear any that are. */ for (; i < it->tcount; tt++, i++) { const ASN1_TEMPLATE *seqtt; seqtt = asn1_do_adb(pval, tt, 1); if (seqtt == NULL) goto err; if (seqtt->flags & ASN1_TFLG_OPTIONAL) { ASN1_VALUE **pseqval; pseqval = asn1_get_field_ptr(pval, seqtt); asn1_template_free(pseqval, seqtt); } else { errtt = seqtt; ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_FIELD_MISSING); goto err; } } /* Save encoding */ if (!asn1_enc_save(pval, *in, p - *in, it)) goto auxerr; if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) goto auxerr; *in = p; return 1; default: return 0; } auxerr: ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_AUX_ERROR); err: if (errtt) ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname); else ERR_add_error_data(2, "Type=", it->sname); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-674', 'CWE-787'], 'message': 'Limit ASN.1 constructed types recursive definition depth Constructed types with a recursive definition (such as can be found in PKCS7) could eventually exceed the stack given malicious input with excessive recursion. Therefore we limit the stack depth. CVE-2018-0739 Credit to OSSFuzz for finding this issue. Reviewed-by: Rich Salz <rsalz@openssl.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 rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp; BIGNUM local_r0, local_d, local_p; BIGNUM *pr0, *d, *p; int bitsp, bitsq, ok = -1, n = 0; BN_CTX *ctx = NULL; unsigned long error = 0; /* * When generating ridiculously small keys, we can get stuck * continually regenerating the same prime values. */ if (bits < 16) { ok = 0; /* we set our own err */ RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL); goto err; } ctx = BN_CTX_new(); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); r3 = BN_CTX_get(ctx); if (r3 == NULL) goto err; bitsp = (bits + 1) / 2; bitsq = bits - bitsp; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) goto err; if (!rsa->d && ((rsa->d = BN_new()) == NULL)) goto err; if (!rsa->e && ((rsa->e = BN_new()) == NULL)) goto err; if (!rsa->p && ((rsa->p = BN_new()) == NULL)) goto err; if (!rsa->q && ((rsa->q = BN_new()) == NULL)) goto err; if (!rsa->dmp1 && ((rsa->dmp1 = BN_new()) == NULL)) goto err; if (!rsa->dmq1 && ((rsa->dmq1 = BN_new()) == NULL)) goto err; if (!rsa->iqmp && ((rsa->iqmp = BN_new()) == NULL)) goto err; if (BN_copy(rsa->e, e_value) == NULL) goto err; BN_set_flags(r2, BN_FLG_CONSTTIME); /* generate p and q */ for (;;) { if (!BN_generate_prime_ex(rsa->p, bitsp, 0, NULL, NULL, cb)) goto err; if (!BN_sub(r2, rsa->p, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 0)) goto err; for (;;) { do { if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, cb)) goto err; } while (BN_cmp(rsa->p, rsa->q) == 0); if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 1)) goto err; if (BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } /* calculate n */ if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx)) goto err; /* calculate d */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* p-1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* q-1 */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* (p-1)(q-1) */ if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) { pr0 = &local_r0; BN_with_flags(pr0, r0, BN_FLG_CONSTTIME); } else pr0 = r0; if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) goto err; /* d */ /* set up d for correct BN_FLG_CONSTTIME flag */ if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) { d = &local_d; BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME); } else d = rsa->d; /* calculate d mod (p-1) */ if (!BN_mod(rsa->dmp1, d, r1, ctx)) goto err; /* calculate d mod (q-1) */ if (!BN_mod(rsa->dmq1, d, r2, ctx)) goto err; /* calculate inverse of q mod p */ if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) { p = &local_p; BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME); } else p = rsa->p; if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) goto err; ok = 1; err: if (ok == -1) { RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN); ok = 0; } if (ctx != NULL) { BN_CTX_end(ctx); BN_CTX_free(ctx); } return ok; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-327'], 'message': 'RSA key generation: ensure BN_mod_inverse and BN_mod_exp_mont both get called with BN_FLG_CONSTTIME flag set. CVE-2018-0737 Reviewed-by: Rich Salz <rsalz@openssl.org> Reviewed-by: Matt Caswell <matt@openssl.org> (cherry picked from commit 6939eab03a6e23d2bd2c3f5e34fe1d48e542e787)'</s>
<s>[INST] Given the following code containing errors, provide 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 SimpleModule::runPull() { pull(m_outChunk->frameCount); run(*m_inChunk, *m_outChunk); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'SimpleModule: set output chunk framecount after pull After pulling the data, set the output chunk to the amount of frames we pulled so that the next module in the chain has the correct frame count. Fixes #50 and #51'</s>
<s>[INST] Given the following code containing errors, provide 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 ssl3_send_alert(SSL *s, int level, int desc) { /* Map tls/ssl alert value to correct one */ desc = s->method->ssl3_enc->alert_value(desc); if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION) desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have * protocol_version alerts */ if (desc < 0) return -1; /* If a fatal one, remove from cache */ if ((level == 2) && (s->session != NULL)) SSL_CTX_remove_session(s->session_ctx, s->session); s->s3->alert_dispatch = 1; s->s3->send_alert[0] = level; s->s3->send_alert[1] = desc; if (s->s3->wbuf.left == 0) /* data still being written out? */ return s->method->ssl_dispatch_alert(s); /* * else data is still being written out, we will get written some time in * the future */ return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-203'], 'message': 'Go into the error state if a fatal alert is sent or received If an application calls SSL_shutdown after a fatal alert has occured and then behaves different based on error codes from that function then the application may be vulnerable to a padding oracle. CVE-2019-1559 Reviewed-by: Richard Levitte <levitte@openssl.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void rand_fork(void) { rand_fork_count++; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'drbg: ensure fork-safety without using a pthread_atfork handler When the new OpenSSL CSPRNG was introduced in version 1.1.1, it was announced in the release notes that it would be fork-safe, which the old CSPRNG hadn't been. The fork-safety was implemented using a fork count, which was incremented by a pthread_atfork handler. Initially, this handler was enabled by default. Unfortunately, the default behaviour had to be changed for other reasons in commit b5319bdbd095, so the new OpenSSL CSPRNG failed to keep its promise. This commit restores the fork-safety using a different approach. It replaces the fork count by a fork id, which coincides with the process id on UNIX-like operating systems and is zero on other operating systems. It is used to detect when an automatic reseed after a fork is necessary. To prevent a future regression, it also adds a test to verify that the child reseeds after fork. CVE-2019-1549 Reviewed-by: Paul Dale <paul.dale@oracle.com> Reviewed-by: Matt Caswell <matt@openssl.org> (Merged from https://github.com/openssl/openssl/pull/9802)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: test_non_svg_element (void) { char *filename = get_test_filename ("335-non-svg-element.svg"); RsvgHandle *handle; GError *error = NULL; handle = rsvg_handle_new_from_file (filename, &error); g_free (filename); g_assert (handle == NULL); g_assert (g_error_matches (error, RSVG_ERROR, RSVG_ERROR_FAILED)); g_error_free (error); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '(#515) - Add a limit for the number of loaded elements This fixes the last part of #515, an enormous SVG file with millions of elements, which causes out-of-memory. To avoid unbounded memory consumption, we'll set a hard limit on the number of loaded elements. The largest legitimate file I have is a map rendering with about 26K elements; here we set a limit of 200,000 elements for good measure. Fixes https://gitlab.gnome.org/GNOME/librsvg/issues/515'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST_P(WasmTest, DivByZero) { Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); Upstream::MockClusterManager cluster_manager; Event::DispatcherPtr dispatcher(api->allocateDispatcher()); auto scope = Stats::ScopeSharedPtr(stats_store.createScope("wasm.")); NiceMock<LocalInfo::MockLocalInfo> local_info; auto name = ""; auto root_id = ""; auto vm_id = ""; auto vm_configuration = ""; auto plugin = std::make_shared<Extensions::Common::Wasm::Plugin>( name, root_id, vm_id, envoy::api::v2::core::TrafficDirection::UNSPECIFIED, local_info, nullptr); auto wasm = std::make_unique<Extensions::Common::Wasm::Wasm>( absl::StrCat("envoy.wasm.runtime.", GetParam()), vm_id, vm_configuration, plugin, scope, cluster_manager, *dispatcher); EXPECT_NE(wasm, nullptr); const auto code = TestEnvironment::readFileToStringForTest(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/wasm/test_data/segv_cpp.wasm")); EXPECT_FALSE(code.empty()); auto context = std::make_unique<TestContext>(wasm.get()); EXPECT_CALL(*context, scriptLog_(spdlog::level::err, Eq("before div by zero"))); EXPECT_TRUE(wasm->initialize(code, false)); wasm->setContext(context.get()); if (GetParam() == "v8") { EXPECT_THROW_WITH_MESSAGE( context->onLog(), Extensions::Common::Wasm::WasmException, "Function: proxy_onLog failed: Uncaught RuntimeError: divide by zero"); } else if (GetParam() == "wavm") { EXPECT_THROW_WITH_REGEX(context->onLog(), Extensions::Common::Wasm::WasmException, "Function: proxy_onLog failed: wavm.integerDivideByZeroOrOverflow.*"); } else { ASSERT_FALSE(true); // Neither of the above was matched. } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': '1.4 - Do not call into the VM unless the VM Context has been created. (#24) * Ensure that the in VM Context is created before onDone is called. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Update as per offline discussion. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Set in_vm_context_created_ in onNetworkNewConnection. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Add guards to other network calls. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Fix common/wasm tests. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Patch tests. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Remove unecessary file from cherry-pick. Signed-off-by: John Plevyak <jplevyak@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Http::FilterTrailersStatus Context::onResponseTrailers() { if (!wasm_->onResponseTrailers_) { return Http::FilterTrailersStatus::Continue; } if (wasm_->onResponseTrailers_(this, id_).u64_ == 0) { return Http::FilterTrailersStatus::Continue; } return Http::FilterTrailersStatus::StopIteration; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': '1.4 - Do not call into the VM unless the VM Context has been created. (#24) * Ensure that the in VM Context is created before onDone is called. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Update as per offline discussion. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Set in_vm_context_created_ in onNetworkNewConnection. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Add guards to other network calls. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Fix common/wasm tests. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Patch tests. Signed-off-by: John Plevyak <jplevyak@gmail.com> * Remove unecessary file from cherry-pick. Signed-off-by: John Plevyak <jplevyak@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: napi_status napi_get_value_string_utf8(napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result) { CHECK_ENV(env); CHECK_ARG(env, value); v8::Local<v8::Value> val = v8impl::V8LocalValueFromJsValue(value); RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected); if (!buf) { CHECK_ARG(env, result); *result = val.As<v8::String>()->Utf8Length(env->isolate); } else { int copied = val.As<v8::String>()->WriteUtf8( env->isolate, buf, bufsize - 1, nullptr, v8::String::REPLACE_INVALID_UTF8 | v8::String::NO_NULL_TERMINATION); buf[copied] = '\0'; if (result != nullptr) { *result = copied; } } return napi_clear_last_error(env); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-191'], 'message': 'napi: fix memory corruption vulnerability Fixes: https://hackerone.com/reports/784186 CVE-ID: CVE-2020-8174 PR-URL: https://github.com/nodejs-private/node-private/pull/195 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Gabriel Schulhof <gabriel.schulhof@intel.com> Reviewed-By: Michael Dawson <michael_dawson@ca.ibm.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ASN1_item_ex_i2d(const ASN1_VALUE **pval, unsigned char **out, const ASN1_ITEM *it, int tag, int aclass) { const ASN1_TEMPLATE *tt = NULL; int i, seqcontlen, seqlen, ndef = 1; const ASN1_EXTERN_FUNCS *ef; const ASN1_AUX *aux = it->funcs; ASN1_aux_const_cb *asn1_cb = NULL; if ((it->itype != ASN1_ITYPE_PRIMITIVE) && *pval == NULL) return 0; if (aux != NULL) { asn1_cb = ((aux->flags & ASN1_AFLG_CONST_CB) != 0) ? aux->asn1_const_cb : (ASN1_aux_const_cb *)aux->asn1_cb; /* backward compatibility */ } switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) return asn1_template_ex_i2d(pval, out, it->templates, tag, aclass); return asn1_i2d_ex_primitive(pval, out, it, tag, aclass); case ASN1_ITYPE_MSTRING: return asn1_i2d_ex_primitive(pval, out, it, -1, aclass); case ASN1_ITYPE_CHOICE: if (asn1_cb && !asn1_cb(ASN1_OP_I2D_PRE, pval, it, NULL)) return 0; i = asn1_get_choice_selector_const(pval, it); if ((i >= 0) && (i < it->tcount)) { const ASN1_VALUE **pchval; const ASN1_TEMPLATE *chtt; chtt = it->templates + i; pchval = asn1_get_const_field_ptr(pval, chtt); return asn1_template_ex_i2d(pchval, out, chtt, -1, aclass); } /* Fixme: error condition if selector out of range */ if (asn1_cb && !asn1_cb(ASN1_OP_I2D_POST, pval, it, NULL)) return 0; break; case ASN1_ITYPE_EXTERN: /* If new style i2d it does all the work */ ef = it->funcs; return ef->asn1_ex_i2d(pval, out, it, tag, aclass); case ASN1_ITYPE_NDEF_SEQUENCE: /* Use indefinite length constructed if requested */ if (aclass & ASN1_TFLG_NDEF) ndef = 2; /* fall through */ case ASN1_ITYPE_SEQUENCE: i = asn1_enc_restore(&seqcontlen, out, pval, it); /* An error occurred */ if (i < 0) return 0; /* We have a valid cached encoding... */ if (i > 0) return seqcontlen; /* Otherwise carry on */ seqcontlen = 0; /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */ if (tag == -1) { tag = V_ASN1_SEQUENCE; /* Retain any other flags in aclass */ aclass = (aclass & ~ASN1_TFLG_TAG_CLASS) | V_ASN1_UNIVERSAL; } if (asn1_cb && !asn1_cb(ASN1_OP_I2D_PRE, pval, it, NULL)) return 0; /* First work out sequence content length */ for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) { const ASN1_TEMPLATE *seqtt; const ASN1_VALUE **pseqval; int tmplen; seqtt = asn1_do_adb(*pval, tt, 1); if (!seqtt) return 0; pseqval = asn1_get_const_field_ptr(pval, seqtt); tmplen = asn1_template_ex_i2d(pseqval, NULL, seqtt, -1, aclass); if (tmplen == -1 || (tmplen > INT_MAX - seqcontlen)) return -1; seqcontlen += tmplen; } seqlen = ASN1_object_size(ndef, seqcontlen, tag); if (!out || seqlen == -1) return seqlen; /* Output SEQUENCE header */ ASN1_put_object(out, ndef, seqcontlen, tag, aclass); for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) { const ASN1_TEMPLATE *seqtt; const ASN1_VALUE **pseqval; seqtt = asn1_do_adb(*pval, tt, 1); if (!seqtt) return 0; pseqval = asn1_get_const_field_ptr(pval, seqtt); /* FIXME: check for errors in enhanced version */ asn1_template_ex_i2d(pseqval, out, seqtt, -1, aclass); } if (ndef == 2) ASN1_put_eoc(out); if (asn1_cb && !asn1_cb(ASN1_OP_I2D_POST, pval, it, NULL)) return 0; return seqlen; default: return 0; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Complain if we are attempting to encode with an invalid ASN.1 template It never makes sense for multi-string or CHOICE types to have implicit tagging. If we have a template that uses the in this way then we should immediately fail. Thanks to David Benjamin from Google for reporting this issue. Reviewed-by: Tomas Mraz <tmraz@fedoraproject.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void part_write_body(const struct message_part *part, string_t *str, bool extended) { const struct message_part_data *data = part->data; bool text; i_assert(part->data != NULL); if ((part->flags & MESSAGE_PART_FLAG_MESSAGE_RFC822) != 0) { str_append(str, "\"message\" \"rfc822\""); text = FALSE; } else { /* "content type" "subtype" */ if (data->content_type == NULL) { text = TRUE; str_append(str, "\"text\" \"plain\""); } else { text = (strcasecmp(data->content_type, "text") == 0); imap_append_string(str, data->content_type); str_append_c(str, ' '); imap_append_string(str, data->content_subtype); } } /* ("content type param key" "value" ...) */ str_append_c(str, ' '); params_write(data->content_type_params, data->content_type_params_count, str, text); str_append_c(str, ' '); imap_append_nstring_nolf(str, data->content_id); str_append_c(str, ' '); imap_append_nstring_nolf(str, data->content_description); str_append_c(str, ' '); if (data->content_transfer_encoding != NULL) imap_append_string(str, data->content_transfer_encoding); else str_append(str, "\"7bit\""); str_printfa(str, " %"PRIuUOFF_T, part->body_size.virtual_size); if (text) { /* text/.. contains line count */ str_printfa(str, " %u", part->body_size.lines); } else if ((part->flags & MESSAGE_PART_FLAG_MESSAGE_RFC822) != 0) { /* message/rfc822 contains envelope + body + line count */ const struct message_part_data *child_data; i_assert(part->children != NULL); i_assert(part->children->next == NULL); child_data = part->children->data; str_append(str, " ("); imap_envelope_write(child_data->envelope, str); str_append(str, ") "); part_write_bodystructure_siblings(part->children, str, extended); str_printfa(str, " %u", part->body_size.lines); } if (!extended) return; /* BODYSTRUCTURE data */ /* "md5" ("content disposition" ("disposition" "params")) ("body" "language" "params") "location" */ str_append_c(str, ' '); imap_append_nstring_nolf(str, data->content_md5); part_write_bodystructure_common(data, str); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'lib-imap: Don't generate invalid BODYSTRUCTURE when reaching MIME part limit If the last MIME part was message/rfc822 and its child was truncated away, BODYSTRUCTURE was missing the ENVELOPE and BODY[STRUCTURE] parts. Fixed by writing empty dummy ones.'</s>
<s>[INST] Given the following code containing errors, provide 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 StreamBase::WriteString(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); CHECK(args[0]->IsObject()); CHECK(args[1]->IsString()); Local<Object> req_wrap_obj = args[0].As<Object>(); Local<String> string = args[1].As<String>(); Local<Object> send_handle_obj; if (args[2]->IsObject()) send_handle_obj = args[2].As<Object>(); // Compute the size of the storage that the string will be flattened into. // For UTF8 strings that are very long, go ahead and take the hit for // computing their actual size, rather than tripling the storage. size_t storage_size; if (enc == UTF8 && string->Length() > 65535 && !StringBytes::Size(env->isolate(), string, enc).To(&storage_size)) return 0; else if (!StringBytes::StorageSize(env->isolate(), string, enc) .To(&storage_size)) return 0; if (storage_size > INT_MAX) return UV_ENOBUFS; // Try writing immediately if write size isn't too big char stack_storage[16384]; // 16kb size_t data_size; size_t synchronously_written = 0; uv_buf_t buf; bool try_write = storage_size <= sizeof(stack_storage) && (!IsIPCPipe() || send_handle_obj.IsEmpty()); if (try_write) { data_size = StringBytes::Write(env->isolate(), stack_storage, storage_size, string, enc); buf = uv_buf_init(stack_storage, data_size); uv_buf_t* bufs = &buf; size_t count = 1; const int err = DoTryWrite(&bufs, &count); // Keep track of the bytes written here, because we're taking a shortcut // by using `DoTryWrite()` directly instead of using the utilities // provided by `Write()`. synchronously_written = count == 0 ? data_size : data_size - buf.len; bytes_written_ += synchronously_written; // Immediate failure or success if (err != 0 || count == 0) { SetWriteResult(StreamWriteResult { false, err, nullptr, data_size }); return err; } // Partial write CHECK_EQ(count, 1); } AllocatedBuffer data; if (try_write) { // Copy partial data data = AllocatedBuffer::AllocateManaged(env, buf.len); memcpy(data.data(), buf.base, buf.len); data_size = buf.len; } else { // Write it data = AllocatedBuffer::AllocateManaged(env, storage_size); data_size = StringBytes::Write(env->isolate(), data.data(), storage_size, string, enc); } CHECK_LE(data_size, storage_size); buf = uv_buf_init(data.data(), data_size); uv_stream_t* send_handle = nullptr; if (IsIPCPipe() && !send_handle_obj.IsEmpty()) { HandleWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, send_handle_obj, UV_EINVAL); send_handle = reinterpret_cast<uv_stream_t*>(wrap->GetHandle()); // Reference LibuvStreamWrap instance to prevent it from being garbage // collected before `AfterWrite` is called. req_wrap_obj->Set(env->context(), env->handle_string(), send_handle_obj).Check(); } StreamWriteResult res = Write(&buf, 1, send_handle, req_wrap_obj); res.bytes += synchronously_written; SetWriteResult(res); if (res.wrap != nullptr) { res.wrap->SetAllocatedStorage(std::move(data)); } return res.err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'src: retain pointers to WriteWrap/ShutdownWrap Avoids potential use-after-free when wrap req's are synchronously destroyed. CVE-ID: CVE-2020-8265 Fixes: https://github.com/nodejs-private/node-private/issues/227 Refs: https://hackerone.com/bugs?subject=nodejs&report_id=988103 PR-URL: https://github.com/nodejs-private/node-private/pull/23 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int evp_EncryptDecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int i, j, bl, cmpl = inl; if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS)) cmpl = (cmpl + 7) / 8; bl = ctx->cipher->block_size; /* * CCM mode needs to know about the case where inl == 0 && in == NULL - it * means the plaintext/ciphertext length is 0 */ if (inl < 0 || (inl == 0 && EVP_CIPHER_mode(ctx->cipher) != EVP_CIPH_CCM_MODE)) { *outl = 0; return inl == 0; } if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { /* If block size > 1 then the cipher will have to do this check */ if (bl == 1 && is_partially_overlapping(out, in, cmpl)) { EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING); return 0; } i = ctx->cipher->do_cipher(ctx, out, in, inl); if (i < 0) return 0; else *outl = i; return 1; } if (is_partially_overlapping(out + ctx->buf_len, in, cmpl)) { EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING); return 0; } if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) { if (ctx->cipher->do_cipher(ctx, out, in, inl)) { *outl = inl; return 1; } else { *outl = 0; return 0; } } i = ctx->buf_len; OPENSSL_assert(bl <= (int)sizeof(ctx->buf)); if (i != 0) { if (bl - i > inl) { memcpy(&(ctx->buf[i]), in, inl); ctx->buf_len += inl; *outl = 0; return 1; } else { j = bl - i; memcpy(&(ctx->buf[i]), in, j); inl -= j; in += j; if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl)) return 0; out += bl; *outl = bl; } } else *outl = 0; i = inl & (bl - 1); inl -= i; if (inl > 0) { if (!ctx->cipher->do_cipher(ctx, out, in, inl)) return 0; *outl += inl; } if (i != 0) memcpy(ctx->buf, &(in[inl]), i); ctx->buf_len = i; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Don't overflow the output length in EVP_CipherUpdate calls CVE-2021-23840 Reviewed-by: Paul Dale <pauli@openssl.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 main(int argc, char **argv) { int fd; int ret; /* Create a temporary raw image */ fd = mkstemp(test_image); g_assert(fd >= 0); ret = ftruncate(fd, TEST_IMAGE_SIZE); g_assert(ret == 0); close(fd); /* Run the tests */ g_test_init(&argc, &argv, NULL); qtest_start("-machine pc -device floppy,id=floppy0"); qtest_irq_intercept_in(global_qtest, "ioapic"); qtest_add_func("/fdc/cmos", test_cmos); qtest_add_func("/fdc/no_media_on_start", test_no_media_on_start); qtest_add_func("/fdc/read_without_media", test_read_without_media); qtest_add_func("/fdc/media_change", test_media_change); qtest_add_func("/fdc/sense_interrupt", test_sense_interrupt); qtest_add_func("/fdc/relative_seek", test_relative_seek); qtest_add_func("/fdc/read_id", test_read_id); qtest_add_func("/fdc/verify", test_verify); qtest_add_func("/fdc/media_insert", test_media_insert); qtest_add_func("/fdc/read_no_dma_1", test_read_no_dma_1); qtest_add_func("/fdc/read_no_dma_18", test_read_no_dma_18); qtest_add_func("/fdc/read_no_dma_19", test_read_no_dma_19); qtest_add_func("/fdc/fuzz-registers", fuzz_registers); qtest_add_func("/fdc/fuzz/cve_2021_20196", test_cve_2021_20196); ret = g_test_run(); /* Cleanup */ qtest_end(); unlink(test_image); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tests/qtest/fdc-test: Add a regression test for CVE-2021-3507 Add the reproducer from https://gitlab.com/qemu-project/qemu/-/issues/339 Without the previous commit, when running 'make check-qtest-i386' with QEMU configured with '--enable-sanitizers' we get: ==4028352==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x619000062a00 at pc 0x5626d03c491a bp 0x7ffdb4199410 sp 0x7ffdb4198bc0 READ of size 786432 at 0x619000062a00 thread T0 #0 0x5626d03c4919 in __asan_memcpy (qemu-system-i386+0x1e65919) #1 0x5626d1c023cc in flatview_write_continue softmmu/physmem.c:2787:13 #2 0x5626d1bf0c0f in flatview_write softmmu/physmem.c:2822:14 #3 0x5626d1bf0798 in address_space_write softmmu/physmem.c:2914:18 #4 0x5626d1bf0f37 in address_space_rw softmmu/physmem.c:2924:16 #5 0x5626d1bf14c8 in cpu_physical_memory_rw softmmu/physmem.c:2933:5 #6 0x5626d0bd5649 in cpu_physical_memory_write include/exec/cpu-common.h:82:5 #7 0x5626d0bd0a07 in i8257_dma_write_memory hw/dma/i8257.c:452:9 #8 0x5626d09f825d in fdctrl_transfer_handler hw/block/fdc.c:1616:13 #9 0x5626d0a048b4 in fdctrl_start_transfer hw/block/fdc.c:1539:13 #10 0x5626d09f4c3e in fdctrl_write_data hw/block/fdc.c:2266:13 #11 0x5626d09f22f7 in fdctrl_write hw/block/fdc.c:829:9 #12 0x5626d1c20bc5 in portio_write softmmu/ioport.c:207:17 0x619000062a00 is located 0 bytes to the right of 512-byte region [0x619000062800,0x619000062a00) allocated by thread T0 here: #0 0x5626d03c66ec in posix_memalign (qemu-system-i386+0x1e676ec) #1 0x5626d2b988d4 in qemu_try_memalign util/oslib-posix.c:210:11 #2 0x5626d2b98b0c in qemu_memalign util/oslib-posix.c:226:27 #3 0x5626d09fbaf0 in fdctrl_realize_common hw/block/fdc.c:2341:20 #4 0x5626d0a150ed in isabus_fdc_realize hw/block/fdc-isa.c:113:5 #5 0x5626d2367935 in device_set_realized hw/core/qdev.c:531:13 SUMMARY: AddressSanitizer: heap-buffer-overflow (qemu-system-i386+0x1e65919) in __asan_memcpy Shadow bytes around the buggy address: 0x0c32800044f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c3280004500: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x0c3280004510: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x0c3280004520: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x0c3280004530: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 =>0x0c3280004540:[fa]fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c3280004550: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c3280004560: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c3280004570: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c3280004580: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x0c3280004590: fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd fd Shadow byte legend (one shadow byte represents 8 application bytes): Addressable: 00 Heap left redzone: fa Freed heap region: fd ==4028352==ABORTING [ kwolf: Added snapshot=on to prevent write file lock failure ] Reported-by: Alexander Bulekov <alxndr@bu.edu> Signed-off-by: Philippe Mathieu-Daudé <philmd@redhat.com> Reviewed-by: Alexander Bulekov <alxndr@bu.edu> Signed-off-by: Kevin Wolf <kwolf@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: create_jwt_token_fields(const char *algo, time_t exp, time_t iat, time_t nbf, ARRAY_TYPE(oauth2_field) *fields) { const struct oauth2_field *field; buffer_t *tokenbuf = t_buffer_create(64); base64url_encode_str( t_strdup_printf("{\"alg\":\"%s\",\"typ\":\"JWT\"}", algo), tokenbuf); buffer_append(tokenbuf, ".", 1); string_t *bodybuf = t_str_new(64); str_append_c(bodybuf, '{'); if (exp > 0) { append_key_value(bodybuf, "exp", dec2str(exp), FALSE); } if (iat > 0) { if (exp > 0) str_append_c(bodybuf, ','); append_key_value(bodybuf, "iat", dec2str(iat), FALSE); } if (nbf > 0) { if (exp > 0 || iat > 0) str_append_c(bodybuf, ','); append_key_value(bodybuf, "nbf", dec2str(nbf), FALSE); } array_foreach(fields, field) { if (str_data(bodybuf)[bodybuf->used-1] != '{') str_append_c(bodybuf, ','); append_key_value(bodybuf, field->name, field->value, TRUE); } str_append_c(bodybuf, '}'); base64url_encode_str(str_c(bodybuf), tokenbuf); return tokenbuf; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'lib-oauth2: Add test for token escape'</s>
<s>[INST] Given the following code containing errors, provide 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 test_sm2_crypt(const EC_GROUP *group, const EVP_MD *digest, const char *privkey_hex, const char *message, const char *k_hex, const char *ctext_hex) { const size_t msg_len = strlen(message); BIGNUM *priv = NULL; EC_KEY *key = NULL; EC_POINT *pt = NULL; unsigned char *expected = OPENSSL_hexstr2buf(ctext_hex, NULL); size_t ctext_len = 0; size_t ptext_len = 0; uint8_t *ctext = NULL; uint8_t *recovered = NULL; size_t recovered_len = msg_len; int rc = 0; if (!TEST_ptr(expected) || !TEST_true(BN_hex2bn(&priv, privkey_hex))) goto done; key = EC_KEY_new(); if (!TEST_ptr(key) || !TEST_true(EC_KEY_set_group(key, group)) || !TEST_true(EC_KEY_set_private_key(key, priv))) goto done; pt = EC_POINT_new(group); if (!TEST_ptr(pt) || !TEST_true(EC_POINT_mul(group, pt, priv, NULL, NULL, NULL)) || !TEST_true(EC_KEY_set_public_key(key, pt)) || !TEST_true(sm2_ciphertext_size(key, digest, msg_len, &ctext_len))) goto done; ctext = OPENSSL_zalloc(ctext_len); if (!TEST_ptr(ctext)) goto done; start_fake_rand(k_hex); if (!TEST_true(sm2_encrypt(key, digest, (const uint8_t *)message, msg_len, ctext, &ctext_len))) { restore_rand(); goto done; } restore_rand(); if (!TEST_mem_eq(ctext, ctext_len, expected, ctext_len)) goto done; if (!TEST_true(sm2_plaintext_size(key, digest, ctext_len, &ptext_len)) || !TEST_int_eq(ptext_len, msg_len)) goto done; recovered = OPENSSL_zalloc(ptext_len); if (!TEST_ptr(recovered) || !TEST_true(sm2_decrypt(key, digest, ctext, ctext_len, recovered, &recovered_len)) || !TEST_int_eq(recovered_len, msg_len) || !TEST_mem_eq(recovered, recovered_len, message, msg_len)) goto done; rc = 1; done: BN_free(priv); EC_POINT_free(pt); OPENSSL_free(ctext); OPENSSL_free(recovered); OPENSSL_free(expected); EC_KEY_free(key); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'Correctly calculate the length of SM2 plaintext given the ciphertext Previously the length of the SM2 plaintext could be incorrectly calculated. The plaintext length was calculated by taking the ciphertext length and taking off an "overhead" value. The overhead value was assumed to have a "fixed" element of 10 bytes. This is incorrect since in some circumstances it can be more than 10 bytes. Additionally the overhead included the length of two integers C1x and C1y, which were assumed to be the same length as the field size (32 bytes for the SM2 curve). However in some cases these integers can have an additional padding byte when the msb is set, to disambiguate them from negative integers. Additionally the integers can also be less than 32 bytes in length in some cases. If the calculated overhead is incorrect and larger than the actual value this can result in the calculated plaintext length being too small. Applications are likely to allocate buffer sizes based on this and therefore a buffer overrun can occur. CVE-2021-3711 Issue reported by John Ouyang. Reviewed-by: Paul Dale <pauli@openssl.org> Reviewed-by: Nicola Tuveri <nic.tuv@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int cn2dnsid(ASN1_STRING *cn, unsigned char **dnsid, size_t *idlen) { int utf8_length; unsigned char *utf8_value; int i; int isdnsname = 0; /* Don't leave outputs uninitialized */ *dnsid = NULL; *idlen = 0; /*- * Per RFC 6125, DNS-IDs representing internationalized domain names appear * in certificates in A-label encoded form: * * https://tools.ietf.org/html/rfc6125#section-6.4.2 * * The same applies to CNs which are intended to represent DNS names. * However, while in the SAN DNS-IDs are IA5Strings, as CNs they may be * needlessly encoded in 16-bit Unicode. We perform a conversion to UTF-8 * to ensure that we get an ASCII representation of any CNs that are * representable as ASCII, but just not encoded as ASCII. The UTF-8 form * may contain some non-ASCII octets, and that's fine, such CNs are not * valid legacy DNS names. * * Note, 'int' is the return type of ASN1_STRING_to_UTF8() so that's what * we must use for 'utf8_length'. */ if ((utf8_length = ASN1_STRING_to_UTF8(&utf8_value, cn)) < 0) return X509_V_ERR_OUT_OF_MEM; /* * Some certificates have had names that include a *trailing* NUL byte. * Remove these harmless NUL characters. They would otherwise yield false * alarms with the following embedded NUL check. */ while (utf8_length > 0 && utf8_value[utf8_length - 1] == '\0') --utf8_length; /* Reject *embedded* NULs */ if ((size_t)utf8_length != strlen((char *)utf8_value)) { OPENSSL_free(utf8_value); return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX; } /* * XXX: Deviation from strict DNS name syntax, also check names with '_' * Check DNS name syntax, any '-' or '.' must be internal, * and on either side of each '.' we can't have a '-' or '.'. * * If the name has just one label, we don't consider it a DNS name. This * means that "CN=sometld" cannot be precluded by DNS name constraints, but * that is not a problem. */ for (i = 0; i < utf8_length; ++i) { unsigned char c = utf8_value[i]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') continue; /* Dot and hyphen cannot be first or last. */ if (i > 0 && i < utf8_length - 1) { if (c == '-') continue; /* * Next to a dot the preceding and following characters must not be * another dot or a hyphen. Otherwise, record that the name is * plausible, since it has two or more labels. */ if (c == '.' && utf8_value[i + 1] != '.' && utf8_value[i - 1] != '-' && utf8_value[i + 1] != '-') { isdnsname = 1; continue; } } isdnsname = 0; break; } if (isdnsname) { *dnsid = utf8_value; *idlen = (size_t)utf8_length; return X509_V_OK; } OPENSSL_free(utf8_value); return X509_V_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix the name constraints code to not assume NUL terminated strings ASN.1 strings may not be NUL terminated. Don't assume they are. CVE-2021-3712 Reviewed-by: Viktor Dukhovni <viktor@openssl.org> Reviewed-by: Paul Dale <pauli@openssl.org>'</s>